Cross-validation, overfitting, and clustering

scikit-learn 1.9.1

Estimate performance across splits and learn how K-means groups unlabeled rows.

On this page

Validate on several folds

Cross-validation repeatedly fits on training folds and scores on their held-out validation folds. Use it on training data to choose settings, then evaluate once on the final test set. A gap between high training scores and lower validation scores can indicate overfitting.

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score

X = [[1], [2], [3], [4], [5], [6]]
y = [3, 5, 7, 9, 11, 13]
scores = cross_val_score(LinearRegression(), X, y, cv=3, scoring="neg_mean_absolute_error")
print([round(-float(score) + 0.0, 6) for score in scores])
Example output
[0.0, 0.0, 0.0]

Group rows without labels

K-means assigns points to centers by Euclidean distance and seeks low within-cluster squared distance. Scale features when their units would otherwise dominate the distances. Cluster label numbers can change without changing the grouping.

from sklearn.cluster import KMeans

points = [[1], [2], [3], [9], [10], [11]]
model = KMeans(n_clusters=2, n_init=10, random_state=42).fit(points)
print(sorted(model.cluster_centers_.ravel().tolist()))
Example output
[2.0, 10.0]

Official references