Manuscript Offprint
arXiv:2610.17458Selective Inference for Clustering Under Unknown Covariance
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Unsupervised clustering is widely used to discover underlying group structure, after which researchers often seek to validate these groups via post-hoc hypothesis testing on the population means. However, using the same data both to form clusters and to test for a difference in means inflates the Type I error rate. Recent work in selective inference has proposed solutions when the underlying data are drawn from a multivariate Gaussian distribution with a known covariance matrix or an unknown isotropic covariance matrix. We propose a new selective test for the difference in means between two clusters that provably controls the Type I error rate under an arbitrary unknown covariance matrix. Our test statistic does not require estimating the feature covariance matrix; instead, it leverages a Monte Carlo sampling procedure over the set of orthogonal matrices. We show that this new selective test can be computed efficiently, and we derive closed-form solutions when clusters are formed using k-means or hierarchical clustering. In simulations, we demonstrate that our proposed p-value controls the selective Type I error rate and achieves substantial power, and we illustrate its application on gene expression and drug review data sets.
1 Introduction
In many analyses, the groups that are compared are not fixed in advance but are estimated from the data. Clinical researchers cluster patients on routine measurements to find subgroups that differ in disease course and in who is most likely to benefit from a treatment (Ahlqvist et al., 2018). Marketers segment customers by their purchases to decide whom to target (Wedel and Kamakura, 2000). It is then tempting to apply a classical two-sample test to ask whether the estimated subgroups, or clusters, truly differ. But the hypothesis is generated from the same data that are used to test it, so classical tests no longer control the Type I error rate. This problem has been studied in a recent line of work known as selective inference or post-selection inference (see Neufeld et al., 2026, for a review).
We illustrate the problem with a toy example. Let follow the matrix normal model
that is, the rows , are independent, where is the ith row of . In Figure 1(a), half of the observations share one mean, the other half share another, and the two features are correlated. We cluster the data into three groups with -means, so the algorithm must split one of the two true groups in two. It does so cleanly by construction, because it chooses the

(b)
(c)
Figure 1: Estimating the covariance trades Type I error control against power. (a) One data set from (1) with two true groups (shapes), split into clusters (colors) by -means, which divides one true group in two. (b) QQ plots of the Uniform(0, 1) distribution against the -values when all observations come from one Gaussian group: the naive test, the test of Chen and Witten (2023) with three choices of covariance (, Section 5), and our proposals in (13), in (19), and of Section 4.4. (c) Conditional power against the separation between the true groups, for the tests that control the Type I error in (b).
partition that maximizes the between-cluster variation. The two halves of the split group therefore have very different sample means, although they have the same population mean. Let and be two of the estimated clusters and write for the average mean of a set of observations. The question is whether
For the two halves of a split group this null is true. A textbook two-sample test, such as Hotelling's referred to its F distribution, nevertheless rejects it almost always (the red line in Figure 1(b)). The F distribution describes the distance between groups that were fixed before the data were seen, not between groups that the data selected. Across the simulation study of Section 5, the naive test rejects the true null in 85% to 100% of replicates (Section 5.1).
Conditional selective inference repairs the reference distribution by conditioning on the selection event. The goal is a p-value p that controls the selective Type I error (Fithian et al., 2014),
That is, among the data sets on which the clustering returns the tested clusters, a true null hypothesis is rejected at level with probability at most . We call such a test valid. Let be a test statistic, such as Hotelling's or the distance between the two cluster means. Instead of asking whether is extreme under its unconditional null law, one asks whether it is extreme given that the clustering procedure returned the observed clusters. Gao et al. (2024) formalized this idea. For a known in (1), the selective p-value is
where is the observed data, is the set of clusters obtained from , and is the contrast vector with entries , so that . To compute (4), Gao et al. (2024) also condition on statistics that remove the nuisance parameters and on one further direction, which leaves a single scalar with a truncated distribution (Section 2.1), and they show that the truncation set can be computed efficiently for hierarchical clustering with commonly used linkages. Chen and Witten (2023) extended this approach to -means by conditioning on the full -means clustering trajectory of Lloyd's algorithm. That is, they replace the event in (4) with the event that Lloyd's algorithm repeats every observed assignment.
Both approaches require in (1) to be known. Section 2 shows that plugging in an estimate of trades Type I error control against power (Figure 1(b) and (c)).
In this work, we give an exactly valid selective test after clustering under model (1) with unknown means and an unknown, unstructured covariance . To avoid estimating , we test a stricter null hypothesis than (2),
which postulates that all observations in the two clusters share a common mean (Yun and Barber, 2023) (Remark 2.2 explains why the weaker null is not enough without a known covariance).
Our first insight is that if we stack the rows from and and center them into a matrix , then under (5), has independent rows. We then take the polar decomposition , where is uniformly distributed on the set , i.e., all matrices with orthonormal columns. Importantly, the distribution of does not involve and is independent of , and therefore can be used as a pivotal statistic for (5).
In addition to the novel test statistic construction inspired by classical results in multivariate statistics (Chikuse, 2003), we also make algorithmic contributions to conditional selective inference. Most existing selective inference frameworks reduce the computation of the selective p-value to a one-dimensional truncation problem; however, in our case, we need to sample Q truncated to a set. We propose a reversible Markov-chain-based algorithm for sampling and use the serial construction of Besag and Clifford (1989), which makes the Monte Carlo p-value exactly valid for any number of draws. Finally, for k-means clustering, we show that each proposal can be characterized exactly using analytical solutions. Conditioning on more information gives a simpler alternative: fixing all of Q except the angle that determines Hotelling's yields a one-dimensional truncated p-value , which is exact, needs only a one-dimensional Monte Carlo sample for a general clustering algorithm, and needs none for k-means when we condition on the Lloyd trajectory (Sections 3.4 and 4.4). Tests based on our proposal control the selective Type I error (3) in finite samples without any knowledge of (Figure 1(b)). In Figure 1(c) they even have at least as much power as the test of Chen and Witten (2023) with the true , because that test conditions on the whole sequence of k-means assignments and ours only on the returned clusters.
The methods are implemented in the R package selectiveHotelling, available at https://github.com/yiqunchen/selectiveHotelling, and its tutorials are at https://yiqunchen.github.io/selectiveHotelling/. The code that reproduces our results is at https://github.com/yiqunchen/selectiveHotelling-paper.
One way to extend the conditional framework to an unknown covariance is to plug in an estimate of it. González-Delgado et al. (2026) show that plugging the sample covariance into the tests of Gao et al. (2024) and Chen and Witten (2023) gives an asymptotically conservative test that controls the selective Type I error, because the sample covariance overestimates asymptotically. The guarantee, however, needs the estimate to come from data independent of the clustered sample, such as an independent copy. It also needs at least two well-separated true clusters. Moreover, when there is a true clustering structure, i.e., when the are not all equal, the sample covariance can lead to a substantial loss of power (Figure 1(c)). An estimator that is universally consistent for without knowledge of is a hard problem and remains an active area of research, especially when is close to (Cai et al., 2016; Fan et al., 2016; Ledoit and Wolf, 2020).
Another line of work avoids conditioning by adding auxiliary randomness. It splits one data set into two independent parts, one to choose the hypothesis and the other to test it (Rasines and Young, 2023). Data fission (Leiner et al., 2025) and data thinning (Neufeld et al., 2024a; Dharamshi et al., 2025; Neufeld et al., 2024b) construct such a split systematically for a single realization from many parametric families, including the multivariate Gaussian with unknown mean but known . Without , Dharamshi et al. (2026) prove that a single multivariate Gaussian cannot be split into independent parts. With observations they do construct independent parts, but these mix the rows of , so an observation clustered in one part has no counterpart to test in the other. We refer to Neufeld et al. (2026) for a comparison of the conditioning and splitting approaches.
Clustering has also been studied from angles other than testing a selected pair. One question is how many clusters there are, addressed by tests for the order of a finite mixture (Chen et al., 2004; Chen and Li, 2009; Li and Chen, 2010), by permutation methods for the number of factors (Dobriban, 2020), and by the mixture-model literature reviewed in McLachlan et al. (2019). Another is whether a cluster, or the variables that drive it, are reproducible, assessed by resampling (Kerr and Churchill, 2001; Suzuki and Shimodaira, 2006), by significance tests for hierarchical clustering and for cluster membership (Kimes et al., 2017; Chung, 2020), and by related tests of systematic variation and exchangeability (Chung and Storey, 2015; Jin and Wang, 2016; Aw et al., 2021). Bayesian work studies the posterior of the number of components and of the mixture parameters (Nobile, 2004; Guha et al., 2021; Cai et al., 2021), and since k-means is a limiting case of the expectation-maximization algorithm, statistical guarantees for that algorithm are also relevant (Wang et al., 2015; Yi and Caramanis, 2015; Balakrishnan et al., 2017; Cai et al., 2019). Many of these results rely on a consistent estimate of the cluster memberships, or at least on the correct number of clusters. By contrast, we follow the conditional selective inference framework and give a test that is valid whether or not the estimated clusters correspond to true ones.
1.2 Notation and organization
The data are with rows , and denotes a realization of ; for any matrix, the subscript denotes its th row, and is the Frobenius norm. We write for the matrix normal distribution with mean , row covariance , and column covariance ; , , and for the -vector of ones, the identity, and a zero vector or matrix; for a nonzero vector or matrix divided by its or Frobenius norm; and for the indicator function. The clustering rule applied to returns the partition of . Finally, is the set of matrices with orthonormal columns.
The remainder of the paper is organized as follows. Section 2 reviews the test of Gao et al. (2024) for a known covariance, shows why estimating the covariance trades Type I error control against power, and writes the test of Yun and Barber (2023) as a polar decomposition of the centered tested rows. Section 3 replaces that decomposition by the matrix polar decomposition, writes Hotelling's as an angle, and gives two exact tests for any clustering algorithm: the one-dimensional test and the test . Section 4 computes both for any clustering algorithm by combining a Markov chain with the construction of Besag and Clifford (1989), and then discusses closed forms for k-means and hierarchical clustering. Section 5 reports the simulation study, including the comparison with plug-in covariance estimates and data thinning, and Section 6 applies the test to leukemia, single-cell RNA sequencing, and drug review data. Section 7 concludes, and proofs and additional results are in the appendices.
2 Testing for a difference in means between two estimated clusters
This section reviews selective inference for clustering when the covariance is known (Section 2.1) and explains why estimating the covariance does not work (Section 2.2). We then end with the intuition behind our approach (Section 2.3).
Throughout, we work under data model (1).
2.1 Selective inference for clustering with a known covariance
We first review the test of Gao et al. (2024) in the setting where in (1) is known. If the clusters and had been chosen before the data were seen, we would test (2) with the difference in sample means , where is the contrast vector defined in Section 1. Under (2), , so the whitened norm follows the scaled distribution .
Because the clusters were chosen from the data, this is not the right null distribution, and the selective -value in (4) conditions on the event that the clustering returns and . That probability still depends on the unknown means. It helps to split the data with three projections that we use throughout the paper, . Here projects onto the difference of the two cluster means; projects onto the deviations of each observation from the mean of its own cluster, with the diagonal matrix with ones in the positions of and the indicator vector of ; and projects onto the rest, namely the overall mean of and the observations outside the two clusters. In words, is the variation between the two tested clusters, the variation within them, and everything else; Figure 2(a) shows a clustering and Figure 2(b) its three parts. We write every test in this paper, theirs and ours, in terms of this split, so that the tests differ only in which parts they hold fixed and which part they let vary. Gao et al. (2024) decompose the data into the part along and the part orthogonal to it,
where the last term is and is the projection orthogonal to . They compute instead
(6)

(b)
(c)
(d)
: between tested clusters
: within tested clusters
: the rest
--- : sample covariance of the tested observations
Figure 2: The split for observations from three bivariate Gaussian groups, clustered into clusters by -means; open circles are the cluster that is not tested. (a) The data. (b) The three parts: joins the two tested cluster means, covers the deviations within each tested cluster, and covers the untested observations (it also holds the overall mean of the two tested clusters). (c) A data set with and held fixed, as in Gao et al. (2024): the two tested clusters keep their shapes and move along the line between their means. (d) A data set with and held fixed, as in our test: the tested observations are redrawn around the same overall mean with the same sample covariance, and the untested observations do not move. The dashed ellipse in (b)–(d) is the 95% ellipse of the sample covariance matrix of the tested observations; it is the same in (b) and (d) and smaller in (c).
The conditions on and remove the unknown means , which are nuisance parameters under , and the condition on is additional conditioning used to enable efficient computation of the -value. Only the scalar then remains random. Because is uniform under given more information than the clustering, it also controls the selective Type I error in the sense of (3) (Proposition 2.1). To compute , replace the observed value of the statistic by and define the perturbed data and the values of that reproduce the clustering,
Proposition 2.1 (Gao et al., 2024, Theorem 1, applied to ). Let follow (1) with known. For any realization and any two non-overlapping groups ,
where is the distribution function of truncated to . If (2) holds, then for every .
The perturbed data set keeps and and rescales only , so it leaves every observation outside in place and keeps the deviations within each tested cluster. It moves the two clusters apart when exceeds the observed statistic and together when is below it, along the direction of (Figure 2(c)). The set therefore collects every value of the statistic that would have produced the same clusters had it been observed instead. Proposition 2.1 says that the scaled distribution remains the right null distribution once it is truncated to this set. For hierarchical clustering with common linkages, is available in closed form (Gao et al., 2024). For -means, Chen and Witten (2023) condition on the full -means clustering trajectory of Lloyd's algorithm instead of on , and the corresponding set is a finite union of intervals whose endpoints solve quadratic equations. With known, the weaker null (2) suffices, because the nuisance is removed by conditioning on .
2.2 Challenges in estimating the covariance
In practice is unknown and must be estimated from the same data. Two natural estimates both fail, in ways that the clustering explains (Figure 1).
• The within-cluster covariance
is consistent when the clusters are fixed in advance. But -means minimizes the within-cluster sum of squares, so when it splits a true group, is too small along the tested direction . With a single Gaussian group, the test of Chen and Witten (2023) with , which we write , rejects 16.1% of true null hypotheses at level 0.05 (Figure 1(b)).
• The sample covariance
(González-Delgado et al., 2026) overestimates when there are separated groups. This protects the Type I error but costs power, because the separation between the tested clusters inflates along the tested direction. At the separation of Figure 1(a), rejects 18% of the pairs from different true groups, against 78% with the true (Figure 1(c)).
Our test does not estimate (Section 3) and avoids this trade-off: it rejects 5.7% of 900 true null hypotheses at level 0.05, and 99% of the pairs from different groups at (Figure 1(b) and (c)).
2.3 Extension to an unknown variance
When is unknown, the length in Section 2.1 has an unknown distribution, so we need a test statistic whose null distribution does not depend on the covariance. Two-sample tests have this property, because they depend on the data only through an angle. We explain the angle with the decomposition of Yun and Barber (2023) for , and then describe how we move to an arbitrary .
Yun and Barber (2023) use the same decomposition of Section 2.1. Their test statistic is
which compares the spread between the two clusters with the spread within them.
To see why the distribution of does not involve , consider , the deviations of the tested observations from their common mean. The matrix is the projection onto an -dimensional subspace of , so under null (5), ; that is, has independent coordinates in an -dimensional subspace of . Such a Gaussian vector splits into its length and its direction. The squared length, , is a sufficient statistic for . The direction is uniformly distributed on the unit sphere of that subspace, whatever is. Moreover, the length and the direction are independent (Muirhead, 1982; Chikuse, 2003).
The statistic is a function of the direction only. Write for the fraction of the squared length of that comes from the difference between the two cluster means. The remaining fraction, , comes from the deviations of the observations from their own cluster means, and . A value of close to one means that the observations sit close to their own cluster means and the two means are far apart relative to that spread, so the clusters look well separated and is large. In that case most of the variation of the tested observations is between the two clusters rather than within them, which we do not expect when (5) holds. A value of close to zero means that the spread within the clusters dominates the difference between their means. Because the direction is uniformly distributed on the sphere and the range of is a -dimensional part of the -dimensional subspace, for every , and therefore . It turns out that is just one such choice. Any other ratio of , , and , such as , is a monotone function of and gives an equivalent test.
The construction rests on two ingredients, which Section 3 reuses for an arbitrary . First, we condition on statistics that are sufficient for the nuisance parameters under the null, here the length for and for the means, so that the conditional distribution of the data does not involve them (Lehmann and Romano, 2005, Chapter 4). Second, the test statistic is a function of the remaining part, here the direction, which is independent of the sufficient statistics; its conditional distribution is therefore its known unconditional one. The direction also splits further: and the two directions and are independent. Testing with a direction that is uniformly distributed on a sphere has also been applied to testing in sparse linear models (Sengupta and Janson, 2024; Paulson et al., 2025).
After clustering, no longer has an distribution, and conditioning on the clustering alone is not enough to compute its distribution. The event depends on the data through , the length, and the whole direction, not only through , so the conditional distribution of given the event would require an integral over all directions that reproduce the clusters, which has no closed form. Yun and Barber (2023) therefore condition on every part of the data other than :
(9)
The conditions on and on the length remove the nuisance parameters, which are the means and ; this uses the first ingredient. The conditions on the two directions are additional conditioning, as is the condition on in (6). Given all four, the data are a function of alone: replacing the observed by gives the perturbed data set
as in (7), and by the second ingredient keeps its distribution given the length and the two directions. So is the upper tail of the distribution truncated to the set . Section 4 takes the other route in our setting: it drops the additional conditioning and computes the integral over directions by Monte Carlo.
What does it take to extend this argument to a general ? Both ingredients rely on being an isotropic Gaussian vector. For a general , the entries within each row are correlated, so the direction is not uniformly distributed and the distribution of depends on . The intuition still applies. In Section 3, the polar decomposition of a matrix splits the distribution of into a part whose distribution involves and an independent part whose distribution does not depend on , and an analogue of in (8) leads to the familiar Hotelling's statistic.
Remark 2.2 (The null hypothesis we test). Both Yun and Barber (2023) and our work test (5) rather than (2). The reason is that both tests use the distribution of , which has mean zero exactly when all tested observations share one mean, because the only vectors on the tested observations that maps to zero are the constant ones. Under (2), has a nonzero mean whenever the observations within a cluster have different means.
3 Selective p-value under an unknown covariance
This section builds on the decomposition in Section 2.3 and proposes a selective test for an arbitrary clustering algorithm under an unknown covariance matrix. Section 3.1 replaces the length by a matrix and shows that the remaining factor is uniformly distributed for every . Section 3.2 shows that Hotelling's is a function of one angle of , which is the angle of Section 2.3 when . Section 3.3 conditions on the clustering and obtains the selective -value , and Section 3.4 conditions on more to obtain the one-dimensional test . Section 4 explains how to compute both.
Throughout, the tested clusters have sizes and , with , which the pooled covariance in Hotelling's requires even without clustering. Theorem 3.1 and Proposition 3.2 hold for any two fixed groups of observations. From Section 3.3 on, and are clusters returned by a clustering algorithm that is a deterministic function of the data (for example, k-means from fixed initial centroids), and the tested pair is fixed in advance or every pair is tested.
3.1 The polar decomposition of
Section 2.3 split , the deviations of the tested observations from their common mean, into a length and a direction. The polar decomposition makes the same split with a matrix in place of the scalar length. When has rank , which holds with probability one when ,
where is symmetric positive definite and the polar factor is an matrix with orthonormal columns. The columns of lie in the -dimensional range of , so belongs to the set of matrices with orthonormal columns in that range, which is a copy of the Stiefel manifold . The matrix is the matrix square root of times the sample covariance matrix of the tested observations. The polar factor plays the role of the direction, and plays the role of the length; when the two decompositions are the same (Appendix A).
Theorem 3.1 (Distribution of the polar factor). Under data model (1) and null (5), Q is uniformly distributed on V and is independent of (H, P₂X).
This follows from a classical result on the polar decomposition of a Gaussian matrix (Muirhead, 1982; Chikuse, 2003); Appendix A gives a proof in our notation. The two ingredients of Section 2.3 therefore hold for every : the means and enter only through , and is independent of them with a distribution that involves no unknown parameter. Figure 2(d) shows a data set with and held fixed and drawn from its uniform distribution. This suggests that we can construct a pivotal statistic based on .
3.2 Hotelling's as a function of Q
Which function of Q should we use? In Section 2.3, R compares the part of the direction of that lies along , the between-cluster part, with the part along , the within-cluster part. The matrix projects onto the one-dimensional column space of , the direction of between-cluster variation. The analogue of for the polar factor is the squared length of the projection of onto that direction, . As with , a large value of means that the polar factor is dominated by between-cluster variation, which is unlikely under the null. This ratio is a scaled version of the usual two-sample Hotelling statistic.
Proposition 3.2 (Hotelling's as a function of ). The two-sample Hotelling statistic,
where is the pooled within-cluster covariance matrix, satisfies
When , in (8). Under data model (1) and null (5), ; equivalently, .
The proof is in Appendix A. The connection is classical: is the largest squared two-sample t-statistic over all one-dimensional projections of the data, attained at the Fisher discriminant direction (Hotelling, 1931; Anderson, 2003).
3.3 The selective p-value
Proposition 3.2 describes before clustering. After clustering, as in (6) and (9), we condition on the clustering and on the sufficient statistics for the nuisance parameters, and propose the selective p-value
The conditioning fixes and , and with them , , and . As in (7) and (10), replacing the observed polar factor by gives the perturbed data set
where is the set of polar factors that reproduce the tested clusters.
Proposition 3.3 (The selective p-value). Under data model (1) and null (5), conditional on , , and , the polar factor is uniformly distributed on . Consequently, with the observed polar factor and integration against the uniform distribution on ,
The proof is in Appendix A. The second part of (14) says that controls the selective Type I error in the sense of (3), with equality and with in place of . In words, among all data sets with the same and on which the clustering returns and , is the fraction on which the two clusters look at least as separated, as measured by , as in the observed data.
Given (6) and (9), it is tempting to expect to be the tail of an F distribution truncated to the values of that reproduce the clusters. It is not, because whether the clustering returns
and depends on all of Q, not only on : polar factors with the same arrange the tested observations differently in the other directions, so some of them reproduce the clusters and some do not. The clustering therefore reweights the null distribution of by the fraction of polar factors with each value of that reproduce the clusters, and this fraction has no closed form. In contrast, (6) and (9) condition on everything except one scalar. Each value of that scalar corresponds to a single data set, which either reproduces the clusters or does not. Computing in (13) therefore needs Monte Carlo sampling, and Section 4 gives sampling methods whose p-values are exact for any number of draws.
3.4 Conditioning on more to obtain a one-dimensional pivot
We now work toward a p-value that, as in (6) and (9), is the survival function of a known one-dimensional distribution truncated to a set. The high-level strategy is to identify a one-dimensional function of Q and condition on all the rest. By Proposition 3.2, depends on Q only through , so is the function we keep random. To say what the rest of Q is, we use the Fisher discriminant direction of Section 3.2.
Since with , the between-cluster part of is the rank-one matrix
The vector is the tested data projected onto the direction , which is proportional to , the Fisher discriminant direction, and scaled so that . So is a data set with one feature. By (15), its between-cluster part is , so is the fraction of Section 2.3 computed on , and is the statistic in (8) computed on .
This suggests applying the conditioning of Yun and Barber (2023) to q and holding the rest of Q fixed. Yun and Barber (2023) fix the directions of the between-cluster and within-cluster parts and keep only their relative size random. The between-cluster part of q always points along , so we fix the following three quantities:
• the direction , which fixes the direction onto which the data are projected;
• the direction of the within-cluster part of ;
- the part of Q orthogonal to , , which describes the tested data in the directions orthogonal to the Fisher direction.
We write . Since has unit length, , and writing gives
So Q is determined by and , and conditioning on leaves as the only random quantity. It is convenient to write this quantity as an angle. For , replacing by and by in (16) gives
the polar factor that has the same as and whose projected data have between-cluster fraction . It lies in for every (Proposition B.2). We write for the observed angle, ; along the path, . As varies, the unit vector in (17)

(b)
(c)
(d)
(e)
Figure 3: Two ways to perturb the data, for observations from one bivariate Gaussian split into clusters by -means; open circles are the cluster that is not tested. (a) The perturbation of Gao et al. (2024) and Chen and Witten (2023) slides the two tested clusters apart along , so every perturbed data set lies on a line. (b) Our perturbation for one pair of rows , where rotates rows and of by the angle (Section 4.1): each tested observation moves on an ellipse, purple where -means still returns the tested clusters. (c) The angles on the unit circle, purple where -means returns the tested clusters, with an accepted proposal (filled triangle) and a rejected proposal (open triangle); the observed data are at . (d) The data at the accepted angle, colored by the clusters that -means returns on them. (e) The same at the rejected angle; the ringed observations have changed cluster.
turns at constant speed in the plane spanned by and . The path is therefore a rotation of , the form used in Section 4. We write
for the set of angles at which the clustering returns the tested clusters. The one-dimensional selective p-value conditions on in addition to the clustering and the nuisance statistics,
(19)
Proposition 3.4 (The one-dimensional selective p-value). Under data model (1) and null (5), is independent of . Consequently, given , , , and the clustering, the scaled statistic has the distribution truncated to the set of values that reproduce the clusters, and is the survival function of this truncated distribution evaluated at the observed value of . Under the null, is uniformly distributed conditional on the clustering.
The proof is in Appendix B.4. Fixing is additional conditioning, like the direction in (6) and the two directions in (9): its distribution involves no unknown parameter, and we fix it only so that the resulting distribution is easy to characterize computationally. In terms of the data, moving along the path (17) keeps , , and the data in the directions orthogonal to the Fisher direction, and moves each tested observation along a line in the direction of the difference in cluster means. So is the test of Yun and Barber (2023) applied to the projected data , with the rest of the data held fixed. Figure 3(a) and Table A.1 in Appendix A.4 compare the three one-dimensional tests. Because it fixes , uses less of the data than and has less power (Section 5).
4 Computing the selective p-values
Both selective p-values, in (13) and in (19), are ratios of integrals over sets that the clustering algorithm defines. By Proposition 3.3, is the fraction of the volume of on which , and by Proposition 3.4, is a ratio of two masses of a truncated distribution over . For a general clustering algorithm, neither set has a closed form, but we can check whether a given point belongs to it by running the algorithm once: exactly when the algorithm, applied to , returns and . Sections 4.1 to 4.3 use only this check, and so apply to any algorithm. Section 4.4 shows what more can be done for -means and hierarchical clustering.
4.1 Monte Carlo sampling for any clustering algorithm
A direct approach, following Gao et al. (2024), is to estimate the two integrals in (14) by importance sampling. We draw independently from a proposal distribution on with density relative to the uniform distribution, run the clustering algorithm on each perturbed data set , and estimate
For the random quantity is one angle and this approach is workable (Section 4.3). For the random quantity is the whole polar factor , which has free coordinates, and is typically a small region around . Points drawn uniformly from rarely land in , so both sums in (20) are usually zero. A proposal concentrated near has the opposite problem. Its density is small away from , so the few draws that land in far from get much larger weights than the others, and is close to the indicator of one or two draws. It is then close to 0 or to 1 depending on which side of those draws happen to fall, and the values close to 0 are false rejections.
An alternative is to draw from a Markov chain whose stationary distribution is the uniform distribution on , such as a random-walk Metropolis chain or Hamiltonian Monte Carlo (Neal, 2011). Every draw then lies in , and the proposal is the target itself, so all weights in (20) are equal and the estimate becomes the fraction of draws with . Used naively, however, this estimate is valid only as , and that limit is far away here. The chain moves slowly through , and its draws are strongly correlated with and with each other, so the resulting p-values are anticonservative in our experiments. For example, the selective Type I error at level 0.05 reaches 0.19 at and (Appendix C.2).
We therefore combine a Markov chain with the construction of Besag and Clifford (1989), which turns a chain into an exact p-value however slowly it mixes (Section 4.2). The construction needs a Markov kernel that is reversible with respect to the uniform distribution on . Since each new point must again have orthonormal columns, we propose moves by Givens rotations (Golub and Van Loan, 2013, Section 5.1.8). Let be a fixed orthonormal basis of the range of . For and an angle , the Givens rotation
rotates the plane spanned by and by the angle and leaves every vector orthogonal to that plane unchanged. Since is orthogonal and maps the range of to itself, whenever . In the coordinates , with , the rotation changes only rows and . As varies, each tested observation moves along an ellipse and the untested observations do not move (Figure 3(b) and (c)). We call the following kernel K the random Givens kernel. Given the current point Q and a number of steps L:
-
draw a step size with uniform on , independently of Q;
-
repeat L times:
(a) draw a pair uniformly at random and an angle ;
(b) set and run the clustering algorithm on ;
(c) if the algorithm returns and , set ; otherwise keep .
Drawing from a range of scales lets the chain take short steps where is narrow and long steps where it is wide, without tuning on the observed data, which the construction of Section 4.2 does not allow. One application of runs the clustering algorithm times. Figure 3(d) and (e) show an accepted and a rejected proposal on a small example.
Proposition 4.1 (The random Givens kernel is reversible). For every , the random Givens kernel is reversible with respect to the uniform distribution on .
The proof is in Appendix B.5. The reason is that the proposal is a random rotation that is as likely as its inverse, because and is symmetric about zero. Such a proposal does not change the uniform distribution on , and keeping only the proposals that reproduce the clusters restricts it to . The same argument applies to any random rotation with this symmetry. One example is the Cayley random walk, which rotates all coordinates at once by the Cayley transform of a random skew-symmetric matrix (Wen and Yin, 2013); it is described in Appendix B.5. Both kernels give exact -values, and in a pilot comparison (Appendix C.4) the random Givens kernel had at least the power of the Cayley random walk at a lower cost per -value.
4.2 An exact p-value from a Markov chain
Besag and Clifford (1989) showed how to obtain an exact p-value from a reversible Markov chain without waiting for it to mix: place the observed point at a uniformly random position along a path of the chain and use its rank on that path. Let K be the random Givens kernel of Section 4.1. Build a path of length as follows.
-
Draw uniformly from and set .
-
Run the chain forward from : for .
-
Run the chain backward from : for .
The backward run uses the same kernel as the forward run because is reversible. With , the Monte Carlo version of is the randomized rank of among ,
with drawn independently of the path to break ties.
Algorithm 1 The selective test for any clustering algorithm
Require: data , clustering algorithm , tested clusters (fixed in advance, or each pair tested in turn), path length , number of steps
1: Form from and , and an orthonormal basis of the range of
2: and polar decomposition, Section 3.1
3: Draw uniformly from and set
4: for do
5: forward
6: end for
7: for do
8: backward
9: end for
10: for , and draw
Ensure:
11: function RANDOMGIVENS( ) the random Givens kernel
12: Draw uniformly on
13: for do
14: Draw uniformly from and
15: Givens rotation (21)
16: if then
17:
18: end if
19: end for
20: return
21: end function
Proposition 4.2 (The Monte Carlo p-value is exact). Suppose that the kernel K is reversible with respect to the uniform distribution on , and that K and M depend on the data only through , H, and the clustering. Under data model (1) and null (5),
for every , however slowly the chain mixes.
The proof is in Appendix B.6. Proposition 4.2 says that (22) gives a valid test for any , any , and any reversible kernel, in the sense that it controls the selective Type I error (3). Different choices, however, lead to different power when does not hold. Power grows with the path length and levels off (Appendix C.3), and it grows with how far the chain moves between consecutive points of the path, which increases with and with the size of the accepted steps. The path then spreads over a wider range, so that under the alternative the observed can stand out at the top of that range. At the other extreme, a kernel that never moves gives , which is exact and has no power. The one restriction is that these choices may not depend on : tuning on trial moves from can break exactness (Appendix C.3), whereas drawing from a fixed distribution, as in Section 4.1, does not. We summarize the test based on in Algorithm 1, which runs the clustering algorithm times at each of the steps of the path.
4.3 The one-dimensional test for any clustering algorithm
Recall that for only the angle is random, and recall the set in (18) of angles at which the clustering returns the tested clusters. Under the null, the angle has density on , which is the Beta distribution of (Proposition 3.2). Given , , , and the clustering, the angle therefore has density
and since a smaller angle means a larger , Proposition 3.4 says
We compute (24) with the construction of Section 4.2. Algorithm C.1 in Appendix C.1 is Algorithm 1 with two changes. First, the path moves the angle in instead of the polar factor Q. Second, each step is a Metropolis step for the density (23): it proposes a nearby angle, accepts it with the usual density ratio, and keeps it only if the clustering returns the tested clusters. This step is reversible with respect to (23), so the resulting p-value is exactly uniform under the null by the argument of Proposition 4.2. Each step runs the clustering only if the proposed angle passes the density check.
Alternatives exist, such as a slice sampler with shrinkage (Neal, 2003), which is also reversible with respect to (23), and importance sampling as in Gao et al. (2024), with the angle drawn from a mixture of f and a normal distribution centered at . In our preliminary experiments, the slice sampler gave similar p-values at about ten times the number of clustering runs. Importance sampling agreed with the exact test in Figure 1, but it is consistent rather than exact, and it was unreliable when was far in the tail of f: with well-separated clusters, 2,000 draws had an effective sample size of 2 to 5.
4.4 Extensions to k-means and hierarchical clustering
k-means: closed-form constraints from the trajectory. Algorithms 1 and C.1 apply to selective inference after any clustering algorithm. For hierarchical and k-means clustering, Gao et al. (2024) and Chen and Witten (2023) also gave closed-form descriptions of their truncation sets. For k-means, has no closed form, because many sequences of intermediate assignments end in the same final clusters (Appendix B). Following Chen and Witten (2023), however, we can condition on the whole sequence of assignments made by Lloyd's algorithm. The set of polar factors that reproduce this sequence then has a closed form, and so does its intersection with any rotation of Q, which gives a kernel that needs no rejections and no step size.
Lloyd’s algorithm starts from the centroids , for fixed indices , and alternates two steps until the assignments stop changing: assign each observation to its nearest centroid, giving labels , and recompute each centroid as the mean of the observations assigned to it. Write for the observed sequence of assignments. For a polar factor , let be the centroids of under the observed labels,
Lloyd’s algorithm applied to produces the same sequence exactly when, at every iteration, every observation is closer to its observed centroid than to the others:
Let be the set of that satisfy (25). It is contained in , because the same sequence of assignments ends in the same clusters, and Sections 3.3 to 4.2 hold with in place of .
Proposition 4.3 (The trajectory event is quadratic in Q). For each t, i, and , the difference
is a quadratic polynomial in the entries of , with coefficients determined by , , and . Hence for all is defined by the quadratic inequalities .
The reason is that is linear in apart from a constant, and with the labels fixed by each centroid is a fixed average of rows of , so each squared distance is quadratic (Appendix B). The quadratic structure also describes along any curve on which rotates.
Proposition 4.4 (The trajectory event along a rotation). Let be a curve in with fixed matrices , , . Then along the curve each in (26) has the form
with constants that have closed forms. Unless it is constant, such a function has at most four zeros in , which are the roots of a quartic polynomial. Hence the set of with is a finite union of intervals whose endpoints have closed forms.
Two curves of this form are the ones we need. The path of Section 3.4 is one, with , , , and . The Givens circle of (21) is another. The proofs and the formulas for are in Appendix B.2. Proposition 4.4 has two consequences for computation.
• The one-dimensional test needs no Monte Carlo. Conditioning on , the set in (24) is a finite union of intervals with known endpoints, so both integrals in (24) are differences of the Beta distribution function at of those endpoints.
• A kernel without rejections or step sizes. On the Givens circle through the current Q, we can compute the whole set and draw uniformly from it, instead of proposing one angle and checking it. This is a hit-and-run step (Smith, 1984; Bélisle et al., 1993). It is reversible with respect to the uniform distribution on (Proposition B.1 in Appendix B.3), it moves at every step, and it never runs Lloyd's algorithm.
Conditioning on is conditioning on more than the event that the clusters are returned, and it costs power (Figure 1(c) and Section 5).
Extension to hierarchical clustering. We sought to follow Gao et al. (2024) to obtain a more efficient computation for agglomerative hierarchical clustering cut at clusters. Recall that Gao et al. (2024) characterized the set in (7), defined through the perturbation , as the solution set of inequalities, each quadratic in , obtained by conditioning on the order of all merges down to clusters. A remarkable consequence is that, because conditioning on and fixes the distances between observations within the same cluster (Gao et al., 2024, Lemma 1), conditioning on the order of all merges is equivalent to conditioning on alone. The extra conditioning therefore costs no power, unlike in other problems where conditioning on more than the selection event does (Jewell et al., 2022; Le Duy and Takeuchi, 2022; Chen et al., 2023).
This is no longer the case for our perturbation , even for the one-dimensional path of Section 3.4. To preserve the sample covariance, and rotate the observations within each cluster, so the distances between observations in the same cluster change, and many different merge orders end in the same tested clusters. Each merge of hierarchical clustering with a commonly used linkage, such as average linkage on squared Euclidean distances, can still be characterized by quadratic inequalities in (or in ), because it compares averages of squared distances between rows of . But conditioning on the merge order is now conditioning on more than the event that the clustering returns the tested clusters, and so it costs power. In fact, in a pilot study, the resulting test had almost no power. We therefore do not present that alternative, and we compute and for hierarchical clustering with Algorithms 1 and C.1.
5 Simulation study
We simulate data from (1), cluster them by k-means or by average-linkage hierarchical clustering with K = 3, and test the null hypothesis in (5) for two of the estimated clusters at level ; implies the null in (2), which the comparators test. We compare these p-values:
• the naive p-value ;
-
our proposals (Algorithm 1) and (Algorithm C.1), with and , and, for k-means, , which conditions on the sequence of assignments of Lloyd's algorithm (Section 4.4);
-
for k-means, the test of Chen and Witten (2023) with (their median-based estimate), with the sample covariance of about its overall mean, or with the true : , , and ;
-
for hierarchical clustering, the test of Gao et al. (2024) with (with estimated from the residuals of about its overall mean), , or : , , and .
Appendix D reports every cell, two more comparators, and Leiden community detection.
5.1 Selective Type I error under the global null
Under the global null, every row of has mean zero in (1), so is true whichever pair the clustering returns. The covariance is isotropic ( ), first-order autoregressive ( ), compound symmetric ( ), or spiked ( with ). For -means, we simulate 600 data sets for each and with , apply -means with from one fixed random initialization (Section 4.4), and

(b)
(c)

— — Proposal: — Proposal: — Proposal: — — —
Figure 4: k-means with K = 3. (a) Quantile-quantile plots of the p-values under (1) with , stratified by and pooled over n and p. (b) The conditional power (29) at under (1) with defined in (28), n = 50, and , stratified by p, for the tests that control the selective Type I error. (c) The recovery probability (30) in the same settings.
compute the -values for a randomly chosen pair of clusters with , so that the pooled sample covariance in Hotelling's is invertible. For hierarchical clustering, we simulate 600 data sets for and under the first three covariances, cut the average-linkage tree on squared Euclidean distances at , and test every pair of clusters with at least three members and .
Figures 4(a) and 5(a) plot the quantiles of the null p-values, pooled over n and p, against those of the Uniform(0,1) distribution. Three patterns hold for both clustering algorithms and every : (i) the curve of lies far below the diagonal, so the naive test rejects true null hypotheses almost always; (ii) and are uniform under isotropic noise and stochastically smaller otherwise, because they assume ; (iii) , , and control the selective Type I error (3), as do , , , and ; the last two lead to conservative tests. In Appendix D, the unknown-scale test of Yun and Barber (2023) behaves like , and data thinning (Neufeld et al., 2024a) with the sample covariance controls the selective Type I error but is conservative, rejecting about 2% of true null hypotheses at level 0.05.
5.2 Conditional power and recovery probability
We generate data from (1) with three true clusters of equal size,
where is the first standard basis vector. The clusters that the algorithm returns need not be true clusters, and a rejection is informative only when they are. Following Gao et al. (2024) and Chen and Witten (2023), we therefore report two quantities over B simulated data sets with true clusters : the conditional power, the rejection rate among the data sets in which both tested clusters are true clusters, and the recovery probability, the fraction of data sets in which the two tested clusters are true clusters:
where , , and are the p-value and the clusters tested in the bth data set. We show power only for the tests and covariances under which the test controls the selective Type I error in Section 5.1. For k-means, we simulate data sets for each cell of the null design and each ; for hierarchical clustering, for each .
Figure 4(b) displays the conditional power of k-means at and Figure 4(c) its recovery probability. The conditional power of every test increases with . In every panel, has the highest conditional power among the tests that do not use (tied with at and ), and it is also at least as powerful as , which uses the true . This is possible because conditions on more: on the whole sequence of assignments of Lloyd's algorithm rather than only on the event that the clustering returns the tested pair, and on all of the data except one scalar. Each extra condition costs power, as the gaps from to and from to show. Using in leads to the least powerful test, because the sample covariance about the overall mean includes the spread between the true cluster means, which grows with , and so overstates along the direction that separates them. The recovery probability increases up to and then decreases slightly, because with collinear means some initializations converge to a partition that merges the middle cluster with an end cluster. At and 200, the conditional power of exceeds 0.98 in every cell (Appendix D).
Figure 5(b) and (c) display the recovery probability and the conditional power for hierarchical clustering under isotropic noise. Average linkage rarely returns two true clusters at . From on, rejects for every pair of true clusters, and , which knows , for almost every pair, while and are less powerful at , increasingly so as grows.
Computing time. At , one value of takes a median of 2.1 seconds on one core of an Apple M4 Max processor at and 5.4 seconds at , and one value of takes 1.0 to 2.3 seconds. The closed-form and the tests of Chen and Witten (2023) take about 0.1 seconds (Figure D.8 in Appendix D). Each of the steps of the path reruns the clustering times.

(b)

(c)

Figure 5: Average-linkage hierarchical clustering with K = 3 and n = 200. (a) Quantile-quantile plots of the p-values under (1) with , stratified by and pooled over p. (b) The recovery probability (30) under (1) with defined in (28) and . (c) The conditional power (29) at in the same settings, stratified by p, for the tests that control the selective Type I error under every ; at each the tests are drawn side by side, with 95% Wilson intervals.
5.3 Sensitivity to the Gaussian assumption
The validity of our proposals in Section 3 depends on the rows of X being Gaussian. We study the sensitivity to moderate deviations from this assumption in Appendix D. The null data have n = 200 and compound-symmetric , and their rows are drawn from a multivariate t distribution, drawn as Gaussian and censored at zero, or drawn as Gaussian with and reduced to their leading principal components before clustering, a common step in the analysis of high-dimensional data. The tests are less sensitive after k-means than after average linkage. After k-means, and control the selective Type I error with t rows (5 or 10 degrees of freedom) and after the reduction to principal components, and reject at most 7.1% of true null hypotheses with 5% of the entries censored. After average linkage, they reject at most 7.4% with 5% censoring but are anticonservative with t rows.
6 Data application
We apply the proposed tests to three data sets spanning gene expression microarrays, text embeddings, and single-cell RNA sequencing: leukemia samples (Section 6.1) and drug reviews (Section 6.2).

| Pair | 1-2 | 1-3 | 2-3 |
|---|---|---|---|
| Majority labels | AML 96% / B-ALL 67% | AML 96% / B-ALL 85% | B-ALL 67% / B-ALL 85% |
| Expected | “alternative”(24, 15) | “alternative”(24, 33) | “null”(15, 33) |
| 0.005 | 0.015 | 0.316 | |
| 0.969 | 0.208 | 0.990 | |
| 0.941 | 0.201 | 0.966 |
Figure 6: The leukemia data of Section 6.1. Left: a UMAP embedding, colored by cluster, with the known label as the plotting symbol. Right: naive and selective -values for each pair of clusters. The row Expected is “alternative” when the two clusters have different majority labels and “null” when they share one.
tion 6.2), both clustered by -means, and cells of the mouse brain, clustered by Leiden community detection (Section 6.3). We use the known labels in each data set to construct “alternative” data sets, whose observations come from several labeled groups, and, where possible, “null” data sets, whose observations come from a single group, and we evaluate the proposed tests against existing ones on them. We compute and with and for every pair of estimated clusters, together with the naive test and, after -means, the test of Chen and Witten (2023) with . Because the tests require , we reduce each data set to its leading principal components before clustering: ten for the leukemia data and twenty for the drug reviews and the mouse brain. The figures display each data set with UMAP (McInnes et al., 2018).
6.1 Leukemia microarray data
Golub et al. (1999) measured gene expression in 72 bone-marrow and blood samples from patients with acute lymphoblastic leukemia (ALL, 47 samples: 38 B-cell acute lymphoblastic leukemia and 9 T-cell acute lymphoblastic leukemia) or acute myeloid leukemia (AML, 25 samples). We preprocess the data as in Dudoit et al. (2002) and keep the first ten principal components.
We apply -means with and obtain clusters of 24, 15, and 33 samples: cluster 1 is AML, cluster 2 is B-cell ALL, and cluster 3 is B-cell ALL (Figure 6, left). The naive test rejects all three null hypotheses, with -values below (Figure 6, right). The test rejects the two contrasts between the AML cluster and a B-cell ALL cluster ( and 0.015), but not the contrast between the two B-cell ALL clusters (), which we expect not to differ much biologically. Neither nor the test of Chen and Witten (2023) with rejects any of the three, including the two contrasts between the AML cluster and a B-cell ALL cluster. This reflects the power lost to extra conditioning and to a conservative covariance estimate, respectively.
6.2 Drug reviews
We apply clustering to group patients by their reviews of the drugs they take, in data collected by Gräber et al. (2018) on Drugs.com. Each review is labeled with the condition that the drug was taken for and with a rating from 1 to 10. We use a random sample of 3,000 reviews of at least 20 words and represent each review by its 384-dimensional text embedding from the pretrained model

| Data set | Pair | Majority labels | Expected | |||||
|---|---|---|---|---|---|---|---|---|
| “Alternative” | 1-2 | Dep 93% / BC 91% | “alternative” | (107, 106) | 0.005 | 0.021 | 0.145 | |
| 1-3 | Dep 93% / Acne 98% | “alternative” | (107, 87) | 0.005 | 0.366 | 0.617 | ||
| 2-3 | BC 91% / Acne 98% | “alternative” | (106, 87) | 0.031 | 0.965 | |||
| “Null” | 1-2 | BC- 100% / BC- 100% | “null” | (41, 34) | 0.136 | 0.218 | 0.299 |
Figure 7: The drug reviews of Section 6.2. Top: a UMAP embedding of their principal components, colored by cluster, with the condition as the plotting symbol; left, the “alternative” data set; right, the “null” data set. Bottom: naive and selective p-values for each pair of clusters. The column Expected is “alternative” when the two clusters have different majority labels and “null” when they share one. Majority labels: Dep, depression; BC, birth control; BC-, birth control with a rating of 4 or less.
bge-small-en-v1.5 (Xiao et al., 2024). For each data set below, the features are the first twenty principal components of the embeddings, computed from the reviews that are not in that data set.
We construct an “alternative” data set by drawing 100 reviews each of drugs taken for birth control, depression, and acne, so n = 300. We apply k-means with K = 3 and obtain clusters of 107, 106, and 87 reviews: cluster 1 is 93% depression, cluster 2 is 91% birth control, and cluster 3 is 98% acne (Figure 7, top left). The naive test gives p-values below for all three pairs (Figure 7, bottom). The test also rejects all three null hypotheses (p between and 0.005), as it should for drugs taken for three different conditions, and rejects two of them. The test of Chen and Witten (2023) with rejects none (p between 0.15 and 0.97).
We construct a “null” data set by drawing 75 reviews of drugs taken for birth control with a rating of 4 or less. We apply k-means with K = 2 and obtain clusters of 41 and 34 reviews. The naive test rejects , but and do not .
6.3 Single-cell RNA sequencing of the mouse brain
In single-cell RNA sequencing, biologists routinely cluster cells to find putative cell types and then test the clusters for differences in gene expression. Zeisel et al. (2015) sequenced cells from the mouse cortex and hippocampus and labeled each cell with a cell type and a finer subclass. For each data set below, we choose the 2,000 most variable genes and the first twenty principal components from the cells that are not in that data set and project the analyzed cells onto them. We cluster with Leiden community detection (Traag et al., 2019) on the graph that joins each cell to its 15

