The spectral clustering algorithm in the Dlib library is implemented in the spectral_cluster function. It takes the distance function object, the training dataset, and the number of clusters as parameters. As a result, it returns a container with cluster indices, which have the same ordering as the input data. In the following sample, the object of the knn_kernel type is used as a distance function. You will find its implementation in the samples provided with the book. This knn_kernel distance function object estimates the first k-nearest neighbor (KNN) objects to the given one. These objects are determined with the KNN algorithm, which uses the Euclidean distance for the distance measure, as follows:
typedef matrix<double, 2, 1> sample_type;
typedef knn_kernel<sample_type> kernel_type;
...
std::vector<sample_type> samples;
...
std::vector<unsigned long> clusters =
spectral_cluster(kernel_type(samples, 15), samples, num_clusters);
The spectral_cluster() function call filled the clusters object with cluster index values, which we can use to visualize the clustering result, as illustrated in the following screenshot:
In the preceding screenshot, we can see how the spectral clustering algorithm implemented in the Dlib library works on different artificial datasets.