{"record":{"id":"61e9a6e8b772526f","repo":"TheAlgorithms/Java","slug":"sample-length-must-match-training-feature-count","errorCode":null,"errorMessage":"sample length must match training feature count","messagePattern":"sample length must match training feature count","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java","lineNumber":109,"sourceCode":"            for (int j = 0; j < numFeatures; j++) {\n                logLikelihood[j] = Math.log((sums[j] + alpha) / denom);\n            }\n            logLikelihoods.put(label, logLikelihood);\n        }\n    }\n\n    /**\n     * Predicts the most likely class for a single sample.\n     *\n     * @param sample feature vector of non-negative counts\n     * @return the predicted class label\n     */\n    public int predict(double[] sample) {\n        if (logPriors.isEmpty()) {\n            throw new IllegalStateException(\"classifier has not been fitted\");\n        }\n        if (sample.length != numFeatures) {\n            throw new IllegalArgumentException(\"sample length must match training feature count\");\n        }\n\n        int bestLabel = -1;\n        double bestScore = Double.NEGATIVE_INFINITY;\n\n        for (Map.Entry<Integer, double[]> entry : logLikelihoods.entrySet()) {\n            int label = entry.getKey();\n            double[] logLikelihood = entry.getValue();\n            double score = logPriors.getOrDefault(label, Double.NEGATIVE_INFINITY);\n            for (int j = 0; j < numFeatures; j++) {\n                score += sample[j] * logLikelihood[j];\n            }\n            if (score > bestScore) {\n                bestScore = score;\n                bestLabel = label;\n            }\n        }\n        return bestLabel;","sourceCodeStart":91,"sourceCodeEnd":127,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java#L91-L127","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before (trained on 4 features)\nclf.predict(new double[]{1.0, 2.0, 3.0}); // length 3\n\n// after\nclf.predict(new double[]{1.0, 2.0, 3.0, 1.0}); // length 4 matches training","handlingStrategy":"validation","validationCode":"if (sample.length != expectedNumFeatures) {\n    throw new IllegalArgumentException(\n        \"sample length \" + sample.length + \" != trained \" + expectedNumFeatures);\n}\nclassifier.predict(sample);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["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."],"tags":["machine-learning","validation","dimensionality-mismatch","naive-bayes","feature-vector"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}