DBSCAN
Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 20 of 51.
This chapter finds crowds of any shape, and the points that belong to none. By its end, you map a valley's lights:
First, the seals' sandbars that broke k-means in When K-Means Fails. DBSCAN follows the crowds instead:
A point with min_samples points (itself included) within eps, the circle's radius, sits in a crowd. Crowds spread through such points. No k to choose:
from sklearn.cluster import DBSCAN
labels = DBSCAN(eps=0.2, min_samples=5).fit_predict(X)
print(labels.max() + 1)This prints 2: crowds are numbered from 0, so the largest plus one counts them.
Challenge
MediumOn a frozen lake, skaters race along a track that winds between two islands, and a crowd watches a hockey game. k-means would cut the track into pieces. The program reads eps in meters.
- Fit DBSCAN with that eps and
min_samples=5; keep the crowds inlabels. - Print how many crowds it found.
- Draw them with
draw_crowds(ax, X, labels)and show.
For another lake and eps 3.5:
Crowds found: 3Coddy describes your chart. Then run it with eps 8: where did the crowds go?
Try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
# Where 170 skaters stood on the frozen lake, in meters
skaters = pd.read_csv("skaters.csv")
X = np.column_stack([skaters["x_m"], skaters["y_m"]])
eps = float(input())
# Draws each crowd in its own color, labelled with its size
def draw_crowds(ax, X, labels):
for crowd in range(labels.max() + 1):
rows = labels == crowd
ax.scatter(X[rows, 0], X[rows, 1], s=14, label=f"{rows.sum()} skaters")
ax.legend()
fig, ax = plt.subplots()
ax.set_title("Skaters on the Lake")
ax.set_xlabel("East (m)")
ax.set_ylabel("North (m)")
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unsupervised Learning
1Finding Groups
Learning Without LabelsMeasuring SimilarityK-Means by HandK-Means in scikit-learnRecap: Gym Members7PCA in Practice
Seeing 64 DimensionsComponents as PatternsCompress and RebuildPCA Before a ModelRecap: Face Scanner10Project: Digit Explorer
Look at the DigitsShrink with PCACluster the DigitsName the ClustersFind the Odd OnesPractice on your own: Online Python compiler