TheAlgorithms/Java · error · IllegalArgumentException
sample length must match training feature count
Error message
sample length must match training feature count
What it means
MultinomialNaiveBayesClassifier.predict requires the sample vector length to match numFeatures (set during fit from features[0].length), because it computes score += sample[j] * logLikelihood[j] iterating j over [0, numFeatures). A mismatch would throw ArrayIndexOutOfBoundsException or compute a meaningless score.
Source
Thrown at src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java:109
for (int j = 0; j < numFeatures; j++) {
logLikelihood[j] = Math.log((sums[j] + alpha) / denom);
}
logLikelihoods.put(label, logLikelihood);
}
}
/**
* Predicts the most likely class for a single sample.
*
* @param sample feature vector of non-negative counts
* @return the predicted class label
*/
public int predict(double[] sample) {
if (logPriors.isEmpty()) {
throw new IllegalStateException("classifier has not been fitted");
}
if (sample.length != numFeatures) {
throw new IllegalArgumentException("sample length must match training feature count");
}
int bestLabel = -1;
double bestScore = Double.NEGATIVE_INFINITY;
for (Map.Entry<Integer, double[]> entry : logLikelihoods.entrySet()) {
int label = entry.getKey();
double[] logLikelihood = entry.getValue();
double score = logPriors.getOrDefault(label, Double.NEGATIVE_INFINITY);
for (int j = 0; j < numFeatures; j++) {
score += sample[j] * logLikelihood[j];
}
if (score > bestScore) {
bestScore = score;
bestLabel = label;
}
}
return bestLabel;View on GitHub (pinned to fdfb9a395b)
Solutions
- Ensure the same feature extraction/featurizer is used at train and predict time.
- Check sample.length == expectedNumFeatures before calling predict.
- Store numFeatures alongside the model and validate inference inputs against it.
Example fix
// before (trained on 4 features)
clf.predict(new double[]{1.0, 2.0, 3.0}); // length 3
// after
clf.predict(new double[]{1.0, 2.0, 3.0, 1.0}); // length 4 matches training Defensive patterns
Strategy: validation
Validate before calling
if (sample.length != expectedNumFeatures) {
throw new IllegalArgumentException(
"sample length " + sample.length + " != trained " + expectedNumFeatures);
}
classifier.predict(sample); Prevention
- Use the identical featurizer/vectorizer at train and predict time.
- Persist numFeatures with the model and validate inference inputs against it.
- Add an integration test that trains and predicts with the same feature pipeline.
When it happens
Trigger: Calling predict(sample) where sample.length != the feature count the classifier was trained on. E.g. trained on 4-feature samples but predicting with a 3-element sample.
Common situations: Feature extraction changed between training and inference (added/removed a feature), a different tokenizer/vectorizer used at predict time, or a sample built with the wrong dimensionality.
Related errors
- alpha must be greater than 0
- features and labels must be non-empty and of equal length
- X and Y must be non-null, non-empty, and of the same length.
- classifier has not been fitted
- Input cannot be negative
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/61e9a6e8b772526f.
Report an issue: GitHub.