MLCrack

    CLASSICAL ML Β· INTERVIEW QUESTION

    Compare K-Means, DBSCAN, and hierarchical clustering. When would you use each?

    🟑 intermediate · Unsupervised Learning

    Hint: Think about cluster shape assumptions, scalability, and hyperparameters.

    Answer

    Clustering algorithms differ in their assumptions about cluster shape, scalability, and hyperparameters.

    Comparison

    AlgorithmCluster ShapeNeeds K?Handles OutliersComplexity
    K-MeansRoughly sphericalβœ… Yes❌ NoO(tnkd)O(tnkd) for t Lloyd iterations
    DBSCANDensity-connected❌ Noβœ… YesO(n2)O(n^2) worst case; faster with effective spatial indexing
    HierarchicalLinkage-dependent❌ No❌ NoLinkage/implementation-dependent; often quadratic memory

    K-Means

    Assumes spherical clusters, sensitive to initialization (use k-means++). Best for large datasets with roughly equal-sized clusters.

    DBSCAN

    Density-based β€” finds clusters of arbitrary shape. Requires Ο΅\epsilon (neighborhood radius) and minPts\text{minPts}. Naturally handles outliers as noise points.

    Hierarchical

    Produces dendrograms, captures multi-scale structure. No K needed upfront but O(n2)O(n^2) memory.

    python
    from sklearn.cluster import KMeans, DBSCAN # K-Means kmeans = KMeans(n_clusters=5, init='k-means++', n_init=10) labels_km = kmeans.fit_predict(X) # DBSCAN db = DBSCAN(eps=0.5, min_samples=5) labels_db = db.fit_predict(X)

    Also consider GMMs for soft clustering and spectral clustering for non-convex shapes.