Clustering

suggest change

Clustering groups similar objects. It is unsupervised learning, so there are no labels to train on. PHP-ML includes these algorithms:

k-Means

k-Means separates the data into n groups of equal variance. This means that we need to pass in a number n which would be the number of clusters we need in our solution. The following code will help bring more clarity

// Our data set
$samples = [[1, 1], [8, 7], [1, 2], [7, 8], [2, 1], [8, 9]];

// Initialize clustering with parameter `n`
$kmeans = new KMeans(3);
$clustered = $kmeans->cluster($samples);

The result has 3 groups because n was 3. Membership depends on initialization, so do not rely on a fixed order. For this data, the points near (1, 1) separate from the points near (8, 8). The constructor also accepts an initialization method:

$kmeans = new KMeans(4, KMeans::INIT_RANDOM);

INIT_RANDOM places a completely random centroid while trying to determine the clusters. But just to avoid the centroid being too far away from the data, it is bound by the space boundaries of data.

The default constructor initialization method is kmeans++ which selects centroid in a smart way to speed up the process.

DBSCAN

As opposed to KMeans, DBSCAN is a density based clustering algorithm which means that we would not be passing n which would determine the number of clusters we want in our result. On the other hand this requires two parameters to work

  1. $minSamples : The minimum number of objects that should be present in a cluster
  2. $epsilon : Which is the maximum distance between two samples for them to be considered as in the same cluster.

A quick sample for the same is as follows

// Our sample data set
$samples = [[1, 1], [8, 7], [1, 2], [7, 8], [2, 1], [8, 9]];

$dbscan = new DBSCAN($epsilon = 2, $minSamples = 3);
$dbscan->cluster($samples);

With these inputs, the three points near (1, 1) are within distance 2 of each other, and so are the three points near (8, 8), so you get two clusters. Unlike k-means, the number of clusters is not chosen in advance.

Practical Case

Here is a real-world sketch:

Clustering is used in pattern recognition and data mining. A publishing app might treat "spent more than a minute and scrolled to the bottom" as interest. Cluster users by the content ids they engage with. People in the same cluster tend to like similar articles, which is a simple recommendation signal.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents