---
title: Panel Kmeans Clustering
url: https://www.emergentmind.com/topics/panel-kmeans-algorithm
type: topic
---

# Panel Kmeans Clustering

The Panel Kmeans algorithm denotes a class of K-means or least-squares clustering procedures adapted to panel data, in which cross-sectional units are assigned to latent groups using repeated observations over time. In the formulation developed for testing clustered equal predictive ability (C-EPA), the algorithm clusters units on the full \(T\times P\) profiles of transformed loss differentials \(Z_{it}\), so that time-series variation enters the clustering criterion directly rather than being collapsed into time averages; the estimated partition then becomes part of the selection event for valid post-clustering inference [2507.14621].

## 1. Formal setup and clustered objects

In the C-EPA framework, the panel consists of \(N\) units, \(i=1,\ldots,N\), observed over \(T\) periods, \(t=1,\ldots,T\). Two agents or models, \(a=1,2\), produce forecasts of \(Y_{it}\) with loss \(L(\cdot,\cdot)\), and the loss differential is
\[
\Delta L_{it}=L(\widehat Y_{1,it},Y_{it})-L(\widehat Y_{2,it},Y_{it}).
\]
Given a \(P\times 1\) testing function \(H_{it-\tau}\), such as \(1\) for unconditional EPA or \((1,Y_{i,t-1})'\) for conditional EPA, the transformed panel array is
\[
Z_{it}=H_{it-\tau}\Delta L_{it}.
\]
The units \(i\) are clustered into \(K\) groups, and each cluster \(k\) has a \(P\)-dimensional centroid \(\theta_k\) equal to the time-and-unit average of \(Z_{it}\) within that cluster [2507.14621].

The asymptotic structure is built from
\[
Z_{it}=\mu_i^0+V_{it},
\]
where \(V_{it}\) is weakly stationary over \(t\), satisfies standard \(\alpha\)- or \(\phi\)-mixing and moment conditions, and has long-run variance
\[
\Omega_i=\sum_j E(V_{it}V'_{i,t-j})
\]
that is positive definite. Cross-sectional dependence is allowed and can be strong, of factor-type, or weak, of spatial-type; a scaling parameter \(\epsilon\in[1/2,1]\) governs CLT normalization in the presence of cross-sectional dependence. Cluster sizes are asymptotically non-negligible, \(|C_k|/N\to\pi_k\in(0,1)\), and under alternatives the clusters are separated in the sense that \(\|\theta_k^0-\theta_g^0\|^2\ge C_{kg}>0\). No independence across units is required, and time-series dependence is generic.

This setup makes clear that the clustered objects are not the raw outcomes \(Y_{it}\) themselves, but the transformed loss-differential profiles \(Z_{it}\). A recurring misconception is to view Panel Kmeans as ordinary K-means applied to unit-level averages. In the C-EPA construction, the operative data are full trajectories indexed by \(t\), and the inferential target is clusterwise predictive ability rather than generic geometric partitioning.

## 2. Objective function, metric, and Lloyd-type iteration

Using the full \(T\times P\) profiles \(Z_{it}\), the Panel Kmeans estimator solves a least-squares clustering problem with Euclidean distance accumulated over time. Its centroid update is
\[
\hat\theta_k
=
\frac{1}{|\widehat{\mathcal C}_k|T}
\sum_{i\in\widehat{\mathcal C}_k}\sum_{t=1}^T Z_{it},
\]
and the assignment step for each unit \(i\) is
\[
\hat k_i
=
\arg\min_{k\in\{1,\ldots,K\}}
\sum_{t=1}^T \|Z_{it}-\hat\theta_k\|^2.
\]
The distance is the standard squared Euclidean norm in \(\mathbb R^P\), with equal weights across \(t=1,\ldots,T\) [2507.14621].

The algorithm is a Panel Lloyd iteration. Initialization randomly assigns each unit to one of \(K\) clusters, not via distance-based Kmeans++, and computes initial centroids as time-and-unit averages in each cluster. The procedure then alternates between reassignment and centroid recomputation until assignments stabilize, changes fall below a threshold, or a maximum iteration cap is reached. Per iteration, the assignment step has complexity \(O(NKTP)\), the updates have complexity \(O(NTP)\), and with \(M\) iterations and \(R\) random starts the total complexity is approximately \(O(RMNKTP)\).

Its distinguishing feature relative to classical K-means is explicit use of time-series variation. Classical K-means on time averages would cluster \(\bar Z_i=T^{-1}\sum_t Z_{it}\) by minimizing \(\sum_i\|\bar Z_i-\mu_{c_i}\|^2\). Panel Kmeans instead minimizes \(\sum_i\sum_t\|Z_{it}-\theta_{c_i}\|^2\) with \(\theta_k\) equal to the grand average over time and units in cluster \(k\). If \(T=1\), the method reduces to standard K-means on the \(P\)-dimensional cross section \(\{Z_{i1}\}\). If time is collapsed ex ante by using \(\bar Z_i\), the objective becomes standard K-means on \(\bar Z_i\), but that ignores the time variation the proposed algorithm exploits.

## 3. Preprocessing and selection of the number of clusters

Implementation begins with construction of \(Z_{it}\), which requires choosing the testing function \(H_{it-\tau}\) and computing \(\Delta L_{it}\) from forecast errors and the chosen loss, such as square or absolute loss. When \(P>1\), scaling each coordinate of \(Z_{it}\), for example by the overall standard deviation, is recommended to avoid dominance by high-variance components. Demeaning over time is not required because the centroid already averages across time and units. If strong drifts or seasonality are present, pre-detrending may help interpretability, but it is not part of the estimator’s theory. Missing data require equal-length series or consistent handling through imputation, use of common sample periods, or averaging over observed \(t\) with rescaling for comparability. The core algorithm uses squared Euclidean loss; robust alternatives such as \(L_1\) or Huber loss are not analyzed, and adopting them would change the selection-region geometry and require re-deriving selective inference [2507.14621].

For unknown \(K\), the proposed information criterion is
\[
IC(K)
=
\log\!\left[
\det\!\left(
\frac{1}{NT}\sum_{i=1}^N\sum_{t=1}^T
\widehat V_{it}(K)\widehat V'_{it}(K)
\right)
\right]
+
(KP+N)\frac{\varsigma\log(NT)}{NT},
\]
where
\[
\widehat V_{it}(K)=Z_{it}-\hat\theta_{K,\hat k_i},
\qquad
\widehat K_{IC}
=
\arg\min_{K\in\{2,\ldots,K_{\max}\}} IC(K).
\]
The tuning constant satisfies \(\varsigma\in[1.5,3]\), and the simulations use \(1.5\). A key theoretical point is that conditioning on the final clustering \(\widehat{\mathcal C}\) implicitly conditions on \(\widehat K_{IC}\), so selecting \(K\) by this criterion before testing does not require further conditioning for validity within the selective conditional inference framework. A consistent cross-validation option also exists through time-split training and validation, although it can be computationally heavier; in the empirical section, cross-validation often selected \(K=2\).

These choices affect both clustering quality and inference. The paper’s guidance is therefore not merely computational. It is part of the inferential design, because preprocessing, dimension scaling, and cluster-count selection determine the selection event on which valid testing is conditioned.

## 4. Selective conditional inference after clustering

The C-EPA null is
\[
\mathcal H_0:
\frac{1}{|\mathcal C_k|}
\sum_{i\in\mathcal C_k}
\mathbb E(\Delta L_{it}\mid\mathcal F_{t-\tau})=0
\quad\text{for each }k=1,\ldots,K.
\]
After transformation by the testing function, this becomes
\[
\theta_k^0(\mathcal C)
=
\frac{1}{|\mathcal C_k|}
\sum_{i\in\mathcal C_k}\mu_i^0
=
0
\quad\text{for all }k.
\]
The hypothesis decomposes into homogeneity across clusters, \(\theta_k^0(\mathcal C)=\theta_g^0(\mathcal C)\) for all \(k\neq g\), and overall EPA,
\[
\frac{1}{N}\sum_{k=1}^K |\mathcal C_k|\,\theta_k^0(\mathcal C)=0.
\]
The overall EPA parameter does not depend on the partition [2507.14621].

For pairwise homogeneity, the method uses the square root of a Wald statistic,
\[
D_{k,g}^2(\widehat{\mathcal C})
=
T\,
\big[\hat\theta_k(\widehat{\mathcal C})-\hat\theta_g(\widehat{\mathcal C})\big]'
\widehat\Sigma_{k,g}^{-1}(\widehat{\mathcal C})
\big[\hat\theta_k(\widehat{\mathcal C})-\hat\theta_g(\widehat{\mathcal C})\big],
\]
where
\[
\widehat\Sigma_{k,g}(\widehat{\mathcal C})
=
\widehat\omega_{k,k}(\widehat{\mathcal C})
+
\widehat\omega_{g,g}(\widehat{\mathcal C})
-
2\widehat\omega_{k,g}(\widehat{\mathcal C}).
\]
Under known clusters and regularity conditions, \(D_{k,g}\overset d\to\chi_P\). After clustering, however, valid critical values require conditioning on the estimated clusters. Conditional on the entire sequence of cluster assignments produced by the Panel Kmeans iterations and on nuisance directions, \(D_{k,g}\) is asymptotically \(\chi_P\) truncated to a data-dependent set. The perturbation path \(z(\phi)\) varies the component of the data along the estimated direction of cluster separation while holding the orthogonal component fixed, and the truncation set
\[
\mathcal T
=
\{\phi\in\mathbb R_{\ge 0}:
k_i^{(m)}[z(\phi)]=k_i^{(m)}(z)
\text{ for all iterations }m
\text{ and all units }i\}
\]
is determined by the assignment inequalities. In the classical point-clustering case this structure is polyhedral; with Panel Kmeans, because assignment uses sums of squared distances over time, the inequalities are quadratic in \(\phi\), so \(\mathcal T\) is a finite union of intervals.

Selective \(p\)-values are obtained from the survival function of a truncated \(\chi_P\) distribution. Homogeneity across \(K\) clusters is then tested by merging the \(n_p=K(K-1)/2\) pairwise \(p\)-values with the M-family generalized mean
\[
F_{homo,r}
=
\frac{r}{r+1}\,
n_p^{1+1/r}
\left\{
\frac{1}{n_p}
\sum_{k<g}
\big[p(D_{k,g}(\widehat{\mathcal C}))\big]^r
\right\}^{1/r}
\wedge 1,
\quad r\in[-\infty,-1),
\]
which is valid under arbitrary dependence. Overall EPA is tested with
\[
W_{oepa}
=
\frac{B-P+1}{PB}\,
T\,\bar Z_o'\widehat\Omega_o^{-1}\bar Z_o,
\]
using an orthonormal-series long-run variance estimator robust to time dependence and strong cross-sectional dependence, with fixed-\(B\) reference distribution \(F_{P,B-P+1}\). The final C-EPA test merges the homogeneity and O-EPA \(p\)-values through
\[
F_{SI,r}
=
\frac{r}{r+1}\,
(n_p+1)^{1+1/r}
\left\{
\frac{1}{n_p+1}
\sum_{k<g}\big[p(D_{k,g}(\widehat{\mathcal C}))\big]^r
+
\frac{1}{n_p+1}\big[p(W_{oepa})\big]^r
\right\}^{1/r}
\wedge 1.
\]

The inferential consequence is central. Naive post-clustering Wald tests severely over-reject, with size approximately \(1.00\) in all Monte Carlo designs. By contrast, the selective-inference C-EPA procedure controls size accurately for \(N\in\{80,120,160\}\) and \(T\in\{20,50,100,200\}\), with rejection rates near the nominal \(5\%\). Split-sample tests generally control size, but they can over-reject in the presence of structural breaks because training and testing partitions fail to account for time variation in cluster centers.

## 5. Related panel K-means formulations

The term “Panel Kmeans” is not restricted to predictive-ability testing. In the supplied literature it also denotes least-squares clustering procedures for grouped intercepts, grouped slopes, latent-group IV models, and panel models with small groups [2008.04708] [2405.08687] [2508.15408].

| Setting | Core criterion | Distinctive issue |
|---|---|---|
| Predictive-ability panels | Cluster on full \(T\times P\) profiles \(Z_{it}=H_{it-\tau}\Delta L_{it}\) | Post-clustering inference requires selective conditioning |
| Grouped-intercept panels | Minimize \(Q_{N,T}(\mathbf g,\boldsymbol\mu)=\frac{1}{NT}\sum_{i,t}(y_{it}-\mu_{g_i})^2\) | Root-\(NT\) estimation can hold with some asymptotic misclassification |
| Endogenous-regressor panels | Second-stage least squares on predicted regressors \(\hat x_{it}\) | Direct K-means on the GMM objective does not yield unique estimates |
| Small-group panels | Least-squares clustering with or without grouped fixed effects | Standard information criteria can miss asymptotically negligible groups |

In grouped-intercept long panels, the estimator alternates between within-cluster averaging and reassignment by unit-level residual sums of squares. Under long-panel asymptotics, sub-exponential tails, group separation, and a rate condition controlling the share and variance of units outside the “easy-to-classify” set, the group-specific means can be estimated at the parametric root-\(NT\) rate even if some units are asymptotically misclassified and error variances diverge with \(T\). This result makes precise that uniform membership recovery is not always necessary for first-order asymptotic normality of the group parameters.

In latent-group IV models, the literature identifies a different failure mode. Direct application of K-means to pooled or groupwise GMM criteria is not well defined in the just-identified case and can fail to identify the true grouping in overidentified settings. The proposed remedy is a two-stage structure: first regress endogenous regressors on instruments, using either a homogeneous first stage, a grouped first stage (TGFE), or a unit-specific first stage (UGFE); then apply K-means or grouped fixed-effects least squares to the regression of \(y_{it}\) on predicted regressors \(\hat x_{it}\). This establishes a panel K-means route for endogenous-regressor settings without relying on naive K-means-GMM minimization.

In panels with small groups, the principal issue is not endogeneity or post-selection inference but group-size asymptotics. When true group sizes satisfy \(N_k^0=\tau_k N^{\alpha_k}\) with some \(\alpha_k<1\), longer \(T\) is required as the smallest groups become smaller. Earlier information criteria can then be inconsistent or perform poorly: Bai–Ng penalties may underestimate \(K\) by missing small groups, whereas BIC-type penalties may overfit in finite samples. Modified information criteria, MIC1 and MIC2, are proposed precisely for this regime.

## 6. Empirical use, implementation, and interpretation

A minimal implementation in the C-EPA setting takes as inputs the \(P\)-dimensional arrays \(Z_{it}\), a chosen \(K\) or a grid for \(K\), a number of random restarts \(R\), and a maximum iteration count \(M\). One run consists of random assignment of units to clusters, centroid computation by time-and-unit averaging, repeated reassignment by minimizing \(\sum_t\|Z_{it}-\hat\theta_k\|^2\), and retention of the solution that minimizes the objective over \(R\) random starts. The paper reports values such as \(R=10\)–\(100\) in simulations, \(R=10{,}000\) in the application, and \(M=100\). For selective inference, long-run variance estimation uses an orthonormal-series estimator,
\[
\widehat\Omega(\widehat{\mathcal C})
=
\frac{1}{B}\sum_{j=1}^B
\widehat\Lambda_j(\widehat{\mathcal C})
\widehat\Lambda_j'(\widehat{\mathcal C}),
\]
with practical choice
\[
B=\min(\lfloor P\,T^{2/3}\rfloor,T).
\]
Available software includes the R packages **clusteredEPA**, for EPA testing in panels with latent clusters including selective-inference and split-sample procedures, and **PanelKmeansInference**, for post-clustering inference for coefficient homogeneity across Panel Kmeans clusters; replication materials are provided at `https://github.com/akoguzhan/` [2507.14621].

The empirical application concerns exchange-rate forecasting. The data comprise \(N=131\) bilateral exchange rates and approximately \(T=238\) forecast periods with recursive window \(r=60\). Models compared to AR(1) include AR(p)-BIC, Elastic Net, XGBoost in a data-poor specification, and SVM and Random Forest in data-rich specifications. Loss-differential summaries show substantial heterogeneity, and XGBoost often exhibits the largest average gain, corresponding to a negative mean loss differential. In formal testing, overall EPA frequently rejects, homogeneity often fails, especially when conditioning on lagged targets or macro regimes, cross-validation frequently selects \(K=2\), and the selective-inference C-EPA procedure detects heterogeneous gains robustly.

Several interpretive cautions follow directly from the literature. First, Panel Kmeans is not a synonym for clustering unit averages; in its predictive-ability form it uses entire time-series profiles. Second, naive post-clustering Wald inference is invalid because cluster membership is estimated from the same data. Third, robust alternatives to squared Euclidean loss are not covered by the selective-inference theory. A plausible implication is that extensions to robust losses, irregular missingness, or alternative assignment metrics are not merely computational variants; they alter the selection event and therefore the reference distribution used for valid post-clustering testing.

Source: https://www.emergentmind.com/topics/panel-kmeans-algorithm