| Data set | Pair | Majority labels | Expected | ||||
|---|---|---|---|---|---|---|---|
| “Alternative” | 1-2 | IN 100% / CA1 95% | “alternative” | (58, 63) | 0.002 | 0.969 | |
| 1-3 | IN 100% / OL 100% | “alternative” | (58, 59) | 0.003 | |||
| 2-3 | CA1 95% / OL 100% | “alternative” | (63, 59) | 0.961 | |||
| “Null” | 1-2 | CA1Pyr2 100% / CA1Pyr2 100% | “null” | (20, 40) | 0.757 | 0.461 |
Figure 8: The mouse brain cells of Section 6.3. Top: a UMAP embedding, colored by cluster, with the known label as the plotting symbol; left, the “alternative” data set; right, the “null” data set. Bottom: naive and selective p-values for each pair of clusters. The column Expected is “alternative” when the two clusters have different majority labels and “null” when they share one. Majority labels: IN, interneurons; CA1, CA1 pyramidal cells; OL, oligodendrocytes. No existing selective inference test applies to Leiden clustering.
nearest neighbors, with the resolution fixed at 0.5. No other selective test applies to this clustering, so we compare our tests with the naive test only.
We construct an “alternative” data set by drawing 60 cells each of interneurons, CA1 pyramidal cells, and oligodendrocytes, so n = 180. Leiden community detection returns clusters of 58, 63, and 59 cells: cluster 1 is 100% interneurons, cluster 2 is 95% CA1 pyramidal cells, and cluster 3 is 100% oligodendrocytes (Figure 8, top left). The naive test gives p-values below , and rejects all three null hypotheses (p between and 0.003), as it should for three distinct cell types. The test rejects only the contrast between interneurons and oligodendrocytes.
We construct a “null” data set by drawing 60 cells of the single subclass CA1Pyr2. Leiden community detection splits them into clusters of 20 and 40 cells. The naive test rejects the null hypothesis , while and do not . With 180 CA1Pyr2 cells instead of 60, Leiden community detection returns three clusters, the naive test again rejects all three null hypotheses , and rejects none .
7 Discussion
In this paper, we proposed a selective test for a difference in means between two estimated clusters when the covariance matrix in (1) is unknown and unstructured. The test does not estimate ; instead, it uses the polar decomposition of the tested observations, which splits their distribution into a part whose distribution depends on and an independent part whose distribution is known. As a result, the test avoids the trade-off between Type I error control and power that comes with a plug-in estimate of (Section 2.2), and it is exact in finite samples for any clustering algorithm. We gave two versions of the test. The test conditions on less, has higher power, and is computed by an exact Monte Carlo construction that takes longer to run. The one-dimensional test conditions on more information, is faster to compute, and has a closed form for k-means when we also condition on the sequence of assignments of Lloyd's algorithm.
These results suggest a number of extensions and open questions. First, we test the null hypothesis (5) that all observations in the two clusters share a mean, which is stronger than the null hypothesis (2) that the two cluster means are equal (Remark 2.2). Testing (2) without knowledge of remains open. Second, we have taken the tested pair as given; when the pair is chosen from the data, for example as the two clusters that look most separated, the conditional distribution of Q must be reweighted by the probability of that choice in the Monte Carlo simulation. Third, any reversible kernel gives a p-value that controls the selective Type I error, but different kernels and different values of their parameters lead to different power, and the best choice for a given n, p, and remains an open question. Fourth, we assumed that the rows of X are independent; testing data with correlated observations could build on the techniques of González-Delgado et al. (2026). Fifth, we would like to extend the test to non-Gaussian data, such as the counts that arise in single-cell RNA sequencing, using techniques from data fission (Leiner et al., 2025) and data thinning (Neufeld et al., 2024a; Dharamshi et al., 2025).
AI assistance statement
During manuscript development, the authors used AI assistants, including GPT-5.5 and coding agents, as interactive tools for mathematical brainstorming, software development, and editorial review. This assistance included proposing and stress-testing proof strategies, checking notation and edge cases, drafting code scaffolds for simulations and manuscript packaging, and suggesting revisions to the exposition. Several proof directions that shaped the final presentation were developed through this workflow: the covariance-free polar-factor formulation, the conditioning argument on the Stiefel feasible set, the Besag–Clifford random-index validity proof, the algorithm-agnostic extension to hierarchical clustering, and the oracle-geometry statement separating validity from power. AI outputs were treated as suggestions rather than evidence: all mathematical derivations, code, simulation outputs, citations, and prose were checked, revised, and verified by the authors, who take full responsibility for the final content.
References
E. Ahlqvist, P. Storm, A. Käräjämäki, et al. Novel subgroups of adult-onset diabetes and their association with outcomes: A data-driven cluster analysis of six variables. The Lancet Diabetes & Endocrinology, 6(5):361–369, 2018.
T. W. Anderson. An Introduction to Multivariate Statistical Analysis. Wiley, Hoboken, NJ, 3rd edition, 2003.
A. J. Aw, J. P. Spence, and Y. S. Song. A flexible and robust non-parametric test of exchangeability. arXiv:2109.15261, 2021.
F. Bachoc, C. Maugis-Rabusseau, and P. Neuvial. Selective inference after convex clustering with penalization. ESAIM: Probability and Statistics, 29:204–242, 2025.
S. Balakrishnan, M. J. Wainwright, and B. Yu. Statistical guarantees for the EM algorithm: From population to sample-based analysis. The Annals of Statistics, 45:77–120, 2017.
C. J. P. Bélisle, H. E. Romeijn, and R. L. Smith. Hit-and-run algorithms for generating multivariate distributions. Mathematics of Operations Research, 18(2):255–266, 1993.
J. Besag and P. Clifford. Generalized Monte Carlo significance tests. Biometrika, 76(4):633–642, 1989.
D. Cai, T. Campbell, and T. Broderick. Finite mixture models do not reliably learn the number of components. In Proceedings of the 38th International Conference on Machine Learning, volume 139 of Proceedings of Machine Learning Research, pages 1158–1169, 2021.
T. T. Cai, Z. Ren, and H. H. Zhou. Estimating structured high-dimensional covariance and precision matrices: Optimal rates and adaptive estimation. Electronic Journal of Statistics, 10(1):1–59, 2016.
T. T. Cai, J. Ma, and L. Zhang. CHIME: Clustering of high-dimensional Gaussian mixtures with EM algorithm and its optimality. The Annals of Statistics, 47:1234–1267, 2019.
H. Chen, J. Chen, and J. D. Kalbfleisch. Testing for a finite mixture model with two components. Journal of the Royal Statistical Society: Series B, 66:95–115, 2004.
J. Chen and P. Li. Hypothesis test for normal mixture models: The EM approach. The Annals of Statistics, 37:2523–2542, 2009.
Y. Chen, S. Jewell, and D. Witten. More powerful selective inference for the graph fused lasso. Journal of Computational and Graphical Statistics, 32(2):577–587, 2023.
Y. T. Chen and D. M. Witten. Selective inference for k-means clustering. Journal of Machine Learning Research, 24:1–41, 2023.
Y. Chikuse. Statistics on Special Manifolds, volume 174 of Lecture Notes in Statistics. Springer, New York, 2003.
N. C. Chung. Statistical significance of cluster membership for unsupervised evaluation of cell identities. Bioinformatics, 36:3107–3114, 2020.
N. C. Chung and J. D. Storey. Statistical significance of variables driving systematic variation in high-dimensional data. Bioinformatics, 31:545–554, 2015.
A. Dharamshi, A. Neufeld, K. Motwani, L. L. Gao, D. Witten, and J. Bien. Generalized data thinning using sufficient statistics. Journal of the American Statistical Association, 120(549): 511–523, 2025.
A. Dharamshi, A. Neufeld, L. L. Gao, J. Bien, and D. Witten. Decomposing Gaussians with unknown covariance. Biometrika, 113(1):asaf057, 2026.
E. Dobriban. Permutation methods for factor analysis and PCA. The Annals of Statistics, 48(5):2824–2847, 2020.
S. Dudoit, J. Fridlyand, and T. P. Speed. Comparison of discrimination methods for the classification of tumors using gene expression data. Journal of the American Statistical Association, 97(457):77–87, 2002.
J. Fan, Y. Liao, and H. Liu. An overview of the estimation of large covariance and precision matrices. The Econometrics Journal, 19(1):C1–C32, 2016.
W. Fithian, D. Sun, and J. Taylor. Optimal inference after model selection. arXiv:1410.2597, 2014.
L. L. Gao, J. Bien, and D. Witten. Selective inference for hierarchical clustering. Journal of the American Statistical Association, 119(545):332–342, 2024.
G. H. Golub and C. F. Van Loan. Matrix Computations. Johns Hopkins University Press, Baltimore, 4th edition, 2013.
T. R. Golub, D. K. Slonim, P. Tamayo, C. Huard, M. Gaasenbeek, J. P. Mesirov, H. Coller, M. L. Loh, J. R. Downing, M. A. Caligiuri, C. D. Bloomfield, and E. S. Lander. Molecular classification of cancer: Class discovery and class prediction by gene expression monitoring. Science, 286(5439): 531–537, 1999.
J. González-Delgado, M. Deronzier, J. Cortés, and P. Neuvial. Post-clustering inference under dependence. Journal of the American Statistical Association, 2026. doi: 10.1080/01621459.2026.2707221. arXiv:2310.11822.
F. Gräßer, S. Kallumadi, H. Malberg, and S. Zaunseder. Aspect-based sentiment analysis of drug reviews applying cross-domain and cross-data learning. In Proceedings of the 2018 International Conference on Digital Health, pages 121–125. ACM, 2018. doi: 10.1145/3194658.3194677.
A. Guha, N. Ho, and X. Nguyen. On posterior contraction of parameters and interpretability in Bayesian mixture modeling. Bernoulli, 27(4):2159–2188, 2021.
H. Hotelling. The generalization of Student's ratio. The Annals of Mathematical Statistics, 2(3): 360–378, 1931.
M. Howes. Markov chain Monte Carlo significance tests. arXiv:2310.04924, 2023.
S. Jewell, P. Fearnhead, and D. Witten. Testing for a change in mean after changepoint detection. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 84(4):1082–1104, 2022.
J. Jin and W. Wang. Influential features PCA for high dimensional clustering. The Annals of Statistics, 44:2323–2359, 2016.
M. K. Kerr and G. A. Churchill. Bootstrapping cluster analysis: Assessing the reliability of conclusions from microarray experiments. Proceedings of the National Academy of Sciences, 98: 8961–8965, 2001.
P. K. Kimes, Y. Liu, D. N. Hayes, and J. S. Marron. Statistical significance for hierarchical clustering. Biometrics, 73:811–821, 2017.
V. N. Le Duy and I. Takeuchi. More powerful conditional selective inference for generalized lasso by parametric programming. Journal of Machine Learning Research, 23(300):1–37, 2022.
O. Ledoit and M. Wolf. Analytical nonlinear shrinkage of large-dimensional covariance matrices. The Annals of Statistics, 48(5):3043–3065, 2020.
J. D. Lee, D. L. Sun, Y. Sun, and J. E. Taylor. Exact post-selection inference, with application to the lasso. Annals of Statistics, 44(3):907–927, 2016.
E. L. Lehmann and J. P. Romano. Testing Statistical Hypotheses. Springer, New York, 3rd edition, 2005.
J. Leiner, B. Duan, L. Wasserman, and A. Ramdas. Data fission: Splitting a single data point. Journal of the American Statistical Association, 120(549):135–146, 2025.
P. Li and J. Chen. Testing the order of a finite mixture. Journal of the American Statistical Association, 105:1084–1092, 2010.
L. McInnes, J. Healy, and J. Melville. UMAP: Uniform manifold approximation and projection for dimension reduction. arXiv:1802.03426, 2018.
G. J. McLachlan, S. X. Lee, and S. I. Rathnayake. Finite mixture models. Annual Review of Statistics and Its Application, 6:355–378, 2019.
Y. Miyata, T. Shiraishi, S. Nishino, and I. Takeuchi. Statistical testing framework for clustering pipelines by selective inference. arXiv:2603.18413, 2026.
E. Mizui, T. Shiraishi, S. Nishino, and I. Takeuchi. Selective inference for deep clustering in latent spaces. arXiv:2609.28756, 2026.
R. J. Muirhead. Aspects of Multivariate Statistical Theory. Wiley, New York, 1982.
R. M. Neal. Slice sampling. The Annals of Statistics, 31(3):705–767, 2003.
R. M. Neal. MCMC using Hamiltonian dynamics. In S. Brooks, A. Gelman, G. L. Jones, and X.-L. Meng, editors, Handbook of Markov Chain Monte Carlo, pages 113–162. Chapman and Hall/CRC, 2011.
A. Neufeld, A. Dharamshi, L. L. Gao, and D. Witten. Data thinning for convolution-closed distributions. Journal of Machine Learning Research, 25(57):1–35, 2024a.
A. Neufeld, J. Popp, L. L. Gao, A. Battle, and D. Witten. Inference after latent variable estimation for single-cell RNA sequencing data. Biostatistics, 25(1):270–287, 2024b.
A. Neufeld, R. Perry, and D. Witten. Inference conditional on selection: A review. arXiv:2604.09779, 2026.
A. Nobile. On the posterior distribution of the number of components in a finite mixture. The Annals of Statistics, 32:2044–2073, 2004.
D. Paulson, S. Sengupta, and L. Janson. The L-test: Increasing the linear model F-test's power under sparsity without sacrificing validity. arXiv:2511.23466, 2025.
D. G. Rasines and G. A. Young. Splitting strategies for post-selection inference. Biometrika, 110(3):597–614, 2023.
S. Sengupta and L. Janson. The -test: Leveraging sparsity in the Gaussian linear model for improved inference. arXiv:2406.18390, 2024.
R. L. Smith. Efficient Monte Carlo procedures for generating points uniformly distributed over bounded regions. Operations Research, 32(6):1296–1308, 1984.
R. Suzuki and H. Shimodaira. Pvclust: An R package for assessing the uncertainty in hierarchical clustering. Bioinformatics, 22:1540–1542, 2006.
V. A. Traag, L. Waltman, and N. J. van Eck. From Louvain to Leiden: guaranteeing well-connected communities. Scientific Reports, 9:5233, 2019. doi: 10.1038/s41598-019-41695-z.
Z. Wang, Q. Gu, Y. Ning, and H. Liu. High dimensional EM algorithm: Statistical optimization and asymptotic normality. In Advances in Neural Information Processing Systems, volume 28, pages 2512–2520, 2015.
M. Wedel and W. A. Kamakura. Market Segmentation: Conceptual and Methodological Foundations. Kluwer Academic Publishers, Boston, 2nd edition, 2000.
Z. Wen and W. Yin. A feasible method for optimization with orthogonality constraints. Mathematical Programming, 142(1–2):397–434, 2013.
S. Xiao, Z. Liu, P. Zhang, N. Muennighoff, D. Lian, and J.-Y. Nie. C-Pack: Packed resources for general Chinese embeddings. In Proceedings of the 47th International ACM SIGIR Conference on Research and Development in Information Retrieval, 2024.
X. Yi and C. Caramanis. Regularized EM algorithms: A unified framework and statistical guarantees. In Advances in Neural Information Processing Systems, volume 28, 2015.
Y. Yun and Y. He. Selective inference for multiple pairs of clusters after K-means clustering. arXiv:2405.16379, 2024.
Y.-J. Yun and R. F. Barber. Selective inference for clustering with unknown variance. Electronic Journal of Statistics, 17(2):1923–1946, 2023. doi: 10.1214/23-EJS2143.
A. Zeisel, A. B. Muñoz-Manchado, S. Codeluppi, P. Lönnnerberg, G. La Manno, A. Juréus, S. Marques, H. Munguba, L. He, C. Betsholtz, C. Rolny, G. Castelo-Branco, J. Hjerling-Leffler, and S. Linnarsson. Cell types in the mouse cortex and hippocampus revealed by single-cell RNA-seq. Science, 347(6226):1138–1142, 2015. doi: 10.1126/science.aaa1934.
A Proofs for Sections 3.1 to 3.3
This appendix proves Theorem 3.1 and Propositions 3.2 and 3.3, one per subsection, and Appendix A.4 compares the three one-dimensional tests. Appendix B uses the same notation.
Preliminaries and notation. Fix a matrix whose columns are an orthonormal basis of the range of , so that
The matrix holds the coordinates of in this basis: and . Every matrix in is times a matrix in , and multiplying by preserves inner products, so we identify the polar factor with its coordinates and write for both. In coordinates,
where is a unit vector, the uniform distribution on becomes the uniform distribution on , written , and the Givens rotation (21) becomes the rotation of rows and , still written .
A.1 Proof of Theorem 3.1
The proof uses the distribution of the coordinates Z.
Proposition A.1 (Distribution of the coordinates). Under data model (1) and null (5), the matrix Z follows and is independent of .
Proof. Multiplying (1) on the left by gives . Under (5), the rows of in are equal, so and . The matrices and are jointly Gaussian, and their cross-covariance is proportional to , so they are independent.
Proof of Theorem 3.1. We must show that Q is uniformly distributed on and independent of . Because is a function of Z, which is independent of by Proposition A.1, it is enough to show that for all bounded functions of Q and of H,
The matrix has rank with probability one when , so is invertible and .
Next, let O be a uniformly distributed orthogonal matrix, drawn independently of X. By Proposition A.1,
so OZ has the same distribution as Z. The polar decomposition of OZ is (OQ)H, because OQ has orthonormal columns and . So (OQ, H) has the same distribution as (Q, H), and
Finally, for a fixed , the matrix is uniformly distributed on , so the inner expectation equals whatever the values of and . This gives (31).
A.2 Proof of Proposition 3.2
Proposition 3.2 makes two claims: the identity (12), which holds for any data with an invertible pooled covariance, and the Beta distribution of under the null.
Proof of the identity (12). Write and , with the polar factor of Section 3.1. Since , we have . We write both ingredients of , the difference in cluster means and the pooled covariance, in terms of and .
The difference in cluster means is , and , so
The vector lies in the range of , so , and by (11),
Since , the same identity gives
The matrix has determinant , so the pooled covariance is invertible exactly when . Substituting (33) and (34) into (32), the factors cancel:
By the Sherman–Morrison formula,
With , this is (12). When , and , which gives .
Proof of the distribution in Proposition 3.2. By Theorem 3.1, under the null Q is uniformly distributed on , and in coordinates for the fixed unit vector . We find the distribution in three steps.
First, a uniformly distributed Q has the same distribution as the first p columns of a uniformly distributed orthogonal matrix . Then consists of the first p entries of the vector .
Second, is a fixed unit vector turned by a uniformly distributed orthogonal matrix, so it is uniformly distributed on the unit sphere of . A standard Gaussian vector has a distribution that is unchanged by orthogonal matrices, so its direction is also uniformly distributed on the sphere. Hence has the same distribution as .
Third, therefore,
with and independent, and such a ratio has the Beta distribution. The statement for follows from (12), because is a ratio of independent variables divided by their degrees of freedom. The substitution gives the density of Section 4.3.
A.3 Proof of Proposition 3.3
Proposition 3.3 makes three claims. (a) Given , , and the event that the clustering returns and , the polar factor is uniformly distributed on . (b) The -value is the ratio of integrals in (14). (c) Under the null, is uniformly distributed given that the clustering returns and . Throughout, is the set of Section 3.3 with the random in place of their observed values,
Proof of (a). The data are , so the clustering returns and exactly when . By Theorem 3.1, is uniformly distributed and independent of , and is fixed once is. So for every set ,
Taking gives , and dividing the two displays,
which is the uniform distribution on . The division is allowed: the clustering returns the tested clusters while with probability .
Proof of (b). By (12), increases with , so exactly when . Taking in (a) gives (14).
Proof of (c). Fix and . For a number , the probability that when is uniformly distributed on is
By (b), , and by (a), under the null is a draw from the uniform distribution on .
The function is continuous. Under the uniform distribution on , has a Beta distribution (Proposition 3.2), so each value has probability zero. The uniform distribution on is the uniform distribution on restricted to a set of positive probability, so each value still has probability zero.
For a random variable with a continuous distribution, its upper tail probability evaluated at the variable itself is uniformly distributed (the probability integral transform). Hence
The right side does not depend on , so averaging over them given the selection event gives the statement conditional on the selection event alone.
A.4 Three one-dimensional tests side by side
Table A.1 lists, for the test of Gao et al. (2024), the test of Yun and Barber (2023), and , the null hypothesis, the nuisance parameters, the parts of that each test holds fixed, and the scalar that remains random.
Table A.1: Nuisance parameters and conditioning in three one-dimensional selective tests. Each test conditions on the selection event, on statistics that remove the nuisance parameters under its null, and on further statistics that leave one scalar random.
| Gao et al. (2024) | Yun and Barber (2023) | (any ) | |
|---|---|---|---|
| null | (2) | (5) | (5) |
| nuisance parameters | means, | means, | |
| removed by fixing | |||
| fixed to reach one dimension | |||
| random scalar | |||
| null distribution |
B The k-means trajectory event and the Monte Carlo kernels
This appendix proves the results of Sections 3.4, 4.1, 4.2, and 4.4. Appendices B.1 and B.2 show that the event that Lloyd's algorithm repeats its observed sequence of assignments is a set of quadratic inequalities in Q, with closed-form solutions on a Givens circle; Appendices B.3 to B.6 prove the reversibility of the kernels, Proposition 3.4 on the one-dimensional test, and the exactness of the Besag–Clifford p-value.
We use the notation of Appendix A: the basis A, the polar factor Q written in coordinates in , and for the uniform distribution on . We write S for the set of polar factors that the test conditions on .
B.1 The trajectory event is quadratic in Q
This subsection proves Proposition 4.3. For a polar factor Q, the data set
keeps and and replaces the polar factor. Writing for the ith row of , which is zero for observations outside , and for the ith row of , each observation is an affine function of ,
Let be the observations that the observed sequence assigns to cluster at iteration ; no cluster is empty at any iteration, since otherwise Lloyd's algorithm is not defined. With these assignments held fixed, each centroid is a fixed average of the rows (36), so it is also affine in :
for , and the initial centroids are affine by (36).
Proof of Proposition 4.3. Fix , , and a cluster . Expanding the two squared distances in (26), the terms cancel and
Substituting (36) and (37), the terms with two factors of Q are
the terms with one factor of Q are linear in its entries, and the rest does not depend on Q. All coefficients are determined by , , and . So is a quadratic polynomial in the entries of , and is the intersection of the sets over all , , and , which are quadratic inequalities.
The proof uses the observed assignments at every iteration. If we condition only on the final clusters, the intermediate assignments vary with Q, and formally
(38) where the union is over the sequences of assignments that end in clusters containing and . Each is an intersection of quadratic sets, so is a union of intersections of quadratic sets. The union is finite, but the number of sequences can be very large and they cannot be listed in advance, which is why we condition on when we want closed forms. Techniques that compute such unions of truncation sets efficiently have been developed for other selective tests (Le Duy and Takeuchi, 2022; Chen et al., 2023) and might apply here.
B.2 Closed-form feasible arcs on a Givens circle
This subsection proves Proposition 4.4 and gives the hit-and-run step. Fix the current and a pair of rows . Then
where has rows i and j equal to those of Q and has rows i and j equal to . and , all other rows being zero. By (35),
The proof below uses only this form, , so it covers any curve in Proposition 4.4, with and . The one-dimensional path of Section 3.4 has the same form, with , , and in place of , , and . With the assignments fixed by , each centroid is the same fixed average of the rows of , , and ,
Proof of Proposition 4.4. Fix , an observation with observed label , and a cluster . The differences between observation and the two centroids are
with and for . The difference of the two squared norms is
where
Using , , and gives (27),
(40)
To find the zeros, substitute , so that
Algorithm B.1 One step of the hit-and-run kernel on the trajectory event
Require: current ; , , and the observed sequence
1: Draw a pair of rows uniformly from
2: Form , , from (39) and the centroid coefficients , ,
3: for each constraint do
4: Compute from (40); skip the constraint if it holds on the whole circle
5: Add the real roots of (41), mapped to angles, to the list of endpoints (and if )
6: end for
7: Keep the intervals between consecutive endpoints whose midpoints satisfy every constraint, giving
8: Draw uniformly on
Ensure:
Multiplying g by gives the polynomial
Each real root of gives a zero = 2 of , and every zero of in arises this way. The substitution misses only , where is infinite. At ,
which is the leading coefficient of . So is a zero exactly when has degree at most three.
We can now count the zeros. If is identically zero, the constraint holds on the whole circle and plays no role. Otherwise, either and the zeros of are the at most four real roots of the quartic , or and the zeros are and the at most three real roots of the cubic . In both cases has at most four zeros on the circle.
Finally, each is continuous in , so it keeps its sign between two consecutive zeros. Take all the zeros of all the constraints together and sort them by increasing angle in . On each interval between two consecutive zeros, every constraint keeps its sign, so either every point of the interval satisfies all the constraints or none does. The feasible set on the circle is therefore a union of intervals whose endpoints are among these zeros. There are at most four zeros per constraint, so the number of intervals is at most four times the number of constraints; a single constraint alone gives at most two intervals.
We also note two shortcuts that further reduce the computational cost. First, some constraints hold on the whole circle and can be dropped. The two pairs of terms in (40) are bounded, and , so if
then for every , and the constraint can be skipped. Second, the feasible set can be read off from the zeros of the remaining constraints. Sort these zeros by increasing angle from 0 to , and add 0 and as the first and last points. On each interval between two consecutive points, the proof above shows that either every point is feasible or none is, so it is enough to check one point, the midpoint, against all the constraints. Keep the intervals whose midpoint is feasible, and merge neighboring kept intervals into one. Algorithm B.1 gives one step of the hit-and-run kernel. We checked the closed-form intervals against a dense grid of angles: they agreed at all 400,000 grid points we tried.
B.3 Reversibility of the hit-and-run kernel
This subsection proves that the hit-and-run kernel of Section 4.4 is reversible with respect to the uniform distribution on S, which is all that Proposition 4.2 requires. The proof does not use the quadratic form of S; it holds for any set S with .
Fix a pair of rows . Rotating rows and of by every angle gives the points , which form a closed curve through in ; we call this curve the circle through . (Figure 3(b) shows the data along such a circle, and Figure 3(c) shows the angles .) The fraction of this circle that lies in is
The kernel moves to with drawn uniformly from the feasible angles . So, when , the expected value of a bounded function after one step is
and leaves in place when . The hit-and-run kernel draws the pair uniformly and then applies .
Two facts about circles drive the proof. First, a function that depends on Q only through its circle takes the same value at as at Q for every ; examples are z and , because replacing Q by only shifts the angle of integration. Second, the uniform distribution on is unchanged by multiplying on the left by an orthogonal matrix, so for every . Averaging this identity over , and then applying it to a product in which g depends on Q only through its circle, gives
In words, inside an integral against , can be replaced by its average over the circle.
Proposition B.1 (Reversibility of the hit-and-run kernel). Each , the kernel , and every power are reversible with respect to the uniform distribution on .
Proof. By definition, is reversible with respect to the uniform distribution on if moving from to a new point is as likely as moving back. Equivalently, for all bounded functions and , the integral is unchanged by swapping and .
Step 1: for almost every . Formula (42) needs , that is, a circle with a feasible arc of positive length. Applying (43) with and ,
So the other case has probability zero.
Step 2: symmetry. The function depends on only through its circle, so (43) with and , followed by (42), gives
The right side is symmetric in and , so is reversible.
Finally, averages the kernels with weights that do not depend on , and an average of reversible kernels is reversible. A power of a reversible kernel is reversible too, so is.
Two remarks complete the picture. First, reversibility is all that the exactness of the test needs: the kernel need not reach every part of S, which can be disconnected. How well it moves through S affects only the power, which is why the path length M and the number of steps L matter (Section 4.2). Second, the pair of rows is drawn afresh at every step, independently of Q, so it is part of the kernel and not an extra condition; keeping one pair fixed for the whole path would keep the path on one circle.
B.4 Proof of Proposition 3.4
This subsection proves Proposition 3.4, the one-dimensional selective p-value, in three steps. We first describe all polar factors with the same coordinates (Proposition B.2), then show that is independent of , and finally condition on the clustering.
In coordinates, write with . Since , we have . Let , a unit vector with , and split it into its parts along and orthogonal to :
where is the within-cluster direction in coordinates. With , the coordinates of Section 3.4 are , and
Proposition B.2 (Polar factors with the same ). The coordinates satisfy
Conversely, for every triple that satisfies (46) and every , the matrix lies in and has coordinates and between-cluster fraction . Hence the polar factors with the same as form the curve
along which .
Proof. We check (46) one identity at a time. The vector is a direction, and has length one because . Next, , and . For the products with ,
and is a combination of these two, so it is zero too. Finally, .
For the converse, fix a triple that satisfies (46) and , and let and . The vector has length one, because and are orthogonal unit vectors, and . So
and . Its coordinates are the given ones: , so and the direction of is ; then , whose split (44) returns ; and . Writing with gives (47).
Proof of the independence in Proposition 3.4. Under the null, Q is uniformly distributed on St(r-1,p) (Theorem 3.1). We show that u and are independent, using maps that change but not u or the distribution of Q. Call a triple admissible if it satisfies (46). By Proposition B.2, the set of admissible triples does not depend on u.
Step 1: the maps. Let be an orthogonal matrix with , and a orthogonal matrix. The map does not change the uniform distribution on . It keeps , because has the same length as , and it changes the coordinates to .
Step 2: the maps reach every admissible triple. Take two admissible triples and . Choose with , and let . Let be an orthonormal basis of the vectors orthogonal to . By (46), the two lists
each consist of orthonormal vectors orthogonal to . The vectors orthogonal to form a space of dimension , so there is an orthogonal with that maps the first list to the second. Then and , since both sides agree on and vanish on . So carries the first triple to the second. For , there are no s.
Step 3: averaging. Draw uniformly among such pairs, independently of , and write for the transformed coordinates. For a fixed admissible triple , the distribution of does not depend on : by Step 2, any other triple is a fixed map applied to , and composing a uniform draw with a fixed map gives another uniform draw. So for a bounded function of the triple, is the same for every . For a bounded function on , Step 1 gives the first equality below:
Taking to be the constant 1 shows , so : the expectation factors, and and are independent.
The factor in is what a direct count misses. Given , the vector lies on the unit sphere of the -dimensional space orthogonal to the columns of . If it were uniform there, the angle would have density proportional to , which contradicts Proposition 3.2.
Proof of the conditional statement in Proposition 3.4. We condition on , , , and the clustering, in four steps. Write for the angle with .
Step 1: the angle given ( , , ). By Theorem 3.1, is independent of ( , ), and by the independence just proved, is independent of . So given ( , , ), keeps its Beta( , ) distribution, and the angle has the density of Section 4.3.
Step 2: the selection event in terms of the angle. Given , Proposition B.2 gives , so the data are , a function of alone. The clustering therefore returns and exactly when , with in (18) computed from .
Step 3: Bayes’ rule. Conditioning the density on the event gives the truncated density (23), provided . Values of with have probability zero given the selection event, as in the proof of Proposition 3.3(a).
Step 4: uniformity. The truncated density (23) has a continuous distribution function, even when is a union of intervals. Since decreases in , the event is the event , so in (24) is the distribution function of (23) evaluated at the observed angle , which is a draw from (23) under the null. By the probability integral transform it is uniformly distributed, and averaging over given the selection event keeps it uniform. Finally, the change of variables turns (23) into the density truncated to .
B.5 Propose-and-check kernels
The random Givens kernel of Section 4.1 proposes a random rotation of Q and keeps it only if the clustering algorithm returns the tested clusters. Two facts make such kernels reversible with respect to the uniform distribution on S; we state them in the coordinates of this appendix.
Proposition B.3 (Accepting only feasible proposals). Let be a proposal on that is reversible with respect to the uniform distribution. The kernel that moves from to a proposal if , and stays at otherwise, is reversible with respect to the uniform distribution on .
Proof. For bounded functions , reversibility of means
Applied to , it shows that the accepted moves are symmetric in ; the rejected moves leave in place and are symmetric trivially. Their sum is the kernel.
Proposition B.4 (Symmetric random rotations). Let be a random orthogonal matrix, drawn independently of , such that has the same distribution as . Then the proposal is reversible with respect to the uniform distribution. The distribution of may depend on , , and the clustering. Two examples are
-
the random Givens kernel, with uniform and symmetric about zero, for which ;
-
the Cayley random walk, with a random skew-symmetric matrix such that has the same distribution as , for which is this map at .
Proof. For a bounded function , the substitution , under which the uniform distribution is unchanged, and then the equality in distribution of and give
which is the reversibility of the proposal. For the Cayley map, the eigenvalues of a real skew-symmetric matrix are purely imaginary, so is invertible, and because commute, .
Proof of Proposition 4.1. For a fixed step size , the random Givens kernel accepts only feasible proposals from the proposal of Proposition B.4, so it is reversible by Proposition B.3. A power of a reversible kernel is reversible, and the kernel that draws from a fixed distribution and then takes L steps is an average of reversible kernels with weights free of Q, so it is also reversible.
Our Cayley random walk draws with a matrix of independent standard normal entries, and draws as the random Givens kernel does. Neither proposition covers a step size tuned on trial moves from (Section 4.2).
B.6 Proof of the exactness of the Besag–Clifford p-value
Proof of Proposition 4.2. Fix , , and the event that the clustering returns and . Because , , and depend on the data only through these, is a fixed kernel and a fixed integer, and , , and the random inputs of every step are drawn independently of . Write for the distribution of one step of the path from , and . By Proposition 3.3, has distribution , and reversibility means
A Givens step has no density, so these are statements about distributions, not densities.
The path. Applying reversibility to , and so on, gives for every k
Given , Algorithm 1 starts at and runs the chain backward to and forward to , so the path has distribution
by (48). The right side does not depend on : it is the distribution of a chain started from the uniform distribution on . So , which is uniform on , is independent of the path. The points of the path need not be exchangeable; only the position of the observed point is uniform (Howes, 2023, Section 3.2).
The rank. Fix a path, and let its distinct values of , in decreasing order, occur times, with . Given the path, the observed point falls in the th group with probability , and then is uniform on the interval . So, given the path, has density
because the intervals cover without overlap. So is uniform given the path, even when all values are tied. Averaging over the path completes the proof.
The kernels. The random Givens kernel is reversible by Proposition 4.1 and the hit-and-run kernel by Proposition B.1; in both cases L steps are reversible too.
C Additional material on the Monte Carlo test
This appendix collects material on the Monte Carlo test of Sections 4.1 and 4.2 that the main text only mentions. Appendix C.1 gives the algorithm for the one-dimensional test, Appendix C.2 explains why a naive Markov chain estimator is not a valid p-value, Appendix C.3 shows how the path length, the number of steps between points of the path, and the step size affect the test, and Appendix C.4 compares kernels.
Algorithm C.1 The one-dimensional selective test for any clustering algorithm
Require: data , clustering algorithm , tested clusters , path length , number of steps
1: Compute , and as in Algorithm 1
2: , , and
3: Draw uniformly from and set
4: for do
5:
6: end for
7: for do
8:
9: end for
10: Draw
Ensure:
11: function
12: Draw uniformly on
13: for do
14: Draw and , and set
15: if and then
16: if then
17:
18: end if
19: end if
20: end for
21: return
22: end function
C.1 The algorithm for the one-dimensional test
Algorithm C.1 computes in (24) for any clustering algorithm, as described in Section 4.3. It follows Algorithm 1, with the angle in place of the polar factor and a Metropolis step for the density (23) in place of the random Givens kernel.
C.2 A naive Markov chain estimator
This subsection records the naive Markov chain estimator mentioned in Section 4.1 and why it fails. Its target distribution, the uniform distribution on , is the right conditional reference, but drawing useful Monte Carlo samples from that target is hard unless the proposal is designed around the geometry of the selection event. The Besag–Clifford test of Section 4.2 needs none.
The naive estimator is built from post-burn-in draws with the uniform distribution on as stationary distribution,
If the draws were close to independent conditional samples, this would approximate the selective tail probability. In our problem they are not. The selection event leaves a thin feasible set around the observed configuration, and a generic random walk that accepts only feasible moves travels through it slowly. The dimension of the Stiefel manifold is
so larger tested pairs and larger feature dimension both make the exploration harder. On the 24 null cells with , , and isotropic, AR(1), or compound-symmetric (600 replicates each), the naive estimator with a Cayley random-walk kernel, 1,000 burn-in steps, and 2,500 post-burn-in draws thinned by 5 has median selective Type I error 0.077 and reaches 0.185 at , ; at and it lies between 0.12 and 0.20, while the Besag–Clifford test is calibrated in the same cells. The bottleneck is not rejection of proposals; step-size adaptation keeps the acceptance rate moderate:
| p = 2 | p = 10 | p = 50 | |
|---|---|---|---|
| Cayley acceptance rate | ≈ 0.40 | ≈ 0.36 | ≈ 0.31 |
The naive estimator is valid only when the chain has mixed, which the Type I errors above show it has not. The Besag–Clifford p-value of Section 4.2 does not need mixing: it is exact for any reversible kernel and any path length (Proposition 4.2), and better kernels and longer paths only add power.
C.3 Path length, number of steps, and step size
Figure C.1 illustrates Section 4.2. On null data the Type I error of stays at the nominal level from to (between 0.047 and 0.056 over 1,021 replicates, each evaluated at every , with steps between points), while on data with a signal the power grows with and levels off (473 to 493 recovered replicates per separation). The identity kernel is an extreme case: it is reversible, and it returns , which is exactly uniform and has no power.
The requirement that the kernel, , and depend on the data only through , , and the clustering cannot be dropped. Take the two-point space with the uniform distribution, , and the kernel that always moves to the other point, which is reversible. Taking and when but when gives , although each fixed is reversible. Tuning a step size on trial moves from is a choice of this kind. A step size, or a number of steps, drawn afresh for each block of steps from a fixed distribution is allowed, because the kernel of one block is then a mixture of reversible kernels with weights that do not depend on the current point of the path.
C.4 A pilot comparison of kernels
We compared four kernels in the construction of Section 4.2 on the design of Figure 1 (, , compound-symmetric with correlation 0.6, -means with ), with and :
• the random Givens kernel of Section 4.1;
• the Cayley random walk of Appendix B.5;
-
a Givens step that draws the angle by a slice sampler with shrinkage (Neal, 2003), which moves at every step but runs the clustering several times per step;
-
the hit-and-run step on the exact arcs of Section 4.4, which conditions on the Lloyd trajectory.

