{"record":{"id":"525601d2ed5f575c","repo":"TheAlgorithms/C-Sharp","slug":"feature-count-mismatch","errorCode":null,"errorMessage":"Feature count mismatch.","messagePattern":"Feature count mismatch\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/LogisticRegression.cs","lineNumber":73,"sourceCode":"            }\n\n            for (int j = 0; j < nFeatures; j++)\n            {\n                weights[j] -= learningRate * dw[j] / nSamples;\n            }\n\n            bias -= learningRate * db / nSamples;\n        }\n    }\n\n    /// <summary>\n    /// Predict probability for a single sample.\n    /// </summary>\n    public double PredictProbability(double[] x)\n    {\n        if (x.Length != weights.Length)\n        {\n            throw new ArgumentException(\"Feature count mismatch.\");\n        }\n\n        return Sigmoid(Dot(x, weights) + bias);\n    }\n\n    /// <summary>\n    /// Predict class label (0 or 1) for a single sample.\n    /// </summary>\n    public int Predict(double[] x) => PredictProbability(x) >= 0.5 ? 1 : 0;\n\n    private static double Sigmoid(double z) => 1.0 / (1.0 + Math.Exp(-z));\n\n    private static double Dot(double[] a, double[] b) => a.Zip(b).Sum(pair => pair.First * pair.Second);\n}\n","sourceCodeStart":55,"sourceCodeEnd":88,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/LogisticRegression.cs#L55-L88","documentation":"PredictProbability validates that a sample has the same number of features as the weight vector learned during Fit. A mismatched vector cannot be dotted with the weights, so the library throws ArgumentException instead of computing a garbage result.","triggerScenarios":"Calling PredictProbability(double[] x) (directly or via Predict) with a vector whose Length differs from the feature count used in Fit, e.g. forgetting a bias/intercept column or passing multiple samples instead of one.","commonSituations":"Serving-time feature engineering differs from training (extra/dropped column); passing a 2D row set to the single-sample API; changing the dataset schema after the model was fitted.","solutions":["Ensure each prediction sample has exactly the same features, in the same order, as training data.","Check x.Length against the model's feature count (e.g. weights.Length) before predicting.","If passing multiple samples, call the batch Predict API rather than looping the wrong-shaped data into PredictProbability."],"exampleFix":"// before\nmodel.PredictProbability(new double[] { 1.0, 2.0, 3.0 }); // trained on 2 features\n\n// after\nmodel.PredictProbability(new double[] { 1.0, 2.0 }); // matches weights.Length","handlingStrategy":"validation","validationCode":"if (sample.Length != expectedFeatureCount)\n{\n    throw new ArgumentException($\"Expected {expectedFeatureCount} features, got {sample.Length}.\");\n}\nvar p = model.PredictProbability(sample);","typeGuard":"static bool MatchesFeatureCount(double[] x, int n) => x != null && x.Length == n;","tryCatchPattern":"try\n{\n    var p = model.PredictProbability(sample);\n}\ncatch (ArgumentException ex) when (ex.Message == \"Feature count mismatch.\")\n{\n    logger.LogError(\"Sample has {Len} features, model expects {Exp}\", sample.Length, model.FeatureCount);\n    throw;\n}","preventionTips":["Share one feature-engineering function between training and serving so schemas cannot drift.","Store the trained feature count with the model and validate inputs against it at the boundary.","Write a round-trip test: fit on a sample, then predict on that exact sample."],"tags":["machine-learning","shape-mismatch","validation","csharp"],"backgroundTag":"tensor-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"}