\section{Introduction}\label{kmtutorial_intro_kmtut}
The popular k-\/means algorithm for clustering has been around since the late 1950s, and the standard algorithm was proposed by Stuart Lloyd in 1957. Given a set of points $ X $, k-\/means clustering aims to partition each point $ x_i $ into a cluster $ c_j $ (where $ j \le k $ and $ k $, the number of clusters, is a parameter). The partitioning is done to minimize the objective function

\[ \sum_{j = 1}^{k} \sum_{x_i \in c_j} \| x_i - \mu_j \|^2 \]

where $\mu_j$ is the centroid of cluster $c_j$. The standard algorithm is a two-\/step algorithm\+:


\begin{DoxyItemize}
\item {\bfseries Assignment} {\bfseries step}. Each point $x_i$ in $X$ is assigned to the cluster whose centroid it is closest to.
\item {\bfseries Update} {\bfseries step}. Using the new cluster assignments, the centroids of each cluster are recalculated.
\end{DoxyItemize}

The algorithm has converged when no more assignment changes are happening with each iteration. However, this algorithm can get stuck in local minima of the objective function and is particularly sensitive to the initial cluster assignments. Also, situations can arise where the algorithm will never converge but reaches steady state -- for instance, one point may be changing between two cluster assignments.

There is vast literature on the k-\/means algorithm and its uses, as well as strategies for choosing initial points effectively and keeping the algorithm from converging in local minima. {\bfseries mlpack} does implement some of these, notably the Bradley-\/\+Fayyad algorithm (see the reference below) for choosing refined initial points. Importantly, the C++ {\ttfamily K\+Means} class makes it very easy to improve the k-\/means algorithm in a modular way.


\begin{DoxyCode}
@inproceedings\{bradley1998refining,
  title=\{Refining initial points \textcolor{keywordflow}{for} k-means clustering\},
  author=\{Bradley, Paul S. and Fayyad, Usama M.\},
  booktitle=\{Proceedings of the Fifteenth International Conference on Machine
      Learning (ICML 1998)\},
  volume=\{66\},
  year=\{1998\}
\}
\end{DoxyCode}


{\bfseries mlpack} provides\+:


\begin{DoxyItemize}
\item a \doxyref{simple command-\/line executable}{p.}{kmtutorial_cli_kmtut} to run k-\/means
\item a \doxyref{simple C++ interface}{p.}{kmtutorial_kmeans_kmtut} to run k-\/means
\item a \doxyref{generic, extensible, and powerful C++ class}{p.}{kmtutorial_kmeans_template_kmtut} for complex usage
\end{DoxyItemize}\section{Table of Contents}\label{kmtutorial_toc_kmtut}
A list of all the sections this tutorial contains.


\begin{DoxyItemize}
\item \doxyref{Introduction}{p.}{kmtutorial_intro_kmtut}
\item \doxyref{Table of Contents}{p.}{kmtutorial_toc_kmtut}
\item \doxyref{Command-\/\+Line \textquotesingle{}kmeans\textquotesingle{}}{p.}{kmtutorial_cli_kmtut}
\begin{DoxyItemize}
\item \doxyref{Simple k-\/means clustering}{p.}{kmtutorial_cli_ex1_kmtut}
\item \doxyref{Saving the resulting centroids}{p.}{kmtutorial_cli_ex2_kmtut}
\item \doxyref{Allowing empty clusters}{p.}{kmtutorial_cli_ex3_kmtut}
\item \doxyref{Limiting the maximum number of iterations}{p.}{kmtutorial_cli_ex4_kmtut}
\item \doxyref{Using Bradley-\/\+Fayyad \char`\"{}refined start\char`\"{}}{p.}{kmtutorial_cli_ex6_kmtut}
\item \doxyref{Using different k-\/means algorithms}{p.}{kmtutorial_cli_ex7_kmtut}
\end{DoxyItemize}
\item \doxyref{The \textquotesingle{}K\+Means\textquotesingle{} class}{p.}{kmtutorial_kmeans_kmtut}
\begin{DoxyItemize}
\item \doxyref{Running k-\/means and getting cluster assignments}{p.}{kmtutorial_kmeans_ex1_kmtut}
\item \doxyref{Running k-\/means and getting centroids of clusters}{p.}{kmtutorial_kmeans_ex2_kmtut}
\item \doxyref{Limiting the maximum number of iterations}{p.}{kmtutorial_kmeans_ex3_kmtut}
\item \doxyref{Setting initial cluster assignments}{p.}{kmtutorial_kmeans_ex5_kmtut}
\item \doxyref{Setting initial cluster centroids}{p.}{kmtutorial_kmeans_ex6_kmtut}
\item \doxyref{Running sparse k-\/means}{p.}{kmtutorial_kmeans_ex7_kmtut}
\end{DoxyItemize}
\item \doxyref{Template parameters for the \textquotesingle{}K\+Means\textquotesingle{} class}{p.}{kmtutorial_kmeans_template_kmtut}
\begin{DoxyItemize}
\item \doxyref{Changing the distance metric used for k-\/means}{p.}{kmtutorial_kmeans_metric_kmtut}
\item \doxyref{Changing the initial partitioning strategy used for k-\/means}{p.}{kmtutorial_kmeans_initial_partition_kmtut}
\item \doxyref{Changing the action taken when an empty cluster is encountered}{p.}{kmtutorial_kmeans_empty_cluster_kmtut}
\item \doxyref{The Lloyd\+Step\+Type template parameter}{p.}{kmtutorial_kmeans_lloyd_kmtut}
\end{DoxyItemize}
\item \doxyref{Further documentation}{p.}{kmtutorial_further_doc_kmtut}
\end{DoxyItemize}\section{Command-\/\+Line \textquotesingle{}kmeans\textquotesingle{}}\label{kmtutorial_cli_kmtut}
{\bfseries mlpack} provides a command-\/line executable, {\ttfamily mlpack\+\_\+kmeans}, to allow easy execution of the k-\/means algorithm on data. Complete documentation of the executable can be found by typing


\begin{DoxyCode}
$ mlpack\_kmeans --help
\end{DoxyCode}


As of October 2014, support for overclustering has been removed due to bugs and lack of usage. If this is support you were using, or are interested, please file a bug or get in touch with the {\bfseries mlpack} developers in some way so that the support can be re-\/implemented.

Below are several examples demonstrating simple use of the {\ttfamily mlpack\+\_\+kmeans} executable.\subsection{Simple k-\/means clustering}\label{kmtutorial_cli_ex1_kmtut}
We want to find 5 clusters using the points in the file dataset.\+csv. By default, if any of the clusters end up empty, that cluster will be reinitialized to contain the point furthest from the cluster with maximum variance. The cluster assignments of each point will be stored in assignments.\+csv. Each row in assignments.\+csv will correspond to the row in dataset.\+csv.


\begin{DoxyCode}
$ mlpack\_kmeans -c 5 -i dataset.csv -v -o assignments.csv
\end{DoxyCode}
\subsection{Saving the resulting centroids}\label{kmtutorial_cli_ex2_kmtut}
Sometimes it is useful to save the centroids of the clusters found by k-\/means; one example might be for plotting the points. The {\ttfamily -\/C} ({\ttfamily --centroid\+\_\+file}) option allows specification of a file into which the centroids will be saved (one centroid per line, if it is a C\+SV or other text format).


\begin{DoxyCode}
$ mlpack\_kmeans -c 5 -i dataset.csv -v -o assignments.csv -C centroids.csv
\end{DoxyCode}
\subsection{Allowing empty clusters}\label{kmtutorial_cli_ex3_kmtut}
If you would like to allow empty clusters to exist, instead of reinitializing them, simply specify the {\ttfamily -\/e} ({\ttfamily --allow\+\_\+empty\+\_\+clusters}) option. Note that when you save your clusters, even empty clusters will still have centroids. The centroids of the empty cluster will be the same as what they were on the last iteration when the cluster was not empty.


\begin{DoxyCode}
$ mlpack\_kmeans -c 5 -i dataset.csv -v -e -o assignments.csv -C centroids.csv
\end{DoxyCode}
\subsection{Allowing empty clusters}\label{kmtutorial_cli_ex3_kmtut}
If you would like to kill empty clusters , instead of reinitializing them, simply specify the {\ttfamily -\/E} ({\ttfamily --kill\+\_\+empty\+\_\+clusters}) option. Note that when you save your clusters, all the empty clusters will be removed and the final result may contain less than specified number of clusters.


\begin{DoxyCode}
$ mlpack\_kmeans -c 5 -i dataset.csv -v -E -o assignments.csv -C centroids.csv
\end{DoxyCode}
\subsection{Limiting the maximum number of iterations}\label{kmtutorial_cli_ex4_kmtut}
As mentioned earlier, the k-\/means algorithm can often fail to converge. In such a situation, it may be useful to stop the algorithm by way of limiting the maximum number of iterations. This can be done with the {\ttfamily -\/m} ({\ttfamily --max\+\_\+iterations}) parameter, which is set to 1000 by default. If the maximum number of iterations is 0, the algorithm will run until convergence -- or potentially forever. The example below sets a maximum of 250 iterations.


\begin{DoxyCode}
$ mlpack\_kmeans -c 5 -i dataset.csv -v -o assignments.csv -m 250
\end{DoxyCode}
\subsection{Using Bradley-\/\+Fayyad \char`\"{}refined start\char`\"{}}\label{kmtutorial_cli_ex6_kmtut}
The method proposed by Bradley and Fayyad in their paper \char`\"{}\+Refining initial
points for k-\/means clustering\char`\"{} is implemented in {\bfseries mlpack}. This strategy samples points from the dataset and runs k-\/means clustering on those points multiple times, saving the resulting clusters. Then, k-\/means clustering is run on those clusters, yielding the original number of clusters. The centroids of those resulting clusters are used as initial centroids for k-\/means clustering on the entire dataset.

This technique generally gives better initial points than the default random partitioning, but depending on the parameters, it can take much longer. This initialization technique is enabled with the {\ttfamily -\/r} ({\ttfamily --refined\+\_\+start}) option. The {\ttfamily -\/S} ({\ttfamily --samplings}) parameter controls how many samplings of the dataset are performed, and the {\ttfamily -\/p} ({\ttfamily --percentage}) parameter controls how much of the dataset is randomly sampled for each sampling (it must be between 0.\+0 and 1.\+0). For more information on the refined start technique, see the paper referenced in the introduction of this tutorial.

The example below performs k-\/means clustering, giving 5 clusters, using the refined start technique, sampling 10\% of the dataset 25 times to produce the initial centroids.


\begin{DoxyCode}
$ mlpack\_kmeans -c 5 -i dataset.csv -v -o assignments.csv -r -S 25 -p 0.2
\end{DoxyCode}
\subsection{Using different k-\/means algorithms}\label{kmtutorial_cli_ex7_kmtut}
The {\ttfamily mlpack\+\_\+kmeans} program implements six different strategies for clustering; each of these gives the exact same results, but will have different runtimes. The particular algorithm to use can be specified with the {\ttfamily -\/a} or {\ttfamily --algorithm} option. The choices are\+:


\begin{DoxyItemize}
\item {\ttfamily naive\+:} the standard Lloyd iteration; takes $O(kN)$ time per iteration.
\item {\ttfamily pelleg-\/moore}\+: the \textquotesingle{}blacklist\textquotesingle{} algorithm, which builds a kd-\/tree on the data. This can be fast when k is small and the dimensionality is reasonably low.
\item {\ttfamily elkan\+:} Elkan\textquotesingle{}s algorithm for k-\/means, which maintains upper and lower distance bounds between each point and each centroid. This can be very fast, but it does not scale well to the case of large N or k, and uses a lot of memory.
\item {\ttfamily hamerly\+:} Hamerly\textquotesingle{}s algorithm is a variant of Elkan\textquotesingle{}s algorithm that handles memory usage much better and thus can operate with much larger datasets than Elkan\textquotesingle{}s algorithm.
\item {\ttfamily dualtree\+:} The dual-\/tree algorithm for k-\/means builds a kd-\/tree on both the centroids and the points in order to prune away as much work as possible. This algorithm is most effective when both N and k are large.
\item {\ttfamily dualtree-\/covertree}\+: This is the dual-\/tree algorithm using cover trees instead of kd-\/trees. It satisfies the runtime guarantees specified in the dual-\/tree k-\/means paper.
\end{DoxyItemize}

In general, the {\ttfamily naive} algorithm will be much slower than the others on datasets that are larger than tiny.

The example below uses the {\ttfamily dualtree} algorithm to perform k-\/means clustering with 5 clusters on the dataset in {\ttfamily dataset.\+csv}, using the initial centroids in {\ttfamily initial\+\_\+centroids.\+csv}, saving the resulting cluster assignments to {\ttfamily assignments.\+csv\+:} 


\begin{DoxyCode}
$ mlpack\_kmeans -i dataset.csv -c 5 -v -I initial\_centroids.csv -a dualtree \(\backslash\)
> -o assignments.csv
\end{DoxyCode}
\section{The \textquotesingle{}\+K\+Means\textquotesingle{} class}\label{kmtutorial_kmeans_kmtut}
The {\ttfamily K\+Means$<$$>$} class (with default template parameters) provides a simple way to run k-\/means clustering using {\bfseries mlpack} in C++. The default template parameters for {\ttfamily K\+Means$<$$>$} will initialize cluster assignments randomly and disallow empty clusters. When an empty cluster is encountered, the point furthest from the cluster with maximum variance is set to the centroid of the empty cluster.\subsection{Running k-\/means and getting cluster assignments}\label{kmtutorial_kmeans_ex1_kmtut}
The simplest way to use the {\ttfamily K\+Means$<$$>$} class is to pass in a dataset and a number of clusters, and receive the cluster assignments in return. Note that the dataset must be column-\/major -- that is, one column corresponds to one point. See \doxyref{the matrices guide}{p.}{matrices} for more information.


\begin{DoxyCode}
\textcolor{preprocessor}{#include <mlpack/methods/kmeans/kmeans.hpp>}

\textcolor{keyword}{using namespace }mlpack::kmeans;

\textcolor{comment}{// The dataset we are clustering.}
\textcolor{keyword}{extern} arma::mat data;
\textcolor{comment}{// The number of clusters we are getting.}
\textcolor{keyword}{extern} \textcolor{keywordtype}{size\_t} clusters;

\textcolor{comment}{// The assignments will be stored in this vector.}
arma::Row<size\_t> assignments;

\textcolor{comment}{// Initialize with the default arguments.}
KMeans<> k;
k.Cluster(data, clusters, assignments);
\end{DoxyCode}


Now, the vector {\ttfamily assignments} holds the cluster assignments of each point in the dataset.\subsection{Running k-\/means and getting centroids of clusters}\label{kmtutorial_kmeans_ex2_kmtut}
Often it is useful to not only have the cluster assignments, but the centroids of each cluster. Another overload of {\ttfamily Cluster()} makes this easily possible\+:


\begin{DoxyCode}
\textcolor{preprocessor}{#include <mlpack/methods/kmeans/kmeans.hpp>}

\textcolor{keyword}{using namespace }mlpack::kmeans;

\textcolor{comment}{// The dataset we are clustering.}
\textcolor{keyword}{extern} arma::mat data;
\textcolor{comment}{// The number of clusters we are getting.}
\textcolor{keyword}{extern} \textcolor{keywordtype}{size\_t} clusters;

\textcolor{comment}{// The assignments will be stored in this vector.}
arma::Row<size\_t> assignments;
\textcolor{comment}{// The centroids will be stored in this matrix.}
arma::mat centroids;

\textcolor{comment}{// Initialize with the default arguments.}
KMeans<> k;
k.Cluster(data, clusters, assignments, centroids);
\end{DoxyCode}


Note that the centroids matrix has columns equal to the number of clusters and rows equal to the dimensionality of the dataset. Each column represents the centroid of the according cluster -- {\ttfamily centroids.\+col(0)} represents the centroid of the first cluster.\subsection{Limiting the maximum number of iterations}\label{kmtutorial_kmeans_ex3_kmtut}
The first argument to the constructor allows specification of the maximum number of iterations. This is useful because often, the k-\/means algorithm does not converge, and is terminated after a number of iterations. Setting this parameter to 0 indicates that the algorithm will run until convergence -- note that in some cases, convergence may never happen. The default maximum number of iterations is 1000.


\begin{DoxyCode}
\textcolor{comment}{// The first argument is the maximum number of iterations.  Here we set it to}
\textcolor{comment}{// 500 iterations.}
KMeans<> k(500);
\end{DoxyCode}


Then you can run {\ttfamily Cluster()} as normal.\subsection{Setting initial cluster assignments}\label{kmtutorial_kmeans_ex5_kmtut}
If you have an initial guess for the cluster assignments for each point, you can fill the assignments vector with the guess and then pass an extra boolean (initial\+Assignment\+Guess) as true to the {\ttfamily Cluster()} method. Below are examples for either overload of {\ttfamily Cluster()}.


\begin{DoxyCode}
\textcolor{preprocessor}{#include <mlpack/methods/kmeans/kmeans.hpp>}

\textcolor{keyword}{using namespace }mlpack::kmeans;

\textcolor{comment}{// The dataset we are clustering on.}
\textcolor{keyword}{extern} arma::mat dataset;
\textcolor{comment}{// The number of clusters we are obtaining.}
\textcolor{keyword}{extern} \textcolor{keywordtype}{size\_t} clusters;

\textcolor{comment}{// A vector pre-filled with initial assignment guesses.}
\textcolor{keyword}{extern} arma::Row<size\_t> assignments;

KMeans<> k;

\textcolor{comment}{// The boolean set to true indicates that our assignments vector is filled with}
\textcolor{comment}{// initial guesses.}
k.Cluster(dataset, clusters, assignments, \textcolor{keyword}{true});
\end{DoxyCode}



\begin{DoxyCode}
\textcolor{preprocessor}{#include <mlpack/methods/kmeans/kmeans.hpp>}

\textcolor{keyword}{using namespace }mlpack::kmeans;

\textcolor{comment}{// The dataset we are clustering on.}
\textcolor{keyword}{extern} arma::mat dataset;
\textcolor{comment}{// The number of clusters we are obtaining.}
\textcolor{keyword}{extern} \textcolor{keywordtype}{size\_t} clusters;

\textcolor{comment}{// A vector pre-filled with initial assignment guesses.}
\textcolor{keyword}{extern} arma::Row<size\_t> assignments;

\textcolor{comment}{// This will hold the centroids of the finished clusters.}
arma::mat centroids;

KMeans<> k;

\textcolor{comment}{// The boolean set to true indicates that our assignments vector is filled with}
\textcolor{comment}{// initial guesses.}
k.Cluster(dataset, clusters, assignments, centroids, \textcolor{keyword}{true});
\end{DoxyCode}


\begin{DoxyNote}{Note}
If you have a heuristic or algorithm which makes initial guesses, a more elegant solution is to create a new class fulfilling the Initial\+Partition\+Policy template policy. See \doxyref{the section about changing the initial partitioning strategy}{p.}{kmtutorial_kmeans_initial_partition_kmtut} for more details.
\end{DoxyNote}
\begin{DoxyParagraph}{}

\end{DoxyParagraph}
\begin{DoxyNote}{Note}
If you set the Initial\+Partition\+Policy parameter to something other than the default but give an initial cluster assignment guess, the Initial\+Partition\+Policy will not be used to initialize the algorithm. See \doxyref{the section about changing the initial partitioning strategy}{p.}{kmtutorial_kmeans_initial_partition_kmtut} for more details.
\end{DoxyNote}
\subsection{Setting initial cluster centroids}\label{kmtutorial_kmeans_ex6_kmtut}
An equally important option to being able to make initial cluster assignment guesses is to make initial cluster centroid guesses without having to assign each point in the dataset to an initial cluster. This is similar to the previous section, but now you must pass two extra booleans -- the first (initial\+Assignment\+Guess) as false, indicating that there are not initial cluster assignment guesses, and the second (initial\+Centroid\+Guess) as true, indicating that the centroids matrix is filled with initial centroid guesses.

This, of course, only works with the overload of {\ttfamily Cluster()} that takes a matrix to put the resulting centroids in. Below is an example.


\begin{DoxyCode}
\textcolor{preprocessor}{#include <mlpack/methods/kmeans/kmeans.hpp>}

\textcolor{keyword}{using namespace }mlpack::kmeans;

\textcolor{comment}{// The dataset we are clustering on.}
\textcolor{keyword}{extern} arma::mat dataset;
\textcolor{comment}{// The number of clusters we are obtaining.}
\textcolor{keyword}{extern} \textcolor{keywordtype}{size\_t} clusters;

\textcolor{comment}{// A matrix pre-filled with guesses for the initial cluster centroids.}
\textcolor{keyword}{extern} arma::mat centroids;

\textcolor{comment}{// This will be filled with the final cluster assignments for each point.}
arma::Row<size\_t> assignments;

KMeans<> k;

\textcolor{comment}{// Remember, the first boolean indicates that we are not giving initial}
\textcolor{comment}{// assignment guesses, and the second boolean indicates that we are giving}
\textcolor{comment}{// initial centroid guesses.}
k.Cluster(dataset, clusters, assignments, centroids, \textcolor{keyword}{false}, \textcolor{keyword}{true});
\end{DoxyCode}


\begin{DoxyNote}{Note}
If you have a heuristic or algorithm which makes initial guesses, a more elegant solution is to create a new class fulfilling the Initial\+Partition\+Policy template policy. See \doxyref{the section about changing the initial partitioning strategy}{p.}{kmtutorial_kmeans_initial_partition_kmtut} for more details.
\end{DoxyNote}
\begin{DoxyParagraph}{}

\end{DoxyParagraph}
\begin{DoxyNote}{Note}
If you set the Initial\+Partition\+Policy parameter to something other than the default but give an initial cluster centroid guess, the Initial\+Partition\+Policy will not be used to initialize the algorithm. See \doxyref{the section about changing the initial partitioning strategy}{p.}{kmtutorial_kmeans_initial_partition_kmtut} for more details.
\end{DoxyNote}
\subsection{Running sparse k-\/means}\label{kmtutorial_kmeans_ex7_kmtut}
The {\ttfamily Cluster()} function can work on both sparse and dense matrices, so all of the above examples can be used with sparse matrices instead, if the fifth template parameter is modified. Below is a simple example. Note that the centroids are returned as a dense matrix, because the centroids of collections of sparse points are not generally sparse.


\begin{DoxyCode}
\textcolor{comment}{// The sparse dataset.}
\textcolor{keyword}{extern} arma::sp\_mat sparseDataset;
\textcolor{comment}{// The number of clusters.}
\textcolor{keyword}{extern} \textcolor{keywordtype}{size\_t} clusters;

\textcolor{comment}{// The assignments will be stored in this vector.}
arma::Row<size\_t> assignments;
\textcolor{comment}{// The centroids of each cluster will be stored in this sparse matrix.}
arma::sp\_mat sparseCentroids;

\textcolor{comment}{// We must change the fifth (and last) template parameter.}
KMeans<metric::EuclideanDistance, SampleInitialization, MaxVarianceNewCluster,
       NaiveKMeans, arma::sp\_mat> k;
k.Cluster(sparseDataset, clusters, assignments, sparseCentroids);
\end{DoxyCode}
\section{Template parameters for the \textquotesingle{}\+K\+Means\textquotesingle{} class}\label{kmtutorial_kmeans_template_kmtut}
The {\ttfamily K\+Means$<$$>$} class also takes three template parameters, which can be modified to change the behavior of the k-\/means algorithm. There are three template parameters\+:


\begin{DoxyItemize}
\item {\ttfamily Metric\+Type\+:} controls the distance metric used for clustering (by default, the squared Euclidean distance is used)
\item {\ttfamily Initial\+Partition\+Policy\+:} the method by which initial clusters are set; by default, \doxyref{Sample\+Initialization}{p.}{classmlpack_1_1kmeans_1_1SampleInitialization} is used
\item {\ttfamily Empty\+Cluster\+Policy\+:} the action taken when an empty cluster is encountered; by default, \doxyref{Max\+Variance\+New\+Cluster}{p.}{classmlpack_1_1kmeans_1_1MaxVarianceNewCluster} is used
\item {\ttfamily Lloyd\+Step\+Type\+:} this defines the strategy used to make a single Lloyd iteration; by default this is the typical Lloyd iteration specified in \doxyref{Naive\+K\+Means}{p.}{classmlpack_1_1kmeans_1_1NaiveKMeans}
\item {\ttfamily Mat\+Type\+:} type of data matrix to use for clustering
\end{DoxyItemize}

The class is defined like below\+:


\begin{DoxyCode}
\textcolor{keyword}{template}<
  \textcolor{keyword}{typename} DistanceMetric = mlpack::metric::SquaredEuclideanDistance,
  \textcolor{keyword}{typename} InitialPartitionPolicy = SampleInitialization,
  \textcolor{keyword}{typename} EmptyClusterPolicy = MaxVarianceNewCluster,
  \textcolor{keyword}{template}<\textcolor{keyword}{class}, \textcolor{keyword}{class}> \textcolor{keyword}{class }LloydStepType = NaiveKMeans,
  \textcolor{keyword}{typename} MatType = arma::mat
>
\textcolor{keyword}{class }KMeans;
\end{DoxyCode}


In the following sections, each policy is described further, with examples of how to modify them.\subsection{Changing the distance metric used for k-\/means}\label{kmtutorial_kmeans_metric_kmtut}
Most machine learning algorithms in {\bfseries mlpack} support modifying the distance metric, and {\ttfamily K\+Means$<$$>$} is no exception. Similar to \doxyref{Neighbor\+Search}{p.}{classmlpack_1_1neighbor_1_1NeighborSearch} (see \doxyref{the section in the Neighbor\+Search tutorial}{p.}{nstutorial_metric_type_doc_nstut}), any class in \doxyref{mlpack\+::metric}{p.}{namespacemlpack_1_1metric} can be given as an argument. The \doxyref{mlpack\+::metric\+::\+L\+Metric}{p.}{classmlpack_1_1metric_1_1LMetric} class is a good example implementation.

A class fulfilling the Metric\+Type policy must provide the following two functions\+:


\begin{DoxyCode}
\textcolor{comment}{// Empty constructor is required.}
MetricType();

\textcolor{comment}{// Computer the distance between two points.}
\textcolor{keyword}{template}<\textcolor{keyword}{typename} VecType>
\textcolor{keywordtype}{double} Evaluate(\textcolor{keyword}{const} VecType& a, \textcolor{keyword}{const} VecType& b);
\end{DoxyCode}


Most of the standard metrics that could be used are stateless and therefore the {\ttfamily Evaluate()} method is implemented statically. However, there are metrics, such as the Mahalanobis distance (\doxyref{mlpack\+::metric\+::\+Mahalanobis\+Distance}{p.}{classmlpack_1_1metric_1_1MahalanobisDistance}), that store state. To this end, an instantiated Metric\+Type object is stored within the {\ttfamily K\+Means} class. The example below shows how to pass an instantiated Mahalanobis\+Distance in the constructor.


\begin{DoxyCode}
\textcolor{comment}{// The initialized Mahalanobis distance.}
\textcolor{keyword}{extern} mlpack::metric::MahalanobisDistance distance;

\textcolor{comment}{// We keep the default arguments for the maximum number of iterations, but pass}
\textcolor{comment}{// our instantiated metric.}
KMeans<mlpack::metric::MahalanobisDistance> k(1000, distance);
\end{DoxyCode}


\begin{DoxyNote}{Note}
While the Metric\+Type policy only requires two methods, one of which is an empty constructor, more can always be added. \doxyref{mlpack\+::metric\+::\+Mahalanobis\+Distance}{p.}{classmlpack_1_1metric_1_1MahalanobisDistance} also has constructors with parameters, because it is a stateful metric.
\end{DoxyNote}
\subsection{Changing the initial partitioning strategy used for k-\/means}\label{kmtutorial_kmeans_initial_partition_kmtut}
There have been many initial cluster strategies for k-\/means proposed in the literature. Fortunately, the {\ttfamily K\+Means$<$$>$} class makes it very easy to implement one of these methods and plug it in without needing to modify the existing algorithm code at all.

By default, the {\ttfamily K\+Means$<$$>$} class uses \doxyref{mlpack\+::kmeans\+::\+Sample\+Initialization}{p.}{classmlpack_1_1kmeans_1_1SampleInitialization}, which randomly samples points as initial centroids. However, writing a new policy is simple; it needs to only implement the following functions\+:


\begin{DoxyCode}
\textcolor{comment}{// Empty constructor is required.}
InitialPartitionPolicy();

\textcolor{comment}{// Only *one* of the following two functions is required!  You should implement}
\textcolor{comment}{// whichever you find more convenient to implement.}

\textcolor{comment}{// This function is called to initialize the clusters and returns centroids.}
\textcolor{keyword}{template}<\textcolor{keyword}{typename} MatType>
\textcolor{keywordtype}{void} Cluster(MatType& data,
             \textcolor{keyword}{const} \textcolor{keywordtype}{size\_t} clusters,
             arma::mat& centroids);

\textcolor{comment}{// This function is called to initialize the clusters and returns individual}
\textcolor{comment}{// point assignments.  The centroids will then be calculated from the given}
\textcolor{comment}{// assignments.}
\textcolor{keyword}{template}<\textcolor{keyword}{typename} MatType>
\textcolor{keywordtype}{void} Cluster(MatType& data,
             \textcolor{keyword}{const} \textcolor{keywordtype}{size\_t} clusters,
             arma::Row<size\_t> assignments);
\end{DoxyCode}


The templatization of the {\ttfamily Cluster()} function allows both dense and sparse matrices to be passed in. If the desired policy does not work with sparse (or dense) matrices, then the method can be written specifically for one type of matrix -- however, be warned that if you try to use {\ttfamily K\+Means} with that policy and the wrong type of matrix, you will get many ugly compilation errors!


\begin{DoxyCode}
\textcolor{comment}{// The Cluster() function specialized for dense matrices.}
\textcolor{keywordtype}{void} Cluster(arma::mat& data,
             \textcolor{keyword}{const} \textcolor{keywordtype}{size\_t} clusters,
             arma::Row<size\_t> assignments);
\end{DoxyCode}


Note that only one of the two possible {\ttfamily Cluster()} functions are required. This is because sometimes it is easier to express an initial partitioning policy as something that returns point assignments, and sometimes it is easier to express the policy as something that returns centroids. The K\+Means$<$$>$ class will use whichever of these two functions is given; if both are given, the overload that returns centroids will be preferred.

One alternate to the default Sample\+Initialization policy is the Refined\+Start policy, which is an implementation of the Bradley and Fayyad approach for finding initial points detailed in \char`\"{}\+Refined initial points for k-\/means
clustering\char`\"{} and other places in this document. Another option is the Random\+Partition class, which randomly assigns points to clusters, but this may not work very well for most settings. See the documentation for \doxyref{mlpack\+::kmeans\+::\+Refined\+Start}{p.}{classmlpack_1_1kmeans_1_1RefinedStart} and \doxyref{mlpack\+::kmeans\+::\+Random\+Partition}{p.}{classmlpack_1_1kmeans_1_1RandomPartition} for more information.

If the {\ttfamily Cluster()} method returns point assignments instead of centroids, then valid initial assignments must be returned for every point in the dataset.

As with the Metric\+Type template parameter, an initialized Initial\+Partition\+Policy can be passed to the constructor of {\ttfamily K\+Means} as a fourth argument.\subsection{Changing the action taken when an empty cluster is encountered}\label{kmtutorial_kmeans_empty_cluster_kmtut}
Sometimes, during clustering, a situation will arise where a cluster has no points in it. The {\ttfamily K\+Means} class allows easy customization of the action to be taken when this occurs. By default, the point furthest from the centroid of the cluster with maximum variance is taken as the centroid of the empty cluster; this is implemented in the \doxyref{mlpack\+::kmeans\+::\+Max\+Variance\+New\+Cluster}{p.}{classmlpack_1_1kmeans_1_1MaxVarianceNewCluster} class. Another alternate choice is the \doxyref{mlpack\+::kmeans\+::\+Allow\+Empty\+Clusters}{p.}{classmlpack_1_1kmeans_1_1AllowEmptyClusters} class, which simply allows empty clusters to persist.

A custom policy can be written and it must implement the following methods\+:


\begin{DoxyCode}
\textcolor{comment}{// Empty constructor is required.}
EmptyClusterPolicy();

\textcolor{comment}{// This function is called when an empty cluster is encountered.  emptyCluster}
\textcolor{comment}{// indicates the cluster which is empty, and then the clusterCounts and}
\textcolor{comment}{// assignments are meant to be modified by the function.  The function should}
\textcolor{comment}{// return the number of modified points.}
\textcolor{keyword}{template}<\textcolor{keyword}{typename} MatType>
\textcolor{keywordtype}{size\_t} EmptyCluster(\textcolor{keyword}{const} MatType& data,
                    \textcolor{keyword}{const} \textcolor{keywordtype}{size\_t} emptyCluster,
                    \textcolor{keyword}{const} MatType& centroids,
                    arma::Col<size\_t>& clusterCounts,
                    arma::Row<size\_t>& assignments);
\end{DoxyCode}


The {\ttfamily Empty\+Cluster()} function is called for each cluster that is empty at each iteration of the algorithm. As with Initial\+Partition\+Policy, the {\ttfamily Empty\+Cluster()} function does not need to be generalized to support both dense and sparse matrices -- but usage with the wrong type of matrix will cause compilation errors.

Like the other template parameters to {\ttfamily K\+Means}, Empty\+Cluster\+Policy implementations that have state can be passed to the constructor of {\ttfamily K\+Means} as a fifth argument. See the kmeans\+::\+K\+Means documentation for further details.\subsection{The Lloyd\+Step\+Type template parameter}\label{kmtutorial_kmeans_lloyd_kmtut}
The internal algorithm used for a single step of the k-\/means algorithm can easily be changed; {\bfseries mlpack} implements several existing classes that satisfy the {\ttfamily Lloyd\+Step\+Type} policy\+:


\begin{DoxyItemize}
\item \doxyref{mlpack\+::kmeans\+::\+Naive\+K\+Means}{p.}{classmlpack_1_1kmeans_1_1NaiveKMeans}
\item \doxyref{mlpack\+::kmeans\+::\+Elkan\+K\+Means}{p.}{classmlpack_1_1kmeans_1_1ElkanKMeans}
\item \doxyref{mlpack\+::kmeans\+::\+Hamerly\+K\+Means}{p.}{classmlpack_1_1kmeans_1_1HamerlyKMeans}
\item \doxyref{mlpack\+::kmeans\+::\+Pelleg\+Moore\+K\+Means}{p.}{classmlpack_1_1kmeans_1_1PellegMooreKMeans}
\item \doxyref{mlpack\+::kmeans\+::\+Dual\+Tree\+K\+Means}{p.}{classmlpack_1_1kmeans_1_1DualTreeKMeans}
\end{DoxyItemize}

Note that the {\ttfamily Lloyd\+Step\+Type} policy is itself a template template parameter, and must accept two template parameters of its own\+:


\begin{DoxyItemize}
\item {\ttfamily Metric\+Type\+:} the type of metric to use
\item {\ttfamily Mat\+Type\+:} the type of data matrix to use
\end{DoxyItemize}

The {\ttfamily Lloyd\+Step\+Type} policy also mandates three functions\+:


\begin{DoxyItemize}
\item a constructor\+: {\ttfamily Lloyd\+Step\+Type(const Mat\+Type\& dataset, Metric\+Type\& metric);}
\item an {\ttfamily Iterate()} function\+:
\end{DoxyItemize}


\begin{DoxyCode}

\textcolor{keywordtype}{double} Iterate(\textcolor{keyword}{const} arma::mat& centroids,
               arma::mat& newCentroids,
               arma::Col<size\_t>& counts);
\end{DoxyCode}



\begin{DoxyItemize}
\item a function to get the number of distance calculations\+:
\end{DoxyItemize}


\begin{DoxyCode}
\textcolor{keywordtype}{size\_t} DistanceCalculations()\textcolor{keyword}{ const }\{ \textcolor{keywordflow}{return} distanceCalculations; \}
\end{DoxyCode}


Note that {\ttfamily Iterate()} does not need to return valid centroids if the cluster is empty. This is because {\ttfamily Empty\+Cluster\+Policy} will handle the empty centroid. This behavior can be used to avoid small amounts of computation.

For examples, see the five aforementioned implementations of classes that satisfy the {\ttfamily Lloyd\+Step\+Type} policy.\section{Further documentation}\label{kmtutorial_further_doc_kmtut}
For further documentation on the K\+Means class, consult the \doxyref{complete A\+PI documentation}{p.}{classmlpack_1_1kmeans_1_1KMeans}. 