Debian Codegraph @

vignettes/fastcluster.Rtex

raw
1 \def\fastclusterversion{1.3.0}
2 \documentclass[fontsize=10pt,paper=letter,BCOR=-6mm,DIV=8]{scrartcl}
3 \usepackage[utf8]{inputenc}
4 \usepackage{lmodern}
5 \normalfont
6 \usepackage[T1]{fontenc}
7 \usepackage{textcomp}
8 \newcommand*\q{\textquotesingle}
9 \usepackage{amsmath}
10 \usepackage{amsfonts}
11 \usepackage{xcolor}
12 \usepackage{booktabs}
13 \usepackage{ifpdf}
14 \ifpdf
15 \newcommand*\driver{}
16 \else
17 \newcommand*\driver{dvipdfmx}
18 \fi
19 \usepackage[%
20 pdftitle={fastcluster manual},
21 pdfauthor={Daniel Müllner},
22 % pdfsubject={},
23 pdfdisplaydoctitle=true,
24 % pdfduplex=DuplexFlipLongEdge,
25 pdfstartview=FitH,
26 colorlinks=True,
27 pdfhighlight=/I,
28 % pdfborder={0 0 1},
29 % linkbordercolor={1 .8 .8},
30 % citebordercolor={.5 .9 .5},
31 % urlbordercolor={.5 .7 1},
32 % linkcolor={blue},
33 % citecolor={blue},
34 urlcolor={blue!80!black},
35 linkcolor={red!80!black},
36 % runcolor={blue},
37 % filecolor={blue},
38 pdfpagemode=UseOutlines,
39 bookmarksopen=true,
40 bookmarksopenlevel=1,
41 bookmarksdepth=2,
42 breaklinks=true,
43 unicode=true,
44 \driver
45 ]{hyperref}
46 % Optimize the PDF targets and make the PDF file smaller
47 \ifpdf\RequirePackage{hypdestopt}\fi
48
49 \renewcommand*\sectionautorefname{Section}
50
51 \usepackage{typearea}
52
53 \DeclareMathOperator\size{size}
54 \DeclareMathOperator\Var{Var}
55
56 \newcommand*\linkage{\href{https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html}{\texttt{linkage}}}
57 \newcommand*\hierarchy{\href{https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html}{\texttt{scipy.\hskip0pt cluster.\hskip0pt hierarchy}}}
58 \newcommand*\hclust{\href{https://stat.ethz.ch/R-manual/R-patched/library/stats/html/hclust.html}{\texttt{hclust}}}
59 \newcommand*\stats{\href{https://stat.ethz.ch/R-manual/R-patched/library/stats/html/00Index.html}{\texttt{stats}}}
60 \newcommand*\flashClustPack{\href{https://CRAN.R-project.org/package=flashClust}{\texttt{flashClust}}}
61 \newcommand*\dist{\href{https://stat.ethz.ch/R-manual/R-patched/library/stats/html/dist.html}{\texttt{dist}}}
62 \newcommand*\print{\href{https://stat.ethz.ch/R-manual/R-patched/library/base/html/print.html}{\texttt{print}}}
63 \newcommand*\plot{\href{https://stat.ethz.ch/R-manual/R-patched/library/graphics/html/plot.html}{\texttt{plot}}}
64 \newcommand*\identify{\href{https://stat.ethz.ch/R-manual/R-patched/library/stats/html/identify.hclust.html}{\texttt{identify}}}
65 \newcommand*\rect{\href{https://stat.ethz.ch/R-manual/R-patched/library/stats/html/rect.hclust.html}{\texttt{rect.hclust}}}
66 \newcommand*\NA{\href{https://stat.ethz.ch/R-manual/R-patched/library/base/html/NA.html}{\texttt{NA}}}
67 \newcommand*\double{\href{https://stat.ethz.ch/R-manual/R-patched/library/base/html/double.html}{\texttt{double}}}
68 \newcommand*\matchcall{\href{https://stat.ethz.ch/R-manual/R-patched/library/base/html/match.call.html}{\texttt{match.call}}}
69 \newcommand*\NumPyarray{\href{https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html}{NumPy array}}
70 \newcommand*\maskedarrays{\href{https://docs.scipy.org/doc/numpy/reference/maskedarray.html}{masked arrays}}
71 \newcommand*\pdist{\href{https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html}{\texttt{scipy.spatial.distance.pdist}}}
72
73 %\usepackage{showframe}
74
75 \makeatletter
76 \newenvironment{methods}{%
77 \list{}{\labelwidth\z@
78 \itemindent-\leftmargin
79 \let\makelabel\methodslabel}%
80 }{%
81 \endlist
82 }
83 \newcommand*{\methodslabel}[1]{%
84 %\hspace{\labelsep}%
85 \hbox to \textwidth{\hspace{\labelsep}%
86 \normalfont\bfseries\ttfamily
87 #1\hskip-\labelsep\hfill}%
88 }
89
90 \makeatother
91 \setkomafont{descriptionlabel}{\normalfont\ttfamily\bfseries}
92
93
94 \begin{document}
95 %\VignetteIndexEntry{User's manual}
96 \title{The \textit{fastcluster} package: User's manual}
97 \author{\href{https://danifold.net}{Daniel Müllner}}
98 \date{May 4, 2025}
99 \subtitle{Version \fastclusterversion}
100 \maketitle
101
102 \makeatletter
103 \renewenvironment{quotation}{%
104 \list{}{\listparindent 1em%
105 \itemindent \listparindent
106 \leftmargin2.5em
107 \rightmargin \leftmargin
108 \parsep \z@ \@plus\p@
109 }%
110 \item\relax
111 }{%
112 \endlist
113 }
114 \makeatother
115 \begin{abstract}\noindent\small
116 The fastcluster package is a C++ library for hierarchical, agglomerative
117 clustering. It efficiently implements the
118 seven most widely used clustering schemes: single, complete, average, weighted/\hskip0pt mcquitty, Ward, centroid and median linkage. The library currently has interfaces to two languages: R and Python/SciPy. Part of the functionality is designed as drop-in replacement for existing routines: \linkage{} in the SciPy package \hierarchy{}, \hclust{} in R's \stats{} package, and the \flashClustPack{} package. Once the fastcluster library is loaded at the beginning of the code, every program that uses hierarchical clustering can benefit immediately and effortlessly from the performance gain. Moreover, there are memory-saving routines for clustering of vector data, which go beyond what the existing packages provide.
119 \end{abstract}
120
121 \noindent
122 This document describes the usage for the two interfaces for R and Python and is meant as the reference document for the end user. Installation instructions are given in the file INSTALL in the source distribution and are not repeated here. The sections about the two interfaces are independent and in consequence somewhat redundant, so that users who need a reference for one interface need to consult only one section.
123
124 If you use the fastcluster package for scientific work, please cite it as:
125 \begin{quote}
126 Daniel Müllner, \textit{fastcluster: Fast Hierarchical, Agglomerative Clustering Routines for R and Python}, Journal of Statistical Software, \textbf{53} (2013), no.~9, 1--18, \url{https://doi.org/10.18637/jss.v053.i09}.
127 \end{quote}
128
129 The \hyperref[yule]{“Yule” distance function} changed in the Python interface of fastcluster version 1.2.0. This is following a \href{https://github.com/scipy/scipy/commit/3b22d1da98dc1b5f64bc944c21f398d4ba782bce}{change in SciPy 1.6.3}. The \hyperref[jaccard]{“Jaccard” distance function} changed in the Python interface of fastcluster version 1.3.0. This is following a \href{https://github.com/scipy/scipy/commit/ecf3ff0ff12666cbeaa5c61d5726fd0141657b54}{change in SciPy 1.15.0}. Therefore, the following pairings of SciPy and fastcluster versions are recommended:
130 \[
131 \begin{tabular}{ll}\toprule
132 SciPy version $v$ & Recommended fastcluster version \\\midrule
133 $v<\textrm{1.6.3}$ & 1.1.28 \\
134 $\textrm{1.6.3} \leq v < \textrm{1.15.0}$ & 1.2.6 \\
135 $v \geq \textrm{1.15.0}$ & latest ($\geq$ 1.3.0)\\\bottomrule
136 \end{tabular}
137 \]
138
139 The R interface does not have the “Yule” and “Jaccard” distance functions, hence is not affected by these changes.
140
141 The fastcluster package is considered stable and will undergo few changes from now on. If some years from now there have not been any updates, this does not necessarily mean that the package is unmaintained but maybe it just was not necessary to correct anything. Of course, please still report potential bugs and incompatibilities to \texttt{[email protected]}.
142
143 \tableofcontents
144
145 \section{The R interface}
146
147 Load the package with the following command:
148 \begin{quote}
149 \texttt{library(\q fastcluster\q)}
150 \end{quote}
151
152 The package overwrites the function \hclust{} from the \stats{} package (in the same
153 way as the \flashClustPack{} package does). Please remove any references to the
154 \flashClustPack{} package in your R files to not accidentally overwrite the \hclust{}
155 function with the \flashClustPack{} version.
156
157 The \hyperref[hclust]{new \texttt{hclust} function} has exactly the same calling conventions as the old one. You may just load the package and immediately and effortlessly enjoy the performance improvements. The function is also an improvement to the \texttt{flashClust} function from the \flashClustPack{} package. Just replace every call to \texttt{flashClust} by \hyperref[hclust]{\texttt{hclust}} and expect your code to work as before, only faster.\footnote{If you are using flashClust prior to version 1.01, update it! See the change log for \flashClustPack{} at \url{https://cran.r-project.org/web/packages/flashClust/ChangeLog}.} In case the data includes infinite or NaN values, see \autoref{sec:infnan}.
158
159 If you need to access the old function or make sure that the right function is
160 called, specify the package as follows:
161 \begin{quote}
162 \texttt{\hyperref[hclust]{fastcluster::hclust}(…)}\\
163 \texttt{flashClust::hclust(…)}\\
164 \texttt{stats::hclust(…)}
165 \end{quote}
166
167 Vector data can be clustered with a memory-saving algorithm with the command:
168 \begin{quote}
169 \texttt{\hyperref[hclust.vector]{hclust.vector}(…)}
170 \end{quote}
171
172 The following sections contain comprehensive descriptions of these methods.
173
174 \begin{methods}
175 \item [\normalfont\texttt{\textbf{hclust}}\,(\textit{d, method=\q complete\q, members=NULL})]
176 \phantomsection\label{hclust}
177 \addcontentsline{toc}{subsection}{\texttt{hclust}}
178
179 Hierarchical, agglomerative clustering on a condensed dissimilarity matrix.
180
181 This method has the same specifications as the method \hclust{} in the package \stats{} and \texttt{hclust} alias \texttt{flashClust} in the package \flashClustPack{}. In particular, the \print{}, \plot{}, \rect{} and \identify{} methods work as expected.
182
183 The argument $d$ is a condensed distance matrix, as it is produced by \dist.
184
185 The argument \textit{method} is one of the strings \textit{\q single\q}, \textit{\q complete\q}, \textit{\q average\q}, \textit{\q mcquitty\q}, \textit{\q centroid\q}, \textit{\q median\q}, \textit{\q ward.D\q}, \textit{\q ward.D2\q} or an unambiguous abbreviation thereof.
186
187 The argument \textit{members} specifies the sizes of the initial nodes, ie.\ the number of observations in the initial clusters. The default value \texttt{NULL} says that all initial nodes are singletons, ie.\ have size 1. Otherwise, \textit{members} must be a vector whose size is the number of input points. The vector is processed as a \double{} array so that not only integer cardinalities of nodes can be accounted for but also weighted nodes with real weights.
188
189 The general scheme of the agglomerative clustering procedure is as follows:
190 \begin{enumerate}
191 \item Start with $N$ singleton clusters (nodes) labeled $-1,\ldots, -N$, which represent the input points.
192 \item Find a pair of nodes with minimal distance among all pairwise distances.
193 \item Join the two nodes into a new node and remove the two old nodes. The new nodes are labeled consecutively $1,2,\ldots$
194 \item The distances from the new node to all other nodes is determined by the \textit{method} parameter (see below).
195 \item Repeat $N-1$ times from step 2, until there is one big node, which contains all original input points.
196 \end{enumerate}
197
198 The output of \texttt{hclust} is an object of class \texttt{\q hclust\q} and represents a \emph{stepwise dendrogram}. It contains the following fields:
199 \begin{description}
200 \item[\normalfont\textit{merge}]
201 This is an $(N-1)\times 2$ array. Row $i$ specifies the labels of the nodes which are joined step $i$ of the clustering.
202
203 \item[\normalfont\textit{height}]
204 This is a vector of length $N-1$. It contains the sequence of dissimilarities at which every pair of nearest nodes is joined.
205
206 \item[\normalfont\textit{order}]
207 This is a vector of length $N$. It contains a permutation of the numbers $1,\ldots N$ for the \plot{} method. When the dendrogram is plotted, this is the order in which the singleton nodes are plotted as the leaves of a rooted tree. The order is computed so that the dendrogram is plotted without intersections (except the case when there are inversions for the \textit{\q centroid\q} and \textit{\q median\q} methods). The choice of the \textit{\q order\q} sequence follows the same scheme as the \texttt{stats} package does, only with a faster algorithm. Note that there are many valid choices to order the nodes in a dendrogram without intersections. Also, subsequent points in the \textit{\q order\q} field are not always close in the ultrametric given by the dendrogram.
208
209 \item[\normalfont\textit{labels}]
210 This copies the attribute \textit{\q Labels\q} from the first input parameter $d$. It contains the labels for the objects being clustered.
211
212 \item[\normalfont\textit{method}]
213 The (unabbreviated) string for the \textit{\q method\q} parameter. See below for a specification of all available methods.
214
215 \item[\normalfont\textit{call}]
216 The full command that produced the result. See \matchcall.
217
218 \item[\normalfont\textit{dist.method}]
219 This \textit{\q method\q} attribute of the first input parameter $d$. This specifies which metric was used in the \texttt{dist} method which generated the first argument.
220 \end{description}
221
222 The parameter \textit{method} specifies which clustering scheme to use. The clustering scheme determines the distance from a new node to the other nodes. Denote the dissimilarities by $d$, the nodes to be joined by $I,J$, the new node by $K$ and any other node by $L$. The symbol $|I|$ denotes the size of the cluster $I$.
223
224 \begin{description}
225 \item [\normalfont\textit{method=\q single\q}:]
226 $\displaystyle d(K,L) = \min(d(I,L), d(J,L))$
227
228 The distance between two clusters $A,B$ is the closest distance between any two points in each cluster:
229 \[
230 d(A,B)=\min_{a\in A, b\in B}d(a,b)
231 \]
232
233 \item [\normalfont\textit{method=\q complete\q}:]
234 $\displaystyle d(K,L) = \max(d(I,L), d(J,L))$
235
236 The distance between two clusters $A,B$ is the maximal distance between any two points in each cluster:
237 \[
238 d(A,B)=\max_{a\in A, b\in B}d(a,b)
239 \]
240
241 \item [\normalfont\textit{method=\q average\q}:]
242 $\displaystyle d(K,L) = \frac{|I|\cdot d(I,L)+|J|\cdot d(J,L)}{|I|+|J|}$
243
244 The distance between two clusters $A,B$ is the average distance between the points in the two clusters:
245 \[
246 d(A,B)=\frac1{|A||B|}\sum_{a\in A, b\in B}d(a,b)
247 \]
248
249 \item [\normalfont\textit{method=\q mcquitty\q}:]
250 $\displaystyle d(K,L) = \tfrac12(d(I,L)+d(J,L))$
251
252 There is no global description for the distance between clusters since the distance depends on the order of the merging steps.
253 \end{description}
254
255 The following three methods are intended for Euclidean data only, ie.\ when $X$ contains the pairwise \textbf{squared} distances between vectors in Euclidean space. The algorithm will work on any input, however, and it is up to the user to make sure that applying the methods makes sense.
256
257 \begin{description}
258 \item [\normalfont\textit{method=\q centroid\q}:]
259 $\displaystyle d(K,L) = \frac{|I|\cdot d(I,L)+|J|\cdot d(J,L)}{|I|+|J|}-\frac{|I|\cdot|J|\cdot d(I,J)}{(|I|+|J|)^2}$
260
261 There is a geometric interpretation: $d(A,B)$ is the distance between the centroids (ie.\ barycenters) of the clusters in Euclidean space:
262 \[
263 d(A,B) = \|\vec c_A-\vec c_B\|^2,
264 \]
265 where $\vec c_A$ denotes the centroid of the points in cluster $A$.
266
267 \item [\normalfont\textit{method=\q median\q}:]
268 $\displaystyle d(K,L) = \tfrac12 d(I,L)+\tfrac12 d(J,L)-\tfrac14 d(I,J)$
269
270 Define the midpoint $\vec w_K$ of a cluster $K$ iteratively as $\vec w_K=k$ if $K=\{k\}$ is a singleton and as the midpoint $\frac12(\vec w_I+\vec w_J)$ if $K$ is formed by joining $I$ and $J$. Then we have
271 \[
272 d(A,B)=\|\vec w_A-\vec w_B\|^2
273 \]
274 in Euclidean space for all nodes $A,B$. Notice however that this distance depends on the order of the merging steps.
275
276 \item [\normalfont\textit{method=\q ward.D\q}:]
277 $\displaystyle d(K,L) = \frac{(|I|+|L|)\cdot d(I,L)+(|J|+|L|)\cdot d(J,L)-|L|\cdot d(I,J)}{|I|+|J|+|L|}$
278
279 The global cluster dissimilarity can be expressed as
280 \[
281 d(A,B)=\frac{2|A||B|}{|A|+|B|}\cdot\|\vec c_A-\vec c_B\|^2,
282 \]
283 where $\vec c_A$ again denotes the centroid of the points in cluster $A$.
284
285 \item [\normalfont\textit{method=\q ward.D2\q}:]
286 This is the equivalent of \textit{\q ward.D\q}, but for input consisting of untransformed (in particular: \textbf{non-squared}) Euclidean distances. Internally, all distances are squared first, then method \textit{ward.D} is applied, and finally the square root of all heights in the dendrogram is taken. Thus, global cluster dissimilarity can be expressed as the square root of that for \textit{ward.D}, namely
287 \[
288 d(A,B)=\sqrt{\frac{2|A||B|}{|A|+|B|}}\cdot\|\vec c_A-\vec c_B\|.
289 \]
290 \end{description}
291
292 \item [\normalfont\texttt{\textbf{hclust.vector}}\,(\textit{X, method=\q single\q, members=NULL, metric=\q euclidean\q, p=NULL})]
293 \phantomsection\label{hclust.vector}
294 \addcontentsline{toc}{subsection}{\texttt{hclust.vector}}
295 This performs hierarchical, agglomerative clustering on vector data with memory-saving algorithms. While the \hyperref[hclust]{\texttt{hclust}} method requires $\Theta(N^2)$ memory for clustering of $N$ points, this method needs $\Theta(ND)$ for $N$ points in $\mathbb R^D$, which is usually much smaller.
296
297 The argument $X$ must be a two-dimensional matrix with \double{} precision values. It describes $N$ data points in $\mathbb R^D$ as an $(N\times D)$ matrix.
298
299 The parameter \textit{\q members\q} is the same as for \hyperref[hclust]{\texttt{hclust}}.
300
301 The parameter \textit{\q method\q} is one of the strings \textit{\q single\q}, \textit{\q centroid\q}, \textit{\q median\q}, \textit{\q ward\q}, or an unambiguous abbreviation thereof.
302
303 If \textit{method} is \textit{\q single\q}, single linkage clustering is performed on the data points with the metric which is specified by the \textit{metric} parameter. The choices are the same as in the \dist{} method: \textit{\q euclidean\q}, \textit{\q maximum\q}, \textit{\q manhattan\q}, \textit{\q canberra\q}, \textit{\q binary\q} and \textit{\q minkowski\q}. Any unambiguous substring can be given. The parameter \textit{p} is used for the \textit{\q minkowski\q} metric only.
304
305 The call
306 \begin{quote}
307 \texttt{hclust.vector(X, method=\q single\q, metric=[...])}
308 \end{quote}
309 is equivalent to
310 \begin{quote}
311 \texttt{hclust(dist(X, metric=[...]), method=\q single\q)}
312 \end{quote}
313 but uses less memory and is equally fast. Ties may be resolved differently, ie.\ if two pairs of nodes have equal, minimal dissimilarity values at some point, in the specific computer's representation for floating point numbers, either pair may be chosen for the next merging step in the dendrogram.
314
315 Note that the formula for the \textit{\q canberra\q} metric changed in R 3.5.0: Before R version 3.5.0, the \textit{\q canberra\q} metric was computed as
316 \[
317 d(u,v) = \sum_j\frac{|u_j-v_j|}{|u_j+v_j|}.
318 \]
319 Starting with R version 3.5.0, the formula was corrected to
320 \[
321 d(u,v) = \sum_j\frac{|u_j-v_j|}{|u_j|+|v_j|}.
322 \]
323 Summands with $u_j=v_j=0$ always contribute 0 to the sum. The second, newer formula equals SciPy's definition.
324
325 The fastcluster package detects the R version at runtime and chooses the formula accordingly, so that fastcluster and the \dist{} method always use the same formula for a given R version.
326
327 If \textit{method} is one of \textit{\q centroid\q}, \textit{\q median\q}, \textit{\q ward\q}, clustering is performed with respect to Euclidean distances. In this case, the parameter \textit{metric} must be \textit{\q euclidean\q}. Notice that \texttt{hclust.vector} operates on Euclidean distances for compatibility reasons with the \dist{} method, while \hyperref[hclust]{\texttt{hclust}} assumes \textbf{squared} Euclidean distances for compatibility with the \href{https://stat.ethz.ch/R-manual/R-patched/library/stats/html/hclust.html}{\texttt{stats::hclust}} method! Hence, the call
328 \phantomsection\label{squared}
329 \begin{quote}
330 \texttt{hc = hclust.vector(X, method=\q centroid\q)}
331 \end{quote}
332 is, aside from the lesser memory requirements, equivalent to
333 \begin{quote}
334 \texttt{d = dist(X)}\\
335 \texttt{hc = hclust(d\textasciicircum 2, method=\q centroid\q)}\\
336 \texttt{hc\$height = sqrt(hc\$height)}
337 \end{quote}
338 The same applies to the \textit{\q median\q} method. The \textit{\q ward\q} method in \hyperref[hclust.vector]{\texttt{hclust.vector}} is equivalent to \hyperref[hclust]{\texttt{hclust}} with method \textit{\q ward.D2\q}, but to method \textit{\q ward.D\q} only after squaring as above. Differences in these algebraically equivalent methods may arise only from floating-point inaccuracies and the resolution of ties (which may, however, in extreme cases affect the entire clustering result due to the inherently unstable nature of the clustering schemes).
339 \end{methods}
340 \section{The Python interface}
341
342 The fastcluster package is imported as usual by:
343 \begin{quote}
344 \texttt{import fastcluster}
345 \end{quote}
346
347 It provides the following functions:
348 \begin{quote}
349 \hyperref[linkage]{\texttt{linkage}}\,(\textit{X, method=\q single\q, metric=\q euclidean\q, preserve\_input=True})\\
350 \hyperref[single]{\texttt{single}}\,($X$)\\
351 \hyperref[complete]{\texttt{complete}}\,($X$)\\
352 \hyperref[average]{\texttt{average}}\,($X$)\\
353 \hyperref[weighted]{\texttt{weighted}}\,($X$)\\
354 \hyperref[ward]{\texttt{ward}}\,($X$)\\
355 \hyperref[centroid]{\texttt{centroid}}\,($X$)\\
356 \hyperref[median]{\texttt{median}}\,($X$)\\
357 \hyperref[linkage_vector]{\texttt{linkage\_vector}}\,(\textit{X, method=\q single\q, metric=\q euclidean\q, extraarg=None})
358 \end{quote}
359
360 The following sections contain comprehensive descriptions of these methods.
361
362 \begin{methods}
363 \item [\normalfont\texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q single\q, metric=\q euclidean\q, preserve\_input=\q True\q})]
364 \phantomsection\label{linkage}
365 \addcontentsline{toc}{subsection}{\texttt{linkage}}
366
367 Hierarchical, agglomerative clustering on a condensed dissimilarity matrix or on vector data.
368
369 Apart from the argument \textit{preserve\_input}, the method has the same input parameters and output format as the function of the same name in the module \hierarchy.
370
371 The argument $X$ is preferably a \NumPyarray{} with floating point entries (\texttt{X.dtype\hskip0pt==\hskip0pt numpy.double}). Any other data format will be converted before it is processed. NumPy's \maskedarrays{} are not treated as special, and the mask is simply ignored.
372
373 If $X$ is a one-dimensional array, it is considered a condensed matrix of pairwise dissimilarities in the format which is returned by \pdist. It contains the flattened, upper-triangular part of a pairwise dissimilarity matrix. That is, if there are $N$ data points and the matrix $d$ contains the dissimilarity between the $i$-th and $j$-th observation at position $d_{i,j}$, the vector $X$ has length $\binom N2$ and is ordered as follows:
374 \[
375 d
376 = \begin{pmatrix}
377 0&d_{0,1}&d_{0,2}&\ldots&d_{0,n-1}\\
378 & 0&d_{1,2} & \ldots\\
379 &&0&\ldots\\
380 &&&\ddots\\
381 &&&&0
382 \end{pmatrix}
383 = \begin{pmatrix}
384 0&X[0] &X[1]&\ldots&X[n-2]\\
385 & 0&X[n-1] & \ldots\\
386 &&0&\ldots\\
387 &&&\ddots\\
388 &&&&0
389 \end{pmatrix}
390 \]
391 The \textit{metric} argument is ignored in case of dissimilarity input.
392
393 The optional argument \textit{preserve\_input} specifies whether the method makes a working copy of the dissimilarity vector or writes temporary data into the existing array. If the dissimilarities are generated for the clustering step only and are not needed afterward, approximately half the memory can be saved by specifying \textit{preserve\_input=False}. Note that the input array $X$ contains unspecified values after this procedure. It is therefore safer to write
394 \begin{verbatim}
395 linkage(X, method="...", preserve_input=False)
396 del X
397 \end{verbatim}
398 to make sure that the matrix $X$ is not accessed accidentally after it has been
399 used as scratch memory. (The single linkage algorithm does not write to the distance matrix or its copy anyway, so the \textit{preserve\_input} flag has no effect in this case.)
400
401 If $X$ contains vector data, it must be a two-dimensional array with $N$ observations in $D$ dimensions as an $(N\times D)$ array. The \textit{preserve\_input} argument is ignored in this case. The specified \textit{metric} is used to generate pairwise distances from the input. The following two function calls yield equivalent output:
402 \begin{verbatim}
403 linkage(pdist(X, metric), method="...", preserve_input=False)
404 linkage(X, metric=metric, method="...")
405 \end{verbatim}
406
407 The two results are identical in most cases, but differences occur if ties are resolved differently: if the minimum in step 2 below is attained for more than one pair of nodes, either pair may be chosen. It is not guaranteed that both \texttt{linkage} variants choose the same pair in this case.
408
409 The general scheme of the agglomerative clustering procedure is as follows:
410 \begin{enumerate}
411 \item Start with $N$ singleton clusters (nodes) labeled $0,\ldots, N-1$, which represent the input points.
412 \item Find a pair of nodes with minimal distance among all pairwise distances.
413 \item Join the two nodes into a new node and remove the two old nodes. The new nodes are labeled consecutively $N,N+1,\ldots$
414 \item The distances from the new node to all other nodes is determined by the \textit{method} parameter (see below).
415 \item Repeat $N-1$ times from step 2, until there is one big node, which contains all original input points.
416 \end{enumerate}
417
418 The output of \texttt{linkage} is \emph{stepwise dendrogram}, which is represented as an $(N-1)\times 4$ \NumPyarray{} with floating point entries (\texttt{dtype=numpy.double}). The first two columns contain the node indices which are joined in each step. The input nodes are labeled $0,\ldots,N-1$, and the newly generated nodes have the labels $N,\ldots, 2N-2$. The third column contains the distance between the two nodes at each step, ie.\ the current minimal distance at the time of the merge. The fourth column counts the number of points which comprise each new node.
419
420 The parameter \textit{method} specifies which clustering scheme to use. The clustering scheme determines the distance from a new node to the other nodes. Denote the dissimilarities by $d$, the nodes to be joined by $I,J$, the new node by $K$ and any other node by $L$. The symbol $|I|$ denotes the size of the cluster $I$.
421
422 \begin{description}
423 \item [\normalfont\textit{method=\q single\q}:]
424 $\displaystyle d(K,L) = \min(d(I,L), d(J,L))$
425
426 The distance between two clusters $A,B$ is the closest distance between any two points in each cluster:
427 \[
428 d(A,B)=\min_{a\in A, b\in B}d(a,b)
429 \]
430
431 \item [\normalfont\textit{method=\q complete\q}:]
432 $\displaystyle d(K,L) = \max(d(I,L), d(J,L))$
433
434 The distance between two clusters $A,B$ is the maximal distance between any two points in each cluster:
435 \[
436 d(A,B)=\max_{a\in A, b\in B}d(a,b)
437 \]
438
439 \item [\normalfont\textit{method=\q average\q}:]
440 $\displaystyle d(K,L) = \frac{|I|\cdot d(I,L)+|J|\cdot d(J,L)}{|I|+|J|}$
441
442 The distance between two clusters $A,B$ is the average distance between the points in the two clusters:
443 \[
444 d(A,B)=\frac1{|A||B|}\sum_{a\in A, b\in B}d(a,b)
445 \]
446
447 \item [\normalfont\textit{method=\q weighted\q}:]
448 $\displaystyle d(K,L) = \tfrac12(d(I,L)+d(J,L))$
449
450 There is no global description for the distance between clusters since the distance depends on the order of the merging steps.
451 \end{description}
452
453 The following three methods are intended for Euclidean data only, ie.\ when $X$ contains the pairwise (non-squared!)\ distances between vectors in Euclidean space. The algorithm will work on any input, however, and it is up to the user to make sure that applying the methods makes sense.
454
455 \begin{description}
456 \item [\normalfont\textit{method=\q centroid\q}:]
457 $\displaystyle d(K,L) = \sqrt{\frac{|I|\cdot d(I,L)^2+|J|\cdot d(J,L)^2}{|I|+|J|}-\frac{|I|\cdot|J|\cdot d(I,J)^2}{(|I|+|J|)^2}}$
458
459 There is a geometric interpretation: $d(A,B)$ is the distance between the centroids (ie.\ barycenters) of the clusters in Euclidean space:
460 \[
461 d(A,B) = \|\vec c_A-\vec c_B\|,
462 \]
463 where $\vec c_A$ denotes the centroid of the points in cluster $A$.
464
465 \item [\normalfont\textit{method=\q median\q}:]
466 $\displaystyle d(K,L) = \sqrt{\tfrac12 d(I,L)^2+\tfrac12 d(J,L)^2-\tfrac14 d(I,J)^2}$
467
468 Define the midpoint $\vec w_K$ of a cluster $K$ iteratively as $\vec w_K=k$ if $K=\{k\}$ is a singleton and as the midpoint $\frac12(\vec w_I+\vec w_J)$ if $K$ is formed by joining $I$ and $J$. Then we have
469 \[
470 d(A,B)=\|\vec w_A-\vec w_B\|
471 \]
472 in Euclidean space for all nodes $A,B$. Notice however that this distance depends on the order of the merging steps.
473
474 \item [\normalfont\textit{method=\q ward\q}:] \raggedright
475 $\displaystyle d(K,L) = \sqrt{\frac{(|I|+|L|)\cdot d(I,L)^2+(|J|+|L|)\cdot d(J,L)^2-|L|\cdot d(I,J)^2}{|I|+|J|+|L|}}$
476
477 The global cluster dissimilarity can be expressed as
478 \[
479 d(A,B)=\sqrt{\frac{2|A||B|}{|A|+|B|}}\cdot\|\vec c_A-\vec c_B\|,
480 \]
481 where $\vec c_A$ again denotes the centroid of the points in cluster $A$.
482 \end{description}
483
484 \item [\normalfont\texttt{fastcluster.\textbf{single}}\,(\textit{X})]
485 \phantomsection\addcontentsline{toc}{subsection}{\texttt{single}}\label{single}
486 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q single\q}).
487
488 \item [\normalfont\texttt{fastcluster.\textbf{complete}}\,(\textit{X})]
489 \phantomsection\addcontentsline{toc}{subsection}{\texttt{complete}}\label{complete}
490 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q complete\q}).
491
492 \item [\normalfont\texttt{fastcluster.\textbf{average}}\,(\textit{X})]
493 \phantomsection\addcontentsline{toc}{subsection}{\texttt{average}}\label{average}
494 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q average\q}).
495
496 \item [\normalfont\texttt{fastcluster.\textbf{weighted}}\,(\textit{X})]
497 \phantomsection\addcontentsline{toc}{subsection}{\texttt{weighted}}\label{weighted}
498 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q weighted\q}).
499
500 \item [\normalfont\texttt{fastcluster.\textbf{centroid}}\,(\textit{X})]
501 \phantomsection\addcontentsline{toc}{subsection}{\texttt{centroid}}\label{centroid}
502 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q centroid\q}).
503
504 \item [\normalfont\texttt{fastcluster.\textbf{median}}\,(\textit{X})]
505 \phantomsection\addcontentsline{toc}{subsection}{\texttt{median}}\label{median}
506 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q median\q}).
507
508 \item [\normalfont\texttt{fastcluster.\textbf{ward}}\,(\textit{X})]
509 \phantomsection\addcontentsline{toc}{subsection}{\texttt{ward}}\label{ward}
510 Alias for \texttt{fastcluster.\textbf{linkage}}\,(\textit{X, method=\q ward\q}).
511
512 \item [\normalfont\texttt{fastcluster.\textbf{linkage\_vector}}\,(\textit{X, method=\q single\q, metric=\q euclidean\q, extraarg=\q None\q})]
513 \phantomsection\addcontentsline{toc}{subsection}{\texttt{linkage\_vector}}\label{linkage_vector}
514 This performs hierarchical, agglomerative clustering on vector data with memory-saving algorithms. While the \hyperref[linkage]{\texttt{linkage}} method requires $\Theta(N^2)$ memory for clustering of $N$ points, this method needs $\Theta(ND)$ for $N$ points in $\mathbb R^D$, which is usually much smaller.
515
516 The argument $X$ has the same format as before, when $X$ describes vector data, ie.\ it is an $(N\times D)$ array. Also the output array has the same format. The parameter \textit{method} must be one of \textit{\q single\q}, \textit{\q centroid\q}, \textit{\q median\q}, \textit{\q ward\q}, ie.\ only for these methods there exist memory-saving algorithms currently. If \textit{method}, is one of \textit{\q centroid\q}, \textit{\q median\q}, \textit{\q ward\q}, the \textit{metric} must be \textit{\q euclidean\q}.
517
518 Like the \texttt{linkage} method, \texttt{linkage\_vector} does not treat NumPy's \maskedarrays{} as special and simply ignores the mask.
519
520 For single linkage clustering, any dissimilarity function may be chosen. Basically, every metric which is implemented in the method \pdist{} is reimplemented here. However, the metrics differ in some instances since a number of mistakes and typos (both in the code and in the documentation) were corrected in the \textit{fastcluster} package.\footnote{Hopefully, the SciPy metric will be corrected in future versions and some day coincide with the \textit{fastcluster} definitions. See the bug reports at \url{https://github.com/scipy/scipy/issues/2009}, \url{https://github.com/scipy/scipy/issues/2011}.}
521
522 Therefore, the available metrics with their definitions are listed below as a reference. The symbols $u$ and $v$ mostly denote vectors in $\mathbb R^D$ with coordinates $u_j$ and $v_j$ respectively. See below for additional metrics for Boolean vectors. Unless otherwise stated, the input array $X$ is converted to a floating point array (\texttt{X.dtype==\allowbreak numpy.double}) if it does has have already the required data type. Some metrics accept Boolean input; in this case this is stated explicitly below.
523
524 \begin{description}
525 \item[\normalfont\textit{\q euclidean\q}:] Euclidean metric, $L_2$ norm
526 \[
527 d(u,v) = \| u-v\|_2 = \sqrt{\sum_j (u_j-v_j)^2}
528 \]
529
530 \item[\normalfont\textit{\q sqeuclidean\q}:] squared Euclidean metric
531 \[
532 d(u,v) = \| u-v\|^2_2 = \sum_j (u_j-v_j)^2
533 \]
534
535 \item[\normalfont\textit{\q seuclidean\q}:] standardized Euclidean metric
536 \[
537 d(u,v) = \sqrt{\sum_j (u_j-v_j)^2 /V_j}
538 \]
539
540 The vector $V=(V_0,\ldots,V_{D-1})$ is given as the \textit{extraarg} argument. If no \textit{extraarg} is given, $V_j$ is by default the unbiased sample variance of all observations in the $j$-th coordinate, $V_j = \Var_i(X_{i,j})=\frac1{N-1}\sum_i(X_{i,j}^2-\mu(X_j)^2)$. (Here, $\mu(X_j)$ denotes as usual the mean of $X_{i,j}$ over all rows $i$.)
541
542 \item[\normalfont\textit{\q mahalanobis\q}:] Mahalanobis distance
543 \[
544 d(u,v) = \sqrt{(u-v)^{\mkern-3mu\top}V (u-v)}
545 \]
546 Here, $V=\textit{extraarg}$, a $(D\times D)$-matrix. If $V$ is not specified, the inverse of the covariance matrix \texttt{numpy.linalg.inv(numpy.\allowbreak cov(\allowbreak X, rowvar=False))} is used:
547 \[
548 (V^{-1})_{j,k} = \frac1{N-1} \sum_i (X_{i,j}-\mu(X_j))(X_{i,k}-\mu(X_k))
549 \]
550
551 \item[\normalfont\textit{\q cityblock\q}:] the Manhattan distance, $L_1$ norm
552 \[
553 d(u,v) = \sum_j |u_j-v_j|
554 \]
555
556 \item[\normalfont\textit{\q chebychev\q}:] the supremum norm, $L_\infty$ norm
557 \[
558 d(u,v) = \max_j |u_j-v_j|
559 \]
560
561 \item[\normalfont\textit{\q minkowski\q}:] the $L_p$ norm
562 \[
563 d(u,v) = \left(\sum_j |u_j-v_j|^p\right)^{1/p}
564 \]
565 This metric coincides with the \textit{cityblock}, \textit{euclidean} and \textit{chebychev} metrics for $p=1$, $p=2$ and $p=\infty$ (\texttt{numpy.inf}), respectively. The parameter $p$ is given as the \textit{\q extraarg\q} argument.
566
567 \item[\normalfont\textit{\q cosine\q}]
568 \[
569 d(u,v) = 1 - \frac{\langle u,v\rangle}{\|u\|\cdot\|v\|} = 1 - \frac{\sum_j u_jv_j}{\sqrt{\sum_j u_j^2\cdot \sum_j v_j^2}}
570 \]
571
572 \item[\normalfont\textit{\q correlation\q}:] This method first mean-centers the rows of $X$ and then applies the \textit{cosine} distance. Equivalently, the \textit{correlation} distance measures $1-{}$\textrm{(Pearson's correlation coefficient)}.
573 \[
574 d(u,v) = 1 - \frac{\langle u-\mu(u),v-\mu(v)\rangle}{\|u-\mu(u)\|\cdot\|v-\mu(v)\|},
575 \]
576
577 \item[\normalfont\textit{\q canberra\q}]
578 \[
579 d(u,v) = \sum_j\frac{|u_j-v_j|}{|u_j|+|v_j|}
580 \]
581 Summands with $u_j=v_j=0$ contribute 0 to the sum.
582
583 \item[\normalfont\textit{\q braycurtis\q}]
584 \[
585 d(u,v) = \frac{\sum_j |u_j-v_j|}{\sum_j |u_j+v_j|}
586 \]
587
588 \item[\textnormal{(user function):}] The parameter \textit{metric} may also be a function which accepts two NumPy floating point vectors and returns a number. Eg.\ the Euclidean distance could be emulated with
589 \begin{quote}
590 \texttt{fn = lambda u, v: numpy.sqrt(((u-v)*(u-v)).sum())}\\
591 \texttt{linkage\_vector(X, method=\q single\q, metric=fn)}
592 \end{quote}
593 This method, however, is much slower than the built-in function.
594
595 \item[\normalfont\textit{\q hamming\q}:] The Hamming distance accepts a Boolean array (\texttt{X.\allowbreak dtype\allowbreak ==\allowbreak bool}) for efficient storage. Any other data type is converted to \texttt{numpy.double}.
596 \[
597 d(u,v) = |\{j\mid u_j\neq v_j\}|
598 \]
599
600 \end{description}
601 The following metrics are designed for Boolean vectors. The input array is converted to the \texttt{bool} data type if it is not Boolean already. Use the following abbreviations for the entries of a contingency table:
602 \begin{align*}
603 a &= |\{j\mid u_j\land v_j \}| & b &= |\{j\mid u_j\land(\lnot v_j)\}|\\
604 c &= |\{j\mid (\lnot u_j)\land v_j \}| & d &= |\{j\mid (\lnot u_j)\land(\lnot v_j)\}|
605 \end{align*}
606 Recall that $D$ denotes the number of dimensions, hence $D=a+b+c+d$.
607
608
609 \begin{description}
610 \item[\normalfont\textit{\q jaccard\q}]
611 \phantomsection\label{jaccard}
612 \[
613 d(u,v) = \frac{b+c}{b+c+d}
614 \]
615 \[
616 d(0,0) = 0
617 \]
618
619 \item[\normalfont\textit{\q yule\q}]
620 \phantomsection\label{yule}
621 \begin{align*}
622 d(u,v) &= \frac{2bc}{ad+bc} && \text{if $bc \neq 0$}\\
623 d(u,v) &= 0 && \text{if $bc = 0$}
624 \end{align*}
625 Note that the second clause $d(u,v)=0$ if $bc = 0$ was introduced in fastcluster version 1.2.0. Before, the result was NaN if the denominator in the formula was zero. fastcluster is following a \href{https://github.com/scipy/scipy/commit/3b22d1da98dc1b5f64bc944c21f398d4ba782bce}{change in SciPy 1.6.3} here.
626
627 \item[\normalfont\textit{\q dice\q}]
628 \begin{gather*}
629 d(u,v) = \frac{b+c}{2a+b+c}\\
630 d(0,0) = 0
631 \end{gather*}
632
633 \item[\normalfont\textit{\q rogerstanimoto\q}]
634 \[
635 d(u,v) = \frac{2(b+c)}{b+c+D}
636 \]
637
638 \item[\normalfont\textit{\q russellrao\q}]
639 \[
640 d(u,v) = \frac{b+c+d}{D}
641 \]
642
643 \item[\normalfont\textit{\q sokalsneath\q}]
644 \begin{gather*}
645 d(u,v) = \frac{2(b+c)}{a+2(b+c)}\\
646 d(0,0) = 0
647 \end{gather*}
648
649 \item[\normalfont\textit{\q kulsinski\q}]
650 \[
651 d(u,v) = \frac 12\cdot\left(\frac b{a+b} + \frac c{a+c}\right)
652 \]
653
654 \item[\normalfont\textit{\q matching\q}]
655 \[
656 d(u,v) = \frac{b+c}{D}
657 \]
658 Notice that when given a Boolean array, the \textit{matching} and \textit{hamming} distance are the same. The \textit{matching} distance formula, however, converts every input to Boolean first. Hence, the vectors $(0,1)$ and $(0,2)$ have zero \textit{matching} distance since they are both converted to $(\mathrm{False}, \mathrm{True})$ but the \textit{hamming} distance is $0.5$.
659
660 \item[\normalfont\textit{\q sokalmichener\q}] is an alias for \textit{\q matching\q}.
661
662 \end{description}
663
664 \end{methods}
665
666 \section{Behavior for NaN and infinite values}\label{sec:infnan}
667
668 Whenever the fastcluster package encounters a NaN value as the distance between nodes, either as the initial distance or as an updated distance after some merging steps, it raises an error. This was designed intentionally, even if there might be ways to propagate NaNs through the algorithms in a more or less sensible way. Indeed, since the clustering result depends on every single distance value, the presence of NaN values usually indicates a dubious clustering result, and therefore NaN values should be eliminated in preprocessing.
669
670 In the R interface for vector input, coordinates with {\NA} value are interpreted as missing data and treated in the same way as R's {\dist} function does. This results in valid output whenever the resulting distances are not NaN. The Python interface does not provide any way of handling missing coordinates, and data should be processed accordingly and given as pairwise distances to the clustering algorithms in this case.
671
672 The fastcluster package handles node distances and coordinates with infinite values correctly, as long as the formulas for the distance updates and the metric (in case of vector input) make sense. In concordance with the statement above, an error is produced if a NaN value results from performing arithmetic with infinity. Also, the usual proviso applies: internal formulas in the code are mathematically equivalent to the formulas as stated in the documentation only for finite, real numbers but might produce different results for $\pm\infty$. Apart from obvious cases like single or complete linkage, it is therefore recommended that users think about how they want infinite values to be treated by the distance update and metric formulas and then check whether the fastcluster code does exactly what they want in these special cases.
673
674 \section{Differences between the two interfaces}
675 \begin{itemize}
676 \item The \textit{\q mcquitty\q} method in R is called \textit{\q weighted\q} in Python.
677 \item R and SciPy use different conventions for the ``Euclidean'' methods \textit{\q centroid\q}, \textit{\q median\q}! R assumes that the dissimilarity matrix consists of squared Euclidean distances, while SciPy expects non-squared Euclidean distances. The fastcluster package respects these conventions and uses different formulas in the two interfaces.
678
679 The \textit{\q ward\q} method in the Python interface is identical to \textit{\q ward.D2\q} in the R interface.
680
681 If the same results in both interfaces ought to be obtained, then the \hyperref[hclust]{\texttt{hclust}} function in R must be input the entry-wise square of the distance matrix, \verb!d^2!, for the \textit{\q ward.D\q}, \textit{\q centroid\q} and \textit{\q median\q} methods, and later the square root of the height field in the dendrogram must be taken. The \hyperref[hclust.vector]{\texttt{hclust.vector}} method calculates non-squared Euclidean distances, like R's \dist{} method and identically to the Python interface. See the \hyperref[squared]{example} in the \hyperref[hclust.vector]{\texttt{hclust.vector}} documentation above.
682
683 For the \textit{\q average\q} and \textit{\q weighted\q} alias \textit{\q mcquitty\q} methods, the same, non-squared distance matrix \texttt{d} as in the Python interface must be used for the same results. The \textit{\q single\q} and \textit{\q complete\q} methods only depend on the relative order of the distances, hence it does not make a difference whether the method operates on the distances or the squared distances.
684
685 The code example in the R documentation (enter \texttt{?hclust} or \texttt{ex\-am\-ple(hclust)} in R) contains another instance where the squared distance matrix is generated from Euclidean data.
686
687 \item The Python interface is not designed to deal with missing values, and NaN values in the vector data raise an error message. The \hyperref[hclust.vector]{\texttt{hclust.vector}} method in the R interface, in contrast, deals with NaN and the (R specific) {\NA} values in the same way as the \dist{} method does. Confer the documentation for \dist{} for details.
688 \end{itemize}
689
690 \section{References}
691 \begin{trivlist}
692 \item
693 \textit{NumPy: Scientific computing tools for Python}, \url{http://numpy.org/}.
694
695 \item
696 Eric Jones, Travis Oliphant, Pearu Peterson et al., \textit{SciPy: Open Source Scientific Tools for Python}, 2001, \url{https://www.scipy.org}.
697
698 \item
699 \textit{R: A Language and Environment for Statistical Computing}, R Foundation for Statistical Computing, Vienna, 2011, \url{https://www.r-project.org}.
700 \end{trivlist}
701 \end{document}
702 %%% Local variables:
703 %%% mode: latex
704 %%% TeX-master: "fastcluster.Rtex"
705 %%% TeX-PDF-mode: t
706 %%% End: