{"record":{"id":"2678ce3599f478c7","repo":"TheAlgorithms/Java","slug":"features-and-labels-must-be-non-empty-and-of-equal","errorCode":null,"errorMessage":"features and labels must be non-empty and of equal length","messagePattern":"features and labels must be non-empty and of equal length","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java","lineNumber":58,"sourceCode":"        this.logPriors = new HashMap<>();\n        this.logLikelihoods = new HashMap<>();\n    }\n\n    /** Constructs a classifier using the standard Laplace smoothing constant of 1.0. */\n    public MultinomialNaiveBayesClassifier() {\n        this(1.0);\n    }\n\n    /**\n     * Fits the classifier on the given feature matrix and labels.\n     *\n     * @param features training samples, each row a vector of non-negative\n     *                 feature counts\n     * @param labels   class label for each row of {@code features}\n     */\n    public void fit(double[][] features, int[] labels) {\n        if (features.length == 0 || features.length != labels.length) {\n            throw new IllegalArgumentException(\"features and labels must be non-empty and of equal length\");\n        }\n        logPriors.clear();\n        logLikelihoods.clear();\n        numFeatures = features[0].length;\n\n        Map<Integer, Integer> classCounts = new HashMap<>();\n        Map<Integer, double[]> featureSums = new HashMap<>();\n        Map<Integer, Double> totalFeatureCount = new HashMap<>();\n\n        for (int i = 0; i < features.length; i++) {\n            int label = labels[i];\n            classCounts.merge(label, 1, Integer::sum);\n            double[] sums = featureSums.computeIfAbsent(label, k -> new double[numFeatures]);\n            double total = totalFeatureCount.getOrDefault(label, 0.0);\n            for (int j = 0; j < numFeatures; j++) {\n                sums[j] += features[i][j];\n                total += features[i][j];\n            }","sourceCodeStart":40,"sourceCodeEnd":76,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java#L40-L76","documentation":"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.","triggerScenarios":"Calling fit(new double[0][], labels), fit(features, labels) where features.length != labels.length, or passing a non-null but empty feature matrix.","commonSituations":"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.","solutions":["Check features != null && features.length > 0 && features.length == labels.length before calling fit.","If the training set is empty, skip fitting and report the issue upstream.","When loading data, pair features and labels atomically per row to keep lengths in sync."],"exampleFix":"// before\nclassifier.fit(features, labels); // features.length=0\n\n// after\nif (features == null || features.length == 0 || features.length != labels.length) {\n    throw new IllegalArgumentException(\"invalid training data\");\n}\nclassifier.fit(features, labels);","handlingStrategy":"validation","validationCode":"if (features == null || features.length == 0 || features.length != labels.length) {\n    throw new IllegalArgumentException(\"features/labels must be non-empty and equal-length\");\n}\nclassifier.fit(features, labels);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Pair features and labels per row during loading so lengths stay in sync.","Skip fitting on empty datasets and surface the condition upstream.","Add a null check for features before calling fit, since the method only guards length."],"tags":["machine-learning","validation","empty-input","argument-mismatch","naive-bayes"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}