Panel Kmeans Clustering
- Panel Kmeans algorithm is a least-squares clustering method for panel data that uses full time-series profiles of transformed loss differentials rather than collapsing data into averages.
- It employs a Lloyd-type iteration that repeatedly assigns units to clusters based on minimizing accumulated Euclidean distances over time, ensuring valid post-clustering inference.
- Key considerations include preprocessing, scaling, and selecting the number of clusters to maintain robust predictive-ability testing and accurate measurement of group heterogeneity.
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 profiles of transformed loss differentials , 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 (Akgun et al., 19 Jul 2025).
1. Formal setup and clustered objects
In the C-EPA framework, the panel consists of units, , observed over periods, . Two agents or models, , produce forecasts of with loss , and the loss differential is
Given a 0 testing function 1, such as 2 for unconditional EPA or 3 for conditional EPA, the transformed panel array is
4
The units 5 are clustered into 6 groups, and each cluster 7 has a 8-dimensional centroid 9 equal to the time-and-unit average of 0 within that cluster (Akgun et al., 19 Jul 2025).
The asymptotic structure is built from
1
where 2 is weakly stationary over 3, satisfies standard 4- or 5-mixing and moment conditions, and has long-run variance
6
that is positive definite. Cross-sectional dependence is allowed and can be strong, of factor-type, or weak, of spatial-type; a scaling parameter 7 governs CLT normalization in the presence of cross-sectional dependence. Cluster sizes are asymptotically non-negligible, 8, and under alternatives the clusters are separated in the sense that 9. 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 0 themselves, but the transformed loss-differential profiles 1. 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 2, and the inferential target is clusterwise predictive ability rather than generic geometric partitioning.
2. Objective function, metric, and Lloyd-type iteration
Using the full 3 profiles 4, the Panel Kmeans estimator solves a least-squares clustering problem with Euclidean distance accumulated over time. Its centroid update is
5
and the assignment step for each unit 6 is
7
The distance is the standard squared Euclidean norm in 8, with equal weights across 9 (Akgun et al., 19 Jul 2025).
The algorithm is a Panel Lloyd iteration. Initialization randomly assigns each unit to one of 0 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 1, the updates have complexity 2, and with 3 iterations and 4 random starts the total complexity is approximately 5.
Its distinguishing feature relative to classical K-means is explicit use of time-series variation. Classical K-means on time averages would cluster 6 by minimizing 7. Panel Kmeans instead minimizes 8 with 9 equal to the grand average over time and units in cluster 0. If 1, the method reduces to standard K-means on the 2-dimensional cross section 3. If time is collapsed ex ante by using 4, the objective becomes standard K-means on 5, but that ignores the time variation the proposed algorithm exploits.
3. Preprocessing and selection of the number of clusters
Implementation begins with construction of 6, which requires choosing the testing function 7 and computing 8 from forecast errors and the chosen loss, such as square or absolute loss. When 9, scaling each coordinate of 0, 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 1 with rescaling for comparability. The core algorithm uses squared Euclidean loss; robust alternatives such as 2 or Huber loss are not analyzed, and adopting them would change the selection-region geometry and require re-deriving selective inference (Akgun et al., 19 Jul 2025).
For unknown 3, the proposed information criterion is
4
where
5
The tuning constant satisfies 6, and the simulations use 7. A key theoretical point is that conditioning on the final clustering 8 implicitly conditions on 9, so selecting 0 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 1.
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
2
After transformation by the testing function, this becomes
3
The hypothesis decomposes into homogeneity across clusters, 4 for all 5, and overall EPA,
6
The overall EPA parameter does not depend on the partition (Akgun et al., 19 Jul 2025).
For pairwise homogeneity, the method uses the square root of a Wald statistic,
7
where
8
Under known clusters and regularity conditions, 9. 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, 0 is asymptotically 1 truncated to a data-dependent set. The perturbation path 2 varies the component of the data along the estimated direction of cluster separation while holding the orthogonal component fixed, and the truncation set
3
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 4, so 5 is a finite union of intervals.
Selective 6-values are obtained from the survival function of a truncated 7 distribution. Homogeneity across 8 clusters is then tested by merging the 9 pairwise 0-values with the M-family generalized mean
1
which is valid under arbitrary dependence. Overall EPA is tested with
2
using an orthonormal-series long-run variance estimator robust to time dependence and strong cross-sectional dependence, with fixed-3 reference distribution 4. The final C-EPA test merges the homogeneity and O-EPA 5-values through
6
The inferential consequence is central. Naive post-clustering Wald tests severely over-reject, with size approximately 7 in all Monte Carlo designs. By contrast, the selective-inference C-EPA procedure controls size accurately for 8 and 9, with rejection rates near the nominal 00. 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 (Dzemski et al., 2020, Choi et al., 2024, Nishi, 21 Aug 2025).
| Setting | Core criterion | Distinctive issue |
|---|---|---|
| Predictive-ability panels | Cluster on full 01 profiles 02 | Post-clustering inference requires selective conditioning |
| Grouped-intercept panels | Minimize 03 | Root-04 estimation can hold with some asymptotic misclassification |
| Endogenous-regressor panels | Second-stage least squares on predicted regressors 05 | 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-06 rate even if some units are asymptotically misclassified and error variances diverge with 07. 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 08 on predicted regressors 09. 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 10 with some 11, longer 12 is required as the smallest groups become smaller. Earlier information criteria can then be inconsistent or perform poorly: Bai–Ng penalties may underestimate 13 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 14-dimensional arrays 15, a chosen 16 or a grid for 17, a number of random restarts 18, and a maximum iteration count 19. One run consists of random assignment of units to clusters, centroid computation by time-and-unit averaging, repeated reassignment by minimizing 20, and retention of the solution that minimizes the objective over 21 random starts. The paper reports values such as 22–23 in simulations, 24 in the application, and 25. For selective inference, long-run variance estimation uses an orthonormal-series estimator,
26
with practical choice
27
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/ (Akgun et al., 19 Jul 2025).
The empirical application concerns exchange-rate forecasting. The data comprise 28 bilateral exchange rates and approximately 29 forecast periods with recursive window 30. 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 31, 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.