TheAlgorithms/Java · error · IllegalArgumentException

features and labels must be non-empty and of equal length

Error message

features and labels must be non-empty and of equal length

What it means

MultinomialNaiveBayesClassifier.fit requires a non-empty feature matrix whose row count equals the labels array length — each training sample needs a label. An empty matrix or a length mismatch means gradient/counts aggregation cannot proceed and would divide by zero or index out of bounds. Note: features null is not explicitly checked here (only features.length), so a null features array throws NPE rather than this message.

Source

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

        this.logPriors = new HashMap<>();
        this.logLikelihoods = new HashMap<>();
    }

    /** Constructs a classifier using the standard Laplace smoothing constant of 1.0. */
    public MultinomialNaiveBayesClassifier() {
        this(1.0);
    }

    /**
     * Fits the classifier on the given feature matrix and labels.
     *
     * @param features training samples, each row a vector of non-negative
     *                 feature counts
     * @param labels   class label for each row of {@code features}
     */
    public void fit(double[][] features, int[] labels) {
        if (features.length == 0 || features.length != labels.length) {
            throw new IllegalArgumentException("features and labels must be non-empty and of equal length");
        }
        logPriors.clear();
        logLikelihoods.clear();
        numFeatures = features[0].length;

        Map<Integer, Integer> classCounts = new HashMap<>();
        Map<Integer, double[]> featureSums = new HashMap<>();
        Map<Integer, Double> totalFeatureCount = new HashMap<>();

        for (int i = 0; i < features.length; i++) {
            int label = labels[i];
            classCounts.merge(label, 1, Integer::sum);
            double[] sums = featureSums.computeIfAbsent(label, k -> new double[numFeatures]);
            double total = totalFeatureCount.getOrDefault(label, 0.0);
            for (int j = 0; j < numFeatures; j++) {
                sums[j] += features[i][j];
                total += features[i][j];
            }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check features != null && features.length > 0 && features.length == labels.length before calling fit.
  2. If the training set is empty, skip fitting and report the issue upstream.
  3. When loading data, pair features and labels atomically per row to keep lengths in sync.

Example fix

// before
classifier.fit(features, labels); // features.length=0

// after
if (features == null || features.length == 0 || features.length != labels.length) {
    throw new IllegalArgumentException("invalid training data");
}
classifier.fit(features, labels);
Defensive patterns

Strategy: validation

Validate before calling

if (features == null || features.length == 0 || features.length != labels.length) {
    throw new IllegalArgumentException("features/labels must be non-empty and equal-length");
}
classifier.fit(features, labels);

Prevention

When it happens

Trigger: Calling fit(new double[0][], labels), fit(features, labels) where features.length != labels.length, or passing a non-null but empty feature matrix.

Common situations: Empty training set from a filtered/queried dataset, mismatched lengths because a row was dropped from features but not labels (or vice versa), or a data pipeline that produces features and labels from different sources.

Related errors


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