Figure C.1: Path length changes power but not the Type I error (n = 45, p = 10, K = 3). Left: selective Type I error against the path length M on null data, each replicate evaluated at every M. Right: conditional power against M for five separations (one curve each).
On 588 null pairs, the Type I error at level 0.05 was 0.029 for the random Givens kernel, 0.070 for the Cayley random walk, 0.049 for the slice version, and 0.067 for the exact arcs (297 pairs). All four kernels are exact by Proposition 4.2, and on a toy problem where is drawn uniformly from a known set, both the Givens and the Cayley kernels gave rejection rates of 0.050 (Givens) and 0.053 (Cayley) over 2,000 replicates, so we attribute the spread above to Monte Carlo error. With separation (111 pairs), the power was 0.973 for the random Givens kernel (7 seconds per p-value), 0.955 for the Cayley random walk (10 seconds), and 1.000 for the slice version (38 seconds, about 10,000 runs of the clustering against 2,000 for the other two).
A larger run compared the random Givens kernel and the Cayley random walk with and in two settings with compound-symmetric : the design above, and with , each with about 2,100 null pairs. Both kernels control the selective Type I error (Figure C.2(a)), and both reject for 98% to 100% of the pairs of true clusters at the separations we ran. The random Givens kernel is 20% to 30% faster (Figure C.2(b)) and moves at about 65% of its steps, against 3% to 11% for the Cayley random walk (Figure C.2(c)).
D Additional simulation results
This appendix reports every cell of the k-means simulation study of Section 5, which Figure 4 summarizes. It also gives the results for Leiden community detection, the rows of Section 5.3 that are not Gaussian, and the computing time of each test. The figures of this appendix also show a reference that is not available in practice, , which replaces Hotelling's in by and so requires the true . Its conditional power is close to that of , except when is close to the number of tested rows , where estimating costs power.
Selective Type I error of k-means. Table D.1 gives the selective Type I error at as the median and the maximum over the cells , by covariance. Figure D.1 summarizes the cells for every test, and Figure D.2 shows the tests that we propose on a magnified scale. With 600 data

