TheAlgorithms/C-Sharp · error · ArgumentException

Number of samples and labels must match.

Error message

Number of samples and labels must match.

What it means

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.

Solutions

  1. Re-check the code that produced x and y so both derive from the same rows.
  2. Apply any row filtering/removal to x and y together (e.g. zip then filter then unzip).
  3. Assert x.Length == y.Length in the caller before invoking Fit to fail earlier with context.

Example fix

// before
var filteredX = x.Where(r => !r.Any(double.IsNaN)).ToArray();
model.Fit(filteredX, y); // lengths may differ

// after
var paired = x.Zip(y, (xi, yi) => (xi, yi)).Where(p => !p.xi.Any(double.IsNaN)).ToList();
model.Fit(paired.Select(p => p.xi).ToArray(), paired.Select(p => p.yi).ToArray());
Defensive patterns

Strategy: validation

Validate before calling

if (x.Length != y.Length)
{
    throw new ArgumentException($"x has {x.Length} samples but y has {y.Length} labels.");
}
model.Fit(x, y);

Type guard

static bool LabelsMatchSamples<T>(T[][] x, int[] y) => x != null && y != null && x.Length == y.Length;

Try / catch

try
{
    model.Fit(x, y);
}
catch (ArgumentException ex) when (ex.Message == "Number of samples and labels must match.")
{
    logger.LogError("Feature/label count mismatch: x={X}, y={Y}", x.Length, y.Length);
    throw;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/c42099e94c9bb8bc. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/MachineLearning/LogisticRegression.cs:32

    public int FeatureCount => weights.Length;

    /// <summary>
    /// Fit the model using gradient descent.
    /// </summary>
    /// <param name="x">2D array of features (samples x features).</param>
    /// <param name="y">Array of labels (0 or 1).</param>
    /// <param name="epochs">Number of iterations.</param>
    /// <param name="learningRate">Step size.</param>
    public void Fit(double[][] x, int[] y, int epochs = 1000, double learningRate = 0.01)
    {
        if (x.Length == 0 || x[0].Length == 0)
        {
            throw new ArgumentException("Input features cannot be empty.");
        }

        if (x.Length != y.Length)
        {
            throw new ArgumentException("Number of samples and labels must match.");
        }

        int nSamples = x.Length;
        int nFeatures = x[0].Length;
        weights = new double[nFeatures];
        bias = 0;

        for (int epoch = 0; epoch < epochs; epoch++)
        {
            double[] dw = new double[nFeatures];
            double db = 0;
            for (int i = 0; i < nSamples; i++)
            {
                double linear = Dot(x[i], weights) + bias;
                double pred = Sigmoid(linear);
                double error = pred - y[i];
                for (int j = 0; j < nFeatures; j++)
                {

View on GitHub (pinned to 96e2905cab)