TheAlgorithms/C-Sharp · error · ArgumentException

Feature vectors must be of the same length.

Error message

Feature vectors must be of the same length.

What it means

EuclideanDistance requires both feature vectors to have the same number of dimensions; it subtracts element-wise, which is only defined for equal-length arrays. The library throws ArgumentException when a.Length != b.Length instead of producing a wrong or IndexOutOfRange result.

Solutions

  1. Ensure every training sample added via AddSample has the same length as the vector passed to Predict.
  2. Validate/normalize input feature vectors to a fixed dimension before calling Predict.
  3. If using EuclideanDistance directly, check a.Length == b.Length before calling.

Example fix

// before
knn.AddSample(new double[] { 1, 2, 3 }, "a");
knn.Predict(new double[] { 1, 2 }); // length mismatch
// after
knn.AddSample(new double[] { 1, 2, 3 }, "a");
knn.Predict(new double[] { 1, 2, 0 }); // same dimensionality
Defensive patterns

Strategy: validation

Validate before calling

if (query.Length != trainingFeatureLength)
    throw new ArgumentException($"Expected {trainingFeatureLength} features, got {query.Length}.");
var label = knn.Predict(query);

Type guard

static bool IsValidFeatureVector(double[]? v, int expectedDim) =>
    v != null && v.Length == expectedDim;

Try / catch

try
{
    var label = knn.Predict(query);
}
catch (ArgumentException ex)
{
    // dimension mismatch between query and training vectors
    logger.LogError(ex, "Feature dimension mismatch");
}

Prevention

When it happens

Trigger: Calling EuclideanDistance(a, b) (directly or via Predict, which compares the query vector against every stored training sample) with arrays of different lengths.

Common situations: Training samples added with a different feature count than the prediction input; schema changes adding/removing a feature; a malformed CSV row yielding fewer columns; accidentally passing a label or bias term inside one of the arrays.

Related errors


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

Appendix: source

Thrown at Algorithms/MachineLearning/KNearestNeighbors.cs:45

        {
            throw new ArgumentOutOfRangeException(nameof(k), "k must be at least 1.");
        }

        this.k = k;
    }

    /// <summary>
    /// Calculates the Euclidean distance between two feature vectors.
    /// </summary>
    /// <param name="a">First feature vector.</param>
    /// <param name="b">Second feature vector.</param>
    /// <returns>Euclidean distance.</returns>
    /// <exception cref="ArgumentException">Thrown if vectors are of different lengths.</exception>
    public static double EuclideanDistance(double[] a, double[] b)
    {
        if (a.Length != b.Length)
        {
            throw new ArgumentException("Feature vectors must be of the same length.");
        }

        double sum = 0;
        for (int i = 0; i < a.Length; i++)
        {
            double diff = a[i] - b[i];
            sum += diff * diff;
        }

        return Math.Sqrt(sum);
    }

    /// <summary>
    /// Adds a training sample to the classifier.
    /// </summary>
    /// <param name="features">Feature vector of the sample.</param>
    /// <param name="label">Label of the sample.</param>
    public void AddSample(double[] features, TLabel label)

View on GitHub (pinned to 96e2905cab)