KMeans
clustering
ValueError
n_samples
Python error

KMeans clustering - Value error n_samples1 should be n_cluster

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

The error n_samples=1 should be >= n_clusters means KMeans thinks your dataset contains only one sample, but you asked for more than one cluster. The fix is not usually "tune KMeans differently." It is usually "inspect the shape of the data you passed in." In many cases the real bug is that a one-dimensional array was reshaped incorrectly, or earlier preprocessing collapsed the dataset down to one row.

Why KMeans Requires Enough Samples

KMeans needs at least one sample per cluster. If you ask for k=3, the algorithm must be able to place three centroids among at least three samples.

This fails:

python
1from sklearn.cluster import KMeans
2import numpy as np
3
4X = np.array([[10.0, 20.0]])
5
6model = KMeans(n_clusters=3, random_state=42)
7model.fit(X)

X has shape (1, 2):

  • '1 sample'
  • '2 features'

Since there is only one sample, asking for three clusters is impossible.

The Most Common Cause: Wrong Array Shape

A classic mistake is intending to create many one-feature samples but accidentally creating one sample with many features.

Example:

python
1import numpy as np
2
3X = np.array([1, 2, 3, 4])
4print(X.shape)

This has shape (4,), which is not a valid 2D input for scikit-learn clustering as-is.

Developers often then reshape it incorrectly:

python
X = X.reshape(1, -1)
print(X.shape)  # (1, 4)

Now KMeans sees:

  • '1 sample'
  • '4 features'

If what you really meant was four samples with one feature each, the correct reshape is:

python
X = X.reshape(-1, 1)
print(X.shape)  # (4, 1)

That one change fixes many instances of this error.

Correct Example

python
1from sklearn.cluster import KMeans
2import numpy as np
3
4X = np.array([1, 2, 3, 10, 11, 12]).reshape(-1, 1)
5
6model = KMeans(n_clusters=2, random_state=42, n_init="auto")
7labels = model.fit_predict(X)
8
9print(labels)
10print(model.cluster_centers_)

Now the data has:

  • '6 samples'
  • '1 feature'

and KMeans can form two clusters.

Check Your Data After Filtering

Another common cause is preprocessing that leaves only one row.

For example:

python
filtered = df[df["country"] == "CA"][["score"]].dropna()
print(filtered.shape)

If filtered.shape becomes (1, 1), then asking for multiple clusters will fail.

This often happens when:

  • filtering conditions are too narrow
  • missing values are dropped aggressively
  • duplicate removal removes most rows
  • train/test subsetting produces a tiny subset

So the right debugging move is usually:

python
print(X.shape)
print(X[:5])

before blaming the clustering algorithm.

Reduce n_clusters or Increase Samples

Once you understand the shape, the rule is simple:

  • if you only have one sample, use at most one cluster
  • if you need multiple clusters, provide more samples

This is not just a library restriction. It is a mathematical requirement of the clustering problem.

If your pipeline legitimately produces a tiny sample count, KMeans may not be the right tool for that stage.

Watch Out for Text and Embedding Pipelines

This error also appears in NLP or embedding workflows where one long vector is mistaken for a dataset.

For example, an embedding of shape (768,) is:

  • one sample
  • '768 features'

If you reshape it to (1, 768) and ask for several clusters, the error is expected.

If you intended to cluster several embeddings, the input should look more like:

text
(n_samples, embedding_dim)

not one row with many features.

A Practical Debug Checklist

Before fitting KMeans, verify:

  1. X is two-dimensional
  2. the first dimension is the number of samples
  3. n_samples >= n_clusters
  4. earlier filtering did not collapse the dataset

Example:

python
print("shape:", X.shape)
print("n_clusters:", 3)

This tiny check prevents a lot of wasted time.

Common Pitfalls

The biggest mistake is reshaping data to (1, -1) when the intent was (-1, 1). That flips samples and features.

Another issue is filtering or cleaning the dataset so aggressively that only one row remains before clustering.

Developers also sometimes treat a single embedding vector as if it were a multi-sample dataset. KMeans clusters samples, not individual feature dimensions.

Finally, lowering n_clusters may remove the error, but it does not fix the underlying data-shape mistake if the input still represents the wrong conceptual dataset.

Summary

  • The error means KMeans sees fewer samples than the number of clusters you requested.
  • Most often, the root cause is incorrect array shape rather than a KMeans bug.
  • Check whether you accidentally turned many samples into one sample with many features.
  • Print X.shape after filtering and reshaping before fitting the model.
  • Fix the sample count or reduce n_clusters so that n_samples >= n_clusters.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.