(b)
(c)
(d)
— (random Givens) — (Cayley)
Figure C.2: The random Givens kernel and the Cayley random walk with M = 5,000 and L = 2, on null data with compound-symmetric . (a) Quantile-quantile plots of the p-values against the Uniform(0, 1) distribution. (b) Seconds of computing time per p-value. (c) The fraction of steps at which the chain moves.
sets per cell, the 95% Monte Carlo interval for a test with selective Type I error 0.05 is [0.033, 0.067]. Two comparators appear only here. The unknown-scale test of Yun and Barber (2023) divides by the within-cluster sum of squares of the two tested clusters, so it needs no estimate of ; it also assumes and, like , holds the level only under isotropic noise. We computed it, with KmeansInference, on the same null data sets as the other tests. Data thinning (Neufeld et al., 2024a), , splits X into two parts using the sample covariance of X about its overall mean, clusters one part, and applies the classical Hotelling test to the other. Its two parts are independent only when the true is used, but with the sample covariance it is conservative in all of our cells.
Conditional power of k-means. Figure D.3 repeats Figure 4(b) at n = 30 and 50 and Figure D.4 at n = 100 and 200. Figure D.5 shows the other covariances at n = 30, for the tests that control the selective Type I error under them. Conditional power is shown where at least 50 data sets returned two true clusters.
Leiden community detection. Leiden community detection (Traag et al., 2019) on a graph that joins each row to its 15 nearest neighbors has no closed-form selection event, so no existing selective test applies; we report . We used the design of Figure 1: , compound-symmetric with correlation 0.6, and two true groups with means , where , with and . The resolution of the Leiden algorithm was fixed for each
| Method | isotropic | AR(1) | comp. sym. | spiked |
|---|---|---|---|---|
| 1.000 [1.000] | 1.000 [1.000] | 1.000 [1.000] | 1.000 [1.000] | |
| 0.053 [0.064] | 0.048 [0.065] | 0.049 [0.070] | 0.048 [0.064] | |
| 0.052 [0.067] | 0.048 [0.063] | 0.054 [0.068] | 0.043 [0.068] | |
| 0.054 [0.073] | 0.053 [0.067] | 0.048 [0.072] | 0.050 [0.060] | |
| 0.050 [0.073] | 0.053 [0.073] | 0.051 [0.062] | 0.049 [0.073] | |
| 0.058 [0.072] | 0.103 [0.170] | 0.171 [0.693] | 0.122 [0.159] | |
| 0.041 [0.070] | 0.048 [0.070] | 0.048 [0.063] | 0.046 [0.063] | |
| 0.055 [0.070] | 0.049 [0.068] | 0.053 [0.068] | 0.051 [0.071] | |
| 0.056 [0.075] | 0.114 [0.175] | 0.177 [0.714] | 0.125 [0.162] | |
| 0.019 [0.030] | 0.023 [0.030] | 0.025 [0.035] | 0.022 [0.033] |
Table D.1: Selective Type I error at after -means, by covariance: median [maximum] over the cells of Section 5.1.
before the study so that it returns about three clusters, and every pair of clusters with at least members was tested. Figure D.6(a) shows that the null -values of are uniform, with selective Type I error 0.043 at and 0.051 at , and Figure D.6(b) shows that its conditional power is 0.99 at for both dimensions.
Rows that are not Gaussian. Figure D.7 reports the study of Section 5.3. All data sets have , compound-symmetric with correlation 0.5, and no signal. The rows are multivariate with 5 or 10 degrees of freedom. The censored rows are Gaussian rows shifted so that a fraction of each coordinate falls below zero and then censored at zero. For principal components, Gaussian rows with are reduced to their first principal components before -means, and the tests use the component scores.
Computing time. Figure D.8 gives the median time for one -value after -means at . We reran the simulation code of this section on six data sets for each value of , three under the global null and three from the power study, with and . Each -value was computed on one core of an Apple M4 Max processor, with macOS 15.4, R 4.5.2, and the Apple Accelerate linear algebra library restricted to one thread. One value of takes 2 to 6 seconds, and one value of takes 1 to 2.5 seconds. Each of the steps of the path reruns -means once, so the time grows with the cost of one run of the clustering algorithm. The closed-form and the tests of Chen and Witten (2023) take about 0.1 seconds.

