TheAlgorithms/Java · error · IllegalStateException

classifier has not been fitted

Error message

classifier has not been fitted

What it means

MultinomialNaiveBayesClassifier.predict throws IllegalStateException (unchecked) when logPriors is empty, which is the state after construction but before fit() is called. predict relies on fitted log-priors and log-likelihoods; with none, there is no model to evaluate. This is a lifecycle/state error, not an argument error.

Source

Thrown at src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java:106

            double denom = total + alpha * numFeatures;
            double[] logLikelihood = new double[numFeatures];
            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;

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Always call fit(features, labels) before any predict call.
  2. If the model is optional, track a fitted flag and skip prediction when not fitted.
  3. When loading a pre-trained model, rehydrate the priors/likelihoods or re-fit, rather than predicting on a fresh instance.

Example fix

// before
var clf = new MultinomialNaiveBayesClassifier();
int label = clf.predict(sample); // not fitted

// after
var clf = new MultinomialNaiveBayesClassifier();
clf.fit(trainFeatures, trainLabels);
int label = clf.predict(sample);
Defensive patterns

Strategy: validation

Validate before calling

if (!isFitted) {
    throw new IllegalStateException("classifier not fitted; call fit first");
}
classifier.predict(sample);

Prevention

When it happens

Trigger: Calling predict(sample) on a classifier instance that was never fit — i.e. new MultinomialNaiveBayesClassifier() followed directly by predict without an intervening fit().

Common situations: Forgetting to call fit in a training/serving pipeline, a model-loading routine that failed silently and left the classifier unfitted, or unit tests that construct and predict without training.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/5b7322508e8d81c9. Report an issue: GitHub.