TheAlgorithms/C-Sharp · error · ArgumentException
Feature count mismatch.
Error message
Feature count mismatch.
What it means
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.
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.
Example fix
// before
model.PredictProbability(new double[] { 1.0, 2.0, 3.0 }); // trained on 2 features
// after
model.PredictProbability(new double[] { 1.0, 2.0 }); // matches weights.Length Defensive patterns
Strategy: validation
Validate before calling
if (sample.Length != expectedFeatureCount)
{
throw new ArgumentException($"Expected {expectedFeatureCount} features, got {sample.Length}.");
}
var p = model.PredictProbability(sample); Type guard
static bool MatchesFeatureCount(double[] x, int n) => x != null && x.Length == n;
Try / catch
try
{
var p = model.PredictProbability(sample);
}
catch (ArgumentException ex) when (ex.Message == "Feature count mismatch.")
{
logger.LogError("Sample has {Len} features, model expects {Exp}", sample.Length, model.FeatureCount);
throw;
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Understand the failure class
Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.
Related errors
- Number of samples and labels must match.
- k must be at least 1.
- Input features cannot be empty.
- message
- key must be non-empty string
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/525601d2ed5f575c.
Report an issue: GitHub.
Appendix: source
Thrown at Algorithms/MachineLearning/LogisticRegression.cs:73
}
for (int j = 0; j < nFeatures; j++)
{
weights[j] -= learningRate * dw[j] / nSamples;
}
bias -= learningRate * db / nSamples;
}
}
/// <summary>
/// Predict probability for a single sample.
/// </summary>
public double PredictProbability(double[] x)
{
if (x.Length != weights.Length)
{
throw new ArgumentException("Feature count mismatch.");
}
return Sigmoid(Dot(x, weights) + bias);
}
/// <summary>
/// Predict class label (0 or 1) for a single sample.
/// </summary>
public int Predict(double[] x) => PredictProbability(x) >= 0.5 ? 1 : 0;
private static double Sigmoid(double z) => 1.0 / (1.0 + Math.Exp(-z));
private static double Dot(double[] a, double[] b) => a.Zip(b).Sum(pair => pair.First * pair.Second);
}
View on GitHub (pinned to 96e2905cab)