Figure D.1: Selective Type I error at after k-means, by covariance structure, on a square-root scale. Each box summarizes one test over the cells , which are drawn as points; the naive test is omitted. The gray band is the 95% Monte Carlo interval for a test of exact level 0.05.

Figure D.2: Selective Type I error at after k-means for the tests that we propose, stratified by (rows) and (columns). Each box summarizes one test over the values of with , which are drawn as points. The gray band is as in Figure D.1.

Figure D.3: Conditional power (29) at after k-means with , stratified by (rows) and (columns), with 95% Wilson intervals.

Figure D.4: As Figure D.3, at n = 100 and 200.

Figure D.5: As Figure D.3, at n = 30 under the AR(1), compound-symmetric, and spiked covariances (rows), for the tests that control the selective Type I error under them.
(a)

(b)
— pnaive — Proposal: p_polar
Figure D.6: Leiden community detection in the design of Figure 1. (a) Quantile-quantile plots of the p-values with one true group ( ), stratified by p. (b) The conditional power (29) of at against , with 95% Wilson intervals.

Figure D.7: Selective Type I error at with rows that are not Gaussian (Section 5.3), after k-means (left) and average-linkage hierarchical clustering (right), on a square-root scale. Each box summarizes one test over the values of (and of for principal components), which are drawn as points. The gray band is as in Figure D.1. There is no reference for principal components.

Figure D.8: Median seconds for one p-value after k-means at n = 200, on one core, by p. The vertical axis is on a log scale.