{"record":{"id":"c42099e94c9bb8bc","repo":"TheAlgorithms/C-Sharp","slug":"number-of-samples-and-labels-must-match","errorCode":null,"errorMessage":"Number of samples and labels must match.","messagePattern":"Number of samples and labels must match\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/LogisticRegression.cs","lineNumber":32,"sourceCode":"    public int FeatureCount => weights.Length;\n\n    /// <summary>\n    /// Fit the model using gradient descent.\n    /// </summary>\n    /// <param name=\"x\">2D array of features (samples x features).</param>\n    /// <param name=\"y\">Array of labels (0 or 1).</param>\n    /// <param name=\"epochs\">Number of iterations.</param>\n    /// <param name=\"learningRate\">Step size.</param>\n    public void Fit(double[][] x, int[] y, int epochs = 1000, double learningRate = 0.01)\n    {\n        if (x.Length == 0 || x[0].Length == 0)\n        {\n            throw new ArgumentException(\"Input features cannot be empty.\");\n        }\n\n        if (x.Length != y.Length)\n        {\n            throw new ArgumentException(\"Number of samples and labels must match.\");\n        }\n\n        int nSamples = x.Length;\n        int nFeatures = x[0].Length;\n        weights = new double[nFeatures];\n        bias = 0;\n\n        for (int epoch = 0; epoch < epochs; epoch++)\n        {\n            double[] dw = new double[nFeatures];\n            double db = 0;\n            for (int i = 0; i < nSamples; i++)\n            {\n                double linear = Dot(x[i], weights) + bias;\n                double pred = Sigmoid(linear);\n                double error = pred - y[i];\n                for (int j = 0; j < nFeatures; j++)\n                {","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/LogisticRegression.cs#L14-L50","documentation":"LogisticRegression.Fit requires the number of feature rows to equal the number of labels. If x.Length != y.Length, each sample cannot be paired with exactly one binary label, so training is undefined and the library throws ArgumentException.","triggerScenarios":"Calling Fit with x and y arrays of different lengths, e.g. 100 feature rows but 99 labels after a filtering step applied to only one of them.","commonSituations":"Dropping NaN rows from x but not y (or vice versa); a train/test split that sliced arrays inconsistently; a CSV parser that skipped malformed label rows.","solutions":["Re-check the code that produced x and y so both derive from the same rows.","Apply any row filtering/removal to x and y together (e.g. zip then filter then unzip).","Assert x.Length == y.Length in the caller before invoking Fit to fail earlier with context."],"exampleFix":"// before\nvar filteredX = x.Where(r => !r.Any(double.IsNaN)).ToArray();\nmodel.Fit(filteredX, y); // lengths may differ\n\n// after\nvar paired = x.Zip(y, (xi, yi) => (xi, yi)).Where(p => !p.xi.Any(double.IsNaN)).ToList();\nmodel.Fit(paired.Select(p => p.xi).ToArray(), paired.Select(p => p.yi).ToArray());","handlingStrategy":"validation","validationCode":"if (x.Length != y.Length)\n{\n    throw new ArgumentException($\"x has {x.Length} samples but y has {y.Length} labels.\");\n}\nmodel.Fit(x, y);","typeGuard":"static bool LabelsMatchSamples<T>(T[][] x, int[] y) => x != null && y != null && x.Length == y.Length;","tryCatchPattern":"try\n{\n    model.Fit(x, y);\n}\ncatch (ArgumentException ex) when (ex.Message == \"Number of samples and labels must match.\")\n{\n    logger.LogError(\"Feature/label count mismatch: x={X}, y={Y}\", x.Length, y.Length);\n    throw;\n}","preventionTips":["Keep x and y in a single paired structure (tuples) until the moment of training.","Apply row-level filtering to x and y together, never separately.","Assert equal lengths after every transformation step in the pipeline."],"tags":["machine-learning","validation","shape-mismatch","csharp"],"backgroundTag":"shape-mismatch","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}