Statistics tutorial · Chapter 11
Multivariate analyses
The analyses in this chapter deal with several variables measured in the same subjects, with no privileged response variable. Principal Component Analysis (PCA) summarizes correlated variables by a few uncorrelated components; Hierarchical Clustering and K-means Clustering look for groups of subjects (or of variables) that resemble each other. All three use a Multivariable table (chapter 03); PCA is in Analysis › Describe and Explore, the two clustering analyses in Analysis › Clusters. These are descriptive methods: they give no P value (except the principal component regression) and prove neither the existence of "factors" nor that of groups. General notions (variance, standard deviation, percentiles) are covered in chapter 10; correlation and multiple regression, in chapter 16.
The examples use the sample data "Clinical study (continuous, categorical and outcome variables)" (start window, Multivariable table, "an example"): 40 subjects described by Age (years), Weight (kg), Height (m), Sex (M or F), Response (0 or 1), Time (follow-up duration) and Event (0 or 1).
Preparing the data#
The three analyses choose variables and rows in the same way:
- Variables: tick them in "Variables (empty = all continuous)" (Data tab). If no box is ticked, Variance takes all the variables ticked in the Data sets tab, except qualitative variables (type Categorical, or Auto with text). A variable coded 0/1, such as Response or Event, is numeric: it is then included. The two clustering analyses also leave out variables of type Label; PCA does not (see its pitfalls).
- Rows: only rows complete for all the selected variables are analyzed; a missing value removes the whole row, with no imputation.
- Row names (clustering): the first variable of type Label, otherwise the row label, otherwise "Row 1", "Row 2"… The sample data have no Label variable: the rows are called "Row 1", "Row 2"… To display identifiers, add a column of type Label (chapter 03).
Scaling. Variance (PCA) and Euclidean distance (clustering) add up the contributions of the variables in their own units: a variable with a large variance overwhelms the others. In the example, the variance of Height is 0.0057 m², that of Age 119 years²; expressing height in centimeters would multiply its variance by 10,000 and change the result. Standardizing each variable (z = (x − mean) / standard deviation, with the standard deviation computed with n − 1) gives it a variance of 1 and makes the analysis independent of the units: this is the default of all three analyses, and the only reasonable choice when the units differ. It has a cost: a noise variable then weighs as much as an informative one, so it is important to keep only relevant variables. Centering only, or doing nothing, is justified only for variables with the same unit whose differences in variance are meaningful.
Principal Component Analysis (PCA)#
Principal component analysis (PCA) replaces p correlated variables by p new variables, the principal components, which are linear combinations of the original variables, uncorrelated with each other and ranked by decreasing variance. When the variables are strongly related, the first two or three summarize most of their variation: each subject is placed on a plane by its first two coordinates (its scores), and the plot of the loadings shows which variables vary together. PCA describes a correlation structure; it tests nothing (Jolliffe, 2002; Jolliffe and Cadima, 2016).
When to use it#
- Several correlated quantitative variables measured in the same subjects (body measurements, assays, clinical scores) that you want to summarize or visualize: which variables go together, which subjects resemble each other, which are atypical.
- To replace highly correlated predictors by a few components before a regression ("Dependent variable (PCR)"), with the precautions described below.
- Not for qualitative variables (correspondence analysis is not offered), nor for comparing groups (chapter 14).
- Not as a factor analysis: Variance offers neither a latent factor model nor axis rotation (varimax).
Assumptions and checks#
PCA requires no distributional law, but its result is meaningful only if:
- the relationships are linear: PCA summarizes Pearson correlations (or covariances); look at the scatter plots (Bubble plot graph of the table) and the correlation matrix (Correlation, chapter 16);
- no outlier dominates: one extreme subject can create a component on its own; check the isolated points of the score plot;
- the variables are standardized whenever their units differ (default option);
- the variables are correlated: otherwise all the eigenvalues stay close to 1 and PCA summarizes nothing;
- the sample size is sufficient: with few subjects, eigenvalues and eigenvectors vary a lot from one sample to another, and two components with similar eigenvalues can rotate or swap. Variance requires 3 complete rows and 2 variables; aim for many more subjects than variables.
Step by step in Variance#
- Create a Multivariable table (one row per subject, one column per variable) or open the sample data.
- Choose Analysis › Describe and Explore › Principal Component Analysis (PCA).
- Data tab:
- "Variables (empty = all continuous)": the PCA variables (see "Preparing the data");
- "Dependent variable (PCR)": optional, the title of a variable typed on the keyboard (case-insensitive). This variable is excluded from the PCA, then regressed on the retained components; rows where it is missing are also removed from the PCA;
- "Method": "Standardize: center and scale (correlation matrix)" (default) or "Center only (covariance matrix)".
- Components tab:
- "Select principal components": "Parallel analysis (Monte Carlo)" (default), "Kaiser rule (eigenvalues above 1)", "Eigenvalues greater than", "Fixed number of components" or "Components explaining at least this % of variance";
- "Value (threshold, number or %)" (1 by default): depending on the rule, the threshold, the number of components (integer part: 2.7 gives 2) or the percentage (80 for 80%);
- "Parallel analysis: simulations" (200 by default, from 10 to 10,000), "Parallel analysis: percentile" (95 by default, from 50 to 99.9) and "Random seed" (1 by default) are used only for parallel analysis.
- Options tab: "Significant digits" and "P value format" (useful only for the regression). No confidence level to set: the regression intervals are at 95%.
- Data sets tab, then OK. Variance creates the results sheet and the score plot (PC2 against PC1). The other output tables are plotted from their tab (⊞) with Plot These Results; to name the variables on the loading plot or on the biplot, tick "Show the row label next to each point" in Format Graph.
Calculations#
Notation: n subjects (complete rows), p variables, xij the value of variable j in subject i.
mean, standard deviation x̄j = Σi xij / n sj = √[ Σi (xij − x̄j)² / (n − 1) ]
analyzed variables zij = (xij − x̄j) / sj "Standardize" (default)
zij = xij − x̄j "Center only"
p × p matrix C = Zᵀ·Z / (n − 1) correlations (Standardize) or covariances (Center only)
decomposition C·vk = λk·vk with λ1 ≥ λ2 ≥ … ≥ λp ≥ 0 and ‖vk‖ = 1
share of variance πk = λk / (λ1 + … + λp) (the sum of the λ is p in Standardize mode)
cumulative share Πk = π1 + … + πk
loading ljk = vjk · √λk
score tik = Σj zij · vjk (mean 0, variance λk)
Eigenvalues and eigenvectors are obtained by the cyclic Jacobi method; the result is that of a singular value decomposition of Z (λk = σk² / (n − 1)). A negative eigenvalue due to rounding, or one below 10⁻¹² of the largest (the rounding noise of a matrix of incomplete rank, for instance with fewer rows than variables), is set to 0. The sign of an eigenvector is arbitrary: Variance makes its largest coordinate (in absolute value; among coordinates equal within 10⁻⁹, the first one) positive; other software may flip an entire component without changing the interpretation.
In Standardize mode, ljk is the correlation between variable j and component k: the sum of the ljk² is λk over the variables and 1 over all the components; over the retained components, it gives the share of the variable's variance that they represent. In Center only mode, ljk is the covariance of xj with tk / √λk, in the unit of the variable (divide by sj to obtain a correlation).
Number of retained components ("Selected" row):
Kaiser m = number of λk > 1
Eigenvalues greater than m = number of λk > Value
Fixed number of components m = integer part of Value (at most p)
% of variance m = smallest k such that Πk ≥ Value / 100
Parallel analysis for b = 1 … B ("simulations"): draw n × p independent normal
values (standard deviation 1, or sj in Center only mode) and
compute the eigenvalues λk(b) of the same matrix;
threshold qk = chosen percentile of the B values λk(b);
m = number of consecutive initial components with λk > qk
in all cases m ≥ 1: PC1 is always marked "Yes"
Kaiser's rule (1960) assumes a correlation matrix, where a component with an eigenvalue below 1 summarizes less than a single variable; in Center only mode it makes no sense, and a "Note" row says so if you choose it. Cattell's scree test (1966) is read on the "Scree plot" graph: keep the components before the elbow where the curve flattens. Horn's parallel analysis (1965) keeps the components that explain more variance than the component of the same rank in uncorrelated data; the 95th percentile, rather than Horn's mean, rules out noise better (Glorfeld, 1995). The percentile follows the (n + 1)·p method (chapter 10); the threshold varies slightly with the seed.
Biplot. The "Biplot" table superimposes the scores on PC1 and PC2 and the loadings multiplied by c = 0.9 × (largest |score|) / (largest |loading|), maxima taken over PC1 and PC2, so that the two clouds have the same extent. This is only a display convenience: the plot does not have the exact properties of Gabriel's biplot (1971).
Principal component regression. Variance fits by least squares Y = b0 + b1·t1 + … + bm·tm on the m retained components (chapter 16). Since the scores are uncorrelated, bk = cov(Y, tk) / λk does not depend on the other components included. The coefficients refer to the components: Variance does not convert them into coefficients of the variables.
Reading the results#
- "Components" tab (one column per component, PC1 to PCp):
- "Eigenvalue": λk, the variance of the component (in squared units in Center only mode);
- "Proportion of variance (%)" and "Cumulative proportion (%)": 100·πk and 100·Πk;
- "Parallel analysis threshold" (parallel analysis only): the threshold qk;
- "Selected": "Yes" for the m retained components; this is not a test. A rule may retain no component (parallel analysis on data with no structure, for example): all the boxes are then "No".
- "Loadings" tab: one row per variable, the loadings ljk.
- "Eigenvectors" tab: the coefficients vjk, the weights of each standardized (or centered) variable in the computation of the scores.
- "Principal component regression" tab (if "Dependent variable (PCR)" is filled in): "Dependent variable: …", then "Intercept", "PC1"… with "Estimate", "Std. Error", "95% CI" and "P value"; under "Goodness of fit", "R squared", "Adjusted R squared", "Sy.x", "F test P value" and "Components used" (m).
- Output tables: "Score plot" (X = score on PC1, Y = "PC2"), "Scree plot" ("Component", "Eigenvalue"), "Loading plot" ("PC1 loading", "PC2 loading", one row per variable, titled with its name) and "Biplot" (X "PC1"; "Scores" and "Loadings (scaled)"), then "Scores", a Multivariable table of the scores on all the components ("PC1", "PC2"…; one row per individual, titled as in the analyzed table), which lends itself to other analyses (regression on the components, group comparison on PC3…).
Reading the plots. On the loading plot (Standardize mode), the square of the distance from a variable to the origin is the share of its variance contained in the PC1–PC2 plane: close to the origin, the variable is poorly represented. For two well-represented variables a and b, close directions indicate a positive correlation, opposite directions a negative correlation, perpendicular directions a weak correlation (la1·lb1 + la2·lb2 approaches their correlation). On the score plot, nearby subjects have similar profiles; an isolated point should be checked. The biplot is read qualitatively: a subject located in the direction of a variable tends to have a high value of it.
Worked example#
In the sample data, tick Age, Weight, Height and Time in "Variables (empty = all continuous)" (Sex is qualitative; Response and Event are 0/1 indicators) and keep the other options. The correlations (Correlation analysis) form two blocks, Weight–Height and Age–Time, weakly related to each other:
Age Weight Height Time
Age 1 −0.110 −0.208 −0.739
Weight −0.110 1 0.860 0.226
Height −0.208 0.860 1 0.292
Time −0.739 0.226 0.292 1
Variance displays:
Components PC1 PC2 PC3 PC4
Eigenvalue 2.226 1.384 0.2562 0.134
Proportion of variance (%) 55.64 34.61 6.404 3.35
Cumulative proportion (%) 55.64 90.25 96.65 100
Parallel analysis threshold 1.582 1.236 0.9934 0.8133
Selected Yes Yes No No
Loadings PC1 PC2 PC3 PC4
Age -0.6487 0.6768 0.3451 0.04483
Weight 0.7707 0.5836 0.01828 -0.2551
Height 0.8242 0.4996 -0.06709 0.258
Time 0.7291 -0.5796 0.3636 0.01788
Eigenvectors PC1 PC2 PC3 PC4
Age -0.4348 0.5753 0.6819 0.1225
Weight 0.5166 0.4961 0.03611 -0.697
Height 0.5525 0.4247 -0.1326 0.7049
Time 0.4887 -0.4926 0.7184 0.04885
By hand (means 50.7 years, 64.8525 kg, 1.707 m and 53.375; standard deviations 10.908, 5.8704, 0.07542 and 11.072):
sum of the eigenvalues = trace of R = 4 share of PC1 = 2.2256 / 4 = 55.64%
loading of Height on PC1 = 0.5525 × √2.2256 = 0.5525 × 1.4918 = 0.8242
Σ loadings² on PC1 = 0.4208 + 0.5940 + 0.6793 + 0.5316 = 2.2257 ≈ λ1
subject 1 (60 years, 70.5 kg, 1.78 m, Time 52):
z = (60 − 50.7) / 10.908 = 0.8526 (70.5 − 64.8525) / 5.8704 = 0.9620
(1.78 − 1.707) / 0.07542 = 0.9679 (52 − 53.375) / 11.072 = −0.1242
score on PC1 = 0.8526 × (−0.4348) + 0.9620 × 0.5166 + 0.9679 × 0.5525 + (−0.1242) × 0.4887
= −0.3707 + 0.4970 + 0.5347 − 0.0607 = 0.6003 (1st row of "Score plot")
correlations reconstructed by the PC1–PC2 plane:
Weight–Height ≈ 0.7707 × 0.8242 + 0.5836 × 0.4996 = 0.927 (observed 0.860)
Age–Time ≈ (−0.6487) × 0.7291 + 0.6768 × (−0.5796) = −0.865 (observed −0.739)
Interpretation. The rules agree on two components: λ1 and λ2 exceed their thresholds (1.582 and 1.236) and the value 1, λ3 = 0.256 stays far below its own (0.9934), and the scree plot shows a clear elbow after PC2. The PC1–PC2 plane contains 90.2% of the total variance and 87 to 93% of that of each variable (sums of squares of the first two loadings: from 0.868 for Time to 0.935 for Weight). On the loading plot, Weight and Height point in the same direction, Age and Time in opposite directions, and the two pairs are almost perpendicular: the four measurements carry mainly two pieces of information, body size and the Age–follow-up pair. The axes do not coincide with these blocks, however: PC1 contrasts young, tall, heavy and long-followed subjects with the others, PC2 contrasts age and body size with follow-up duration; the weak correlations between blocks are enough to mix the two pieces of information. A component is a direction of maximal variance, not a biological factor. Subject 13 (41 years, 78 kg, 1.83 m, Time 67) has the highest score on PC1 (3.046).
Without standardization ("Center only (covariance matrix)"), PC1 ("Eigenvalue" 211.4, 76.6% of the variance) is almost only Age and Time (coefficients -0.6955 and 0.7133), the variables with the largest variance (119 and 123); Height (0.0057 m²) alone forms PC4 ("Eigenvalue" 0.001406). Kaiser would retain three components (211.4, 37.6 and 27.05 exceed 1).
Pure noise. On 40 rows of 4 simulated independent normal variables, the eigenvalues were 1.241, 1.027, 0.9178 and 0.8138: Kaiser retained two noise components, parallel analysis none (thresholds 1.582 and 1.236): "Selected" is "No" for all the components.
Regression on components. With Age, Height and Time as variables and "Dependent variable (PCR)" = Weight, parallel analysis retains only one component (λ2 = 0.863, below its threshold of 1.092). PC1, mostly Age and Time (loadings -0.8865 and 0.9129), explains little of the weight ("R squared" 0.1562). PC2, discarded, is almost Height alone (loading 0.8581): with "Fixed number of components" and "Value" = 2, "R squared" rises to 0.745. The components are chosen from the variance of the predictors, without looking at Y (Jolliffe, 1982).
Reporting the results#
"A principal component analysis of the standardized variables (age, weight, height and follow-up duration; n = 40) retained two components by parallel analysis (200 simulations, 95th percentile), which explained 55.6% and 34.6% of the variance (90.2% in total). Weight and height (r = 0.86) had loadings of 0.77 and 0.82 on the first component; age and follow-up duration (r = −0.74) were opposed on both (−0.65 and 0.73 on the first, 0.68 and −0.58 on the second)."
Common pitfalls#
- Not standardizing variables with different units: the first components then reflect the variables with the largest variance.
- Taking PCA for a test: it produces components even from noise; "Selected" applies a decision rule, with no P value, and the shares of variance describe the sample.
- Relying on Kaiser's rule alone: it retains too many components when the variables are numerous or weakly correlated; cross-check parallel analysis, the scree plot and interpretability.
- Interpreting a component as a biological factor: its sign is arbitrary, and two components with similar eigenvalues are unstable.
- Keeping the default variables: the 0/1 indicators (Response, Event) are included; untick them if they do not belong in the analysis. Variables of type Label and qualitative variables are always left out.
- Keeping a constant variable: it has no variance; Variance leaves it out and flags it with a warning ("Constant variables left out: …").
- Regression on components: compare "R squared" with more components; the coefficients refer to the components, not to the variables.
Hierarchical Clustering#
Agglomerative hierarchical clustering starts with as many groups as items (subjects, or variables), then at each step merges the two closest groups, until only one is left. It produces a hierarchy of nested partitions, represented by a dendrogram whose node heights are the merge distances; cutting the tree gives k groups. Two choices determine the tree: the distance between items and the linkage method, which defines the distance between two groups (Kaufman and Rousseeuw, 1990).
When to use it#
- Explore whether subjects form groups, without fixing their number in advance, and see at what level they separate.
- Group variables that vary together ("Columns (variables)"); order the rows of a heat map.
- Not to prove that groups exist, nor to classify new subjects.
Assumptions and checks#
The method rests on no probabilistic model: its result depends entirely on the variables, their scaling, the distance, the linkage method and the number of groups.
- The distance must reflect the resemblance sought: Euclidean for close values, correlation for profiles of the same shape whatever their level.
- Ward, Centroid and Median assume Euclidean distances: Variance squares the chosen distance before applying them, which has a geometric justification only with "Euclidean".
- Outliers stay isolated until the last merges; single linkage ("Single") chains points step by step and produces elongated groups.
- Stability should be checked: rerun with another linkage method, without a few variables or subjects, or with K-means Clustering; groups that change with every variation are artifacts. The closer the cophenetic correlation coefficient is to 1, the less the tree distorts the original distances.
Step by step in Variance#
- Multivariable table, one row per subject.
- Choose Analysis › Clusters › Hierarchical Clustering.
- Data tab:
- "Variables (empty = all continuous)";
- "Cluster": "Rows" (the subjects, default) or "Columns (variables)";
- "Scaling": "Standardize (z scores)" (default), "Center (subtract the mean)" or "No scaling". Scaling always applies to each variable, even when the variables are being clustered.
- Method tab:
- "Distance": "Euclidean" (default), "Manhattan", "Pearson correlation", "Cosine" or "Minkowski (p = 3)";
- "Linkage": "Complete", "Single", "Simple average (WPGMA)", "Centroid", "Median", "Group average (UPGMA)" or "Ward's minimum variance" (default).
- Clusters tab: "Number of clusters" (3 by default), the number of groups of the cut.
- Options tab ("P value format" is irrelevant), Data sets tab, then OK. Variance creates the results sheet and a heat map (Heat map of variables) of the "Clustered data" output table.
Calculations#
Distances between two items x and y (scaled values, q coordinates):
Euclidean d = √[ Σ (xj − yj)² ]
Manhattan d = Σ |xj − yj|
Minkowski (p = 3) d = [ Σ |xj − yj|³ ]^(1/3)
Pearson correlation d = 1 − r(x, y) r: Pearson correlation between the two profiles
Cosine d = 1 − Σ xj·yj / (‖x‖·‖y‖)
Between two rows, r is computed over the variables of each row: at least three are needed (with two, all distances are 0 or 2). Between two standardized variables, the Euclidean distance is √[2 (n − 1)(1 − r)], an increasing function of 1 − r; with either distance, two strongly negatively correlated variables are far apart. An item whose values are all equal (all zero for the cosine) has no correlation (or cosine) distance to the others: the analysis is then refused.
With "Standardize" or "Center", the mean and the standard deviation of each variable are computed on its values minus the first one (an exact subtraction for nearby values): a variable close to 10⁹ keeps all its digits.
At each step, the two closest groups i and j are merged (in case of a tie, the first pair in table order), then the distance from the new group to each other group k is recomputed by the Lance and Williams formula (1967), with ni, nj and nk the group sizes:
Single d(k, i∪j) = min(dki, dkj)
Complete d(k, i∪j) = max(dki, dkj)
Simple average (WPGMA) d(k, i∪j) = (dki + dkj) / 2
Group average (UPGMA) d(k, i∪j) = (ni·dki + nj·dkj) / (ni + nj)
Centroid * D(k, i∪j) = (ni·Dki + nj·Dkj) / (ni + nj) − ni·nj·Dij / (ni + nj)²
Median * D(k, i∪j) = (Dki + Dkj) / 2 − Dij / 4
Ward's minimum variance * D(k, i∪j) = [(ni + nk)·Dki + (nj + nk)·Dkj − nk·Dij] / (ni + nj + nk)
* computed on D = d²; the displayed height is √D
With the Euclidean distance, Centroid gives the distance between the centers of gravity of the two groups, and Ward gives √(2·ΔSS), where ΔSS = ni·nj / (ni + nj) × ‖ci − cj‖² is the increase in the within-group sum of squares caused by the merge (Ward, 1963); these are the heights of ward.D2 in R (Murtagh and Legendre, 2014). With Centroid and Median, a merge can occur lower than the previous one (inversion), which makes the tree hard to read.
The cut into k groups applies the first n − k merges; the groups are numbered in the order in which they appear along the dendrogram. The cophenetic correlation coefficient (Sokal and Rohlf, 1962) is the Pearson correlation, over the n(n − 1)/2 pairs, between the original distance d(i, j) (not squared) and the cophenetic distance, the height of the merge that first joins i and j.
Reading the results#
- "Summary" tab: "Items clustered" (number of rows, or of variables), "Cophenetic correlation coefficient" and "Number of clusters".
- "Cluster membership" tab: the group ("Cluster") of each item, in dendrogram order rather than table order.
- "Fusion table" tab: for each step ("Step 1" to "Step n − 1"), the two groups merged ("Joined", "With"), the merge height ("Height") and the size of the group created ("Size"). A group already formed is named "Node s" there, s being the step that created it (not to be confused with the groups of "Cluster membership"). A large jump in height between two steps suggests cutting just before.
- "Clustered data" output table: the scaled values (z by default, not the original values), rows (or columns, if the variables are clustered) in dendrogram order.
- Heat map: the rows follow the order of the analysis; each column is standardized again for display (fixed colors from −2.5 to +2.5, diverging blue-white-red palette by default; a palette chosen in Format Graph or the Inspector, Viridis included, is respected). The "Dendrogram (hierarchical clustering of rows)" box of the Inspector ("Heat map" section) draws the dendrogram of the analysis (its distance, its linkage method, its heights) when the analysis clusters the rows; likewise for the Dendrogram graph of the "Clustered data" table. When the analysis clusters the columns, or on a data table, the dendrogram is recomputed (Euclidean distance on standardized values, Group average).
Worked example#
By hand. Enter five points in a table with two variables X and Y: A (1, 1), B (2, 1), C (4, 3), D (7, 5) and E (8, 6); choose "Scaling": "No scaling" and keep "Euclidean". The distances are:
A B C D E
A 0
B 1 0
C 3.606 2.828 0
D 7.211 6.403 3.606 0
E 8.602 7.810 5 1.414 0
All the methods first merge A and B (height 1), then D and E (1.414), then {A, B} with C, and finally the two groups; only the last two heights differ:
merge of {A, B} with C
Single min(3.606, 2.828) = 2.828
Complete max(3.606, 2.828) = 3.606
UPGMA (3.606 + 2.828) / 2 = 3.217
Ward center of {A, B} = (1.5, 1); ‖(1.5, 1) − (4, 3)‖² = 10.25
ΔSS = 2 × 1 / 3 × 10.25 = 6.833 height = √(2 × 6.833) = 3.697
merge of {A, B, C} with {D, E}
Single smallest of the six distances: d(C, D) = 3.606
Complete largest: d(A, E) = 8.602
UPGMA (7.211 + 8.602 + 6.403 + 7.810 + 3.606 + 5) / 6 = 6.439
Ward centers (2.333, 1.667) and (7.5, 5.5); distance² = 41.39
ΔSS = 3 × 2 / 5 × 41.39 = 49.67 height = √(2 × 49.67) = 9.967
With Ward (default), Variance displays "Cophenetic correlation coefficient" 0.8499 and:
Fusion table Joined With Height Size
Step 1 Row 1 Row 2 1 2
Step 2 Row 4 Row 5 1.414 2
Step 3 Node 1 Row 3 3.697 3
Step 4 Node 3 Node 2 9.967 5
"Node 1" is the group created at step 1 ({A, B}). Cut into two groups ("Number of clusters" = 2), the tree gives {A, B, C} and {D, E} with all the methods; Single, Complete and UPGMA recover the heights above.
Sample data. With Weight and Height, the default options (z, Euclidean, Ward) and "Number of clusters" = 2, "Cophenetic correlation coefficient" is 0.6923. The last merges occur at heights 2.095, 3.741, 5.383 and 9.666: the large final jump suggests two groups. The first contains 27 subjects (20 men and 7 women), the second 13 women (the "M" and "F" names of the rows come from the Sex variable): the cut isolates the smallest body sizes without recovering sex. Its within-group sum of squares is 78 − 9.666² / 2 = 31.29 (78 = (n − 1) × 2 standardized variables); k-means does better (26.03), with different groups.
Variables. Clustering Age, Weight, Height and Time ("Columns (variables)", "Pearson correlation", "Group average (UPGMA)"), Weight and Height merge at 0.1403 (1 − 0.860), Time joins them at 0.7414 and Age comes last (1.352): strongly related to Time (r = −0.739), it is nevertheless the farthest from it, since the distance is 1 − r.
Reporting the results#
"The 40 subjects were clustered by agglomerative hierarchical clustering (standardized weight and height, Euclidean distance, Ward's method). Cut at the level of the largest height jump, the dendrogram (cophenetic correlation coefficient 0.69) separated 13 women of small body size from the other 27 subjects. A k-means clustering gave a different partition; these groups are therefore exploratory."
Common pitfalls#
- Believing the groups exist because the tree shows them: every clustering produces a dendrogram and groups, even on data with no structure (see the Age example in the next section). Check stability.
- Testing the clustering variables between the groups: the groups were built to differ on these variables; a t test or an ANOVA on these same variables gives artificially small P values. Compare the groups on other variables, or validate them on other data.
- Mixing up the numbers: "Node s" in "Fusion table" designates the group created at step s, not group s of the cut ("Cluster membership").
- Taking the recomputed dendrogram of a heat map for that of the analysis: only the graph of the "Clustered data" table of a row clustering shows the tree of the analysis.
- Not standardizing variables with different units, or using Ward, Centroid or Median with a non-Euclidean distance.
- Choosing the linkage method after the fact, because it gives the expected groups.
K-means Clustering#
K-means divides the n rows into k groups, k being fixed in advance, so as to minimize the sum of squared Euclidean distances from each point to the center (the mean) of its group. The algorithm starts from randomly drawn centers and improves them until stable; it reaches a local minimum that depends on the starting point, hence several starts, of which Variance keeps the best. To help choose k, the analysis also computes, for k = 1 to kmax, the within-group sum of squares (elbow criterion) and the mean silhouette.
When to use it#
- Quantitative variables for which the Euclidean distance is meaningful, with expected groups that are compact, roughly spherical and of comparable spread.
- Number of groups known, or to be explored with the elbow and the silhouette.
- Not for elongated, nested or very unequal-sized groups, nor for qualitative variables.
Assumptions and checks#
- Scale: standardize the variables (default option), otherwise the most dispersed one imposes the groups.
- Shape of the groups: k-means splits the space into convex regions around the centers; it cuts an elongated group and separates groups of unequal sizes poorly. Look at the data colored by group.
- Outliers: they attract a center or form a group on their own.
- Local minimum: keep several starts ("Random starts") and check that the solution does not change with the seed.
- Quality of the assignment: a negative silhouette flags a subject that is, on average, closer to another group than to its own.
Step by step in Variance#
- Multivariable table, one row per subject.
- Choose Analysis › Clusters › K-means Clustering.
- Data tab: "Variables (empty = all continuous)" and "Scaling" (same choices as for hierarchical clustering).
- Clusters tab: "Number of clusters" (3 by default) and "Evaluate k from 1 to (elbow and silhouette)" (8 by default, from 2 to 50, limited to the number of rows).
- Method tab: "Algorithm" ("Hartigan-Wong" by default, "Forgy/Lloyd" or "MacQueen"), "Maximum iterations" (100), "Random starts" (10) and "Random seed" (1).
- Options tab, Data sets tab, then OK. Variance creates the results sheet and the graph of the "Elbow and silhouette" table: "Within SS" on the left Y axis, "Mean silhouette" (at most 1) on the right Y axis, each with its own scale.
Calculations#
Notation: zi the vector of scaled values of subject i (q variables), z̄c the center of group c, nc its size.
total sum of squares T = Σi ‖zi − z̄‖² (= (n − 1)·q in Standardize mode)
within-group W = Σc Σi∈c ‖zi − z̄c‖² "Total within-cluster SS"
between-group B = T − W "Between-cluster SS"
start k distinct rows drawn at random serve as centers;
each point is assigned to the nearest center
Forgy/Lloyd repeat: centers = group means, then each point goes to the nearest
center; stop when no assignment changes
MacQueen points are examined one by one; as soon as a point changes group,
the centers of the two groups concerned are recomputed; repeated passes
Hartigan-Wong point i of group l (nl > 1) moves to the group m that minimizes
nm / (nm + 1) · ‖zi − z̄m‖², if this value is smaller than
nl / (nl − 1) · ‖zi − z̄l‖² (the transfer then decreases W);
centers updated immediately; repeated passes until no point moves
limit "Maximum iterations" passes
starts "Random starts" runs, generator initialized by "Random seed";
the run with the smallest W is kept
The three algorithms choose their starting centers in the same way (no k-means++ initialization; Arthur and Vassilvitskii, 2007). "Forgy/Lloyd" is the batch algorithm of Forgy (1965) and Lloyd (1982); MacQueen (1967) described a single pass, which Variance repeats until stable. "Hartigan-Wong" applies the criterion of Hartigan and Wong (1979) point by point, without the shortcuts of their algorithm AS 136: at the end, no move of a single point decreases W, a more demanding condition than Lloyd's (each point closer to its own center), hence often better minima.
Silhouette (Rousseeuw, 1987), with the Euclidean distances of the scaled values:
a(i) mean distance from i to the other points of its group
b(i) smallest, over the other groups, of the mean distances from i to the points of the group
s(i) = (b(i) − a(i)) / max(a(i), b(i)) s(i) = 0 if i is alone in its group
The "Elbow and silhouette" table reruns the analysis for k = 1 to kmax, with the same algorithm, the same seed and the same number of starts. The silhouette is not defined for k = 1 (empty cell); for "Number of clusters" = 1, "Mean silhouette width" stays empty.
Reading the results#
- "Summary" tab: "Number of clusters", "Total within-cluster SS" (W), "Between-cluster SS" (B), "Mean silhouette width" and "Iterations" (passes of the best run). B / T is the share of the total variance explained by the partition; it always increases with k.
- "Clusters" tab (one column per group, "Cluster 1"…): "Size", "Within-cluster SS", then, under "Centroids", the coordinates of the center for each variable, in the scaled units (in Standardize mode, the original mean of the group is x̄j + z × sj). The numbering of the groups is arbitrary.
- "Cluster membership" tab (table order): "Cluster", "Silhouette" s(i) and "Distance to centroid" (Euclidean distance, scaled units).
- "Data with clusters" output table: the scaled values and a "Cluster" column ("Cluster 1"…). Plot These Results turns it into a Bubble plot graph; in the Inspector, "Bubble plot" section, choose "X", "Y" and "Color": Cluster ("Convex hulls" outlines each group).
- "Elbow and silhouette" output table: "Number of clusters" on X, "Within SS" and "Mean silhouette" on Y.
A silhouette close to 1 indicates a subject well inside its group, close to 0 a subject between two groups, negative a subject probably misclassified. Kaufman and Rousseeuw (1990) propose benchmarks for the mean silhouette: above 0.70, strong structure; 0.51 to 0.70, reasonable; 0.26 to 0.50, weak and possibly artificial; 0.25 or less, no substantial structure. These are not tests (see the Age example). W always decreases as k increases: look for the k beyond which the gain becomes small (the elbow), which often coincides with the maximum of the mean silhouette.
Worked example#
With Weight and Height, the default options and "Number of clusters" = 2, Variance displays:
Summary Value
Number of clusters 2
Total within-cluster SS 26.03
Between-cluster SS 51.97
Mean silhouette width 0.5308
Iterations 3
Clusters Cluster 1 Cluster 2
Size 19 21
Within-cluster SS 12.52 13.51
Centroids
Weight 0.8455 -0.765
Height 0.8493 -0.7684
By hand (means 64.8525 kg and 1.707 m; standard deviations 5.8704 and 0.07542):
T = (n − 1) × q = 39 × 2 = 78 B = 78 − 26.03 = 51.97 B / T = 66.6%
group 1: Weight = 64.8525 + 0.8455 × 5.8704 = 69.82 kg Height = 1.707 + 0.8493 × 0.07542 = 1.771 m
group 2: Weight = 64.8525 − 0.7650 × 5.8704 = 60.36 kg Height = 1.707 − 0.7684 × 0.07542 = 1.649 m
subject 1 (z = 0.9620; 0.9679), group 1:
a = mean distance to the 18 other members of group 1 = 0.7717
b = mean distance to the 21 members of group 2 = 2.4827
s = (2.4827 − 0.7717) / 2.4827 = 0.6892 ("Silhouette" 0.6892)
distance to the center = √[(0.9620 − 0.8455)² + (0.9679 − 0.8493)²] = 0.1663 ("Distance to centroid")
Group 1 contains 19 men, group 2 the 20 women and one man (subject 35: 1.72 m, 62.2 kg, silhouette 0.2468). "Forgy/Lloyd" and "MacQueen" find the same partition, in 2 passes. The "Elbow and silhouette" table gives:
Number of clusters 1 2 3 4 5 6 7 8
Within SS 78 26.03 14.68 9.801 7.606 6.076 4.689 3.834
Mean silhouette 0.5308 0.4498 0.4569 0.4504 0.4064 0.4651 0.4382
The elbow is clear at k = 2, where the mean silhouette is also the highest. Ward's hierarchical clustering, on the same data, grouped differently (sum of squares 31.29): two reasonable methods, two partitions.
Groups with no structure. With Age alone, whose values spread fairly evenly from 31 to 67 years, and k = 2, k-means forms two groups of 22 and 18 subjects (centers at 59.2 and 40.3 years), with a mean silhouette of 0.6371, "reasonable structure" according to the benchmarks above; from k = 2 to 8, it stays between 0.58 and 0.66. Nothing justifies two groups, however: k-means has cut a continuum.
Sensitivity to the start. With Age, Weight, Height and Time, k = 4, "Forgy/Lloyd" and "Random starts" = 1, seeds 1 to 6 give six different partitions: W = 52.28, 59.83, 56.01, 59.77, 55.76 and 50.37. With the default options (Hartigan-Wong, 10 starts), W = 50.37, unchanged with 100 starts.
Scale. Age and Height without standardization ("No scaling") give the centers (59.2 years; 1.694 m) and (40.3 years; 1.723 m): the partition splits age and ignores height, whose variance (0.0057) is negligible compared with that of age (119). Standardized, both variables count (centers in z: Age 0.6438 and -0.5267, Height -0.7926 and 0.6485).
Reporting the results#
"A k-means clustering (Hartigan and Wong algorithm, 10 random starts, seed 1; standardized weight and height) was performed with k = 2, a value suggested by the elbow of the within-group sum of squares and by the maximal mean silhouette (0.53). The groups had 19 subjects (means 69.8 kg and 1.77 m) and 21 subjects (60.4 kg and 1.65 m); the partition explained 66.6% of the total variance. Ward's hierarchical clustering gave a different partition."
Common pitfalls#
- Concluding that groups exist: k-means always returns k groups, and a "reasonable" silhouette can be obtained on data with no structure (Age example). Compare with hierarchical clustering, across subsamples, or with simulated data without groups.
- Testing the clustering variables between the groups: the groups were built to differ on these variables (see hierarchical clustering).
- Settling for one start, or not noting the seed: the solution can change from one run to another.
- Not standardizing variables with different units (Age and Height example).
- Reading the centers as original values: they are in the scaled units, like the "Data with clusters" table.
- Choosing k from the elbow alone: W always decreases and the elbow may be missing; cross-check with the silhouette and with the biological meaning of the groups.
- Applying k-means to elongated groups or groups of very unequal sizes: it cuts them poorly; hierarchical clustering with a suitable linkage (single linkage follows elongated groups) is more appropriate.
References#
Books:
- Jolliffe IT. Principal Component Analysis, 2nd ed. Springer, 2002.
- Kaufman L, Rousseeuw PJ. Finding Groups in Data: An Introduction to Cluster Analysis. Wiley, 1990.
Articles:
- Jolliffe IT, Cadima J. Principal component analysis: a review and recent developments. Philosophical Transactions of the Royal Society A 2016;374:20150202.
- Kaiser HF. The application of electronic computers to factor analysis. Educational and Psychological Measurement 1960;20:141-151.
- Cattell RB. The scree test for the number of factors. Multivariate Behavioral Research 1966;1:245-276.
- Horn JL. A rationale and test for the number of factors in factor analysis. Psychometrika 1965;30:179-185.
- Glorfeld LW. An improvement on Horn's parallel analysis methodology for selecting the correct number of factors to retain. Educational and Psychological Measurement 1995;55:377-393.
- Gabriel KR. The biplot graphic display of matrices with application to principal component analysis. Biometrika 1971;58:453-467.
- Jolliffe IT. A note on the use of principal components in regression. Applied Statistics 1982;31:300-303.
- Lance GN, Williams WT. A general theory of classificatory sorting strategies. 1. Hierarchical systems. The Computer Journal 1967;9:373-380.
- Ward JH. Hierarchical grouping to optimize an objective function. Journal of the American Statistical Association 1963;58:236-244.
- Murtagh F, Legendre P. Ward's hierarchical agglomerative clustering method: which algorithms implement Ward's criterion? Journal of Classification 2014;31:274-295.
- Sokal RR, Rohlf FJ. The comparison of dendrograms by objective methods. Taxon 1962;11:33-40.
- Forgy EW. Cluster analysis of multivariate data: efficiency versus interpretability of classifications (abstract). Biometrics 1965;21:768-769.
- MacQueen J. Some methods for classification and analysis of multivariate observations. In: Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, vol. 1. University of California Press, 1967:281-297.
- Lloyd SP. Least squares quantization in PCM. IEEE Transactions on Information Theory 1982;28:129-137.
- Hartigan JA, Wong MA. Algorithm AS 136: a K-means clustering algorithm. Applied Statistics 1979;28:100-108.
- Arthur D, Vassilvitskii S. k-means++: the advantages of careful seeding. In: Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms, 2007:1027-1035.
- Rousseeuw PJ. Silhouettes: a graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics 1987;20:53-65.