{"record":{"id":"18a3a69ec82c5c69","repo":"TheAlgorithms/C-Sharp","slug":"no-training-data-available","errorCode":null,"errorMessage":"No training data available.","messagePattern":"No training data available\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/KNearestNeighbors.cs","lineNumber":83,"sourceCode":"        if (features == null)\n        {\n            throw new ArgumentNullException(nameof(features));\n        }\n\n        trainingData.Add((features, label));\n    }\n\n    /// <summary>\n    /// Predicts the label for a given feature vector using the KNN algorithm.\n    /// </summary>\n    /// <param name=\"features\">Feature vector to classify.</param>\n    /// <returns>Predicted label.</returns>\n    /// <exception cref=\"InvalidOperationException\">Thrown if there is no training data.</exception>\n    public TLabel Predict(double[] features)\n    {\n        if (trainingData.Count == 0)\n        {\n            throw new InvalidOperationException(\"No training data available.\");\n        }\n\n        if (features == null)\n        {\n            throw new ArgumentNullException(nameof(features));\n        }\n\n        // Compute distances to all training samples\n        var distances = trainingData\n            .Select(td => (Label: td.Label, Distance: EuclideanDistance(features, td.Features)))\n            .OrderBy(x => x.Distance)\n            .Take(k)\n            .ToList();\n\n        // Majority vote\n        var labelCounts = distances\n            .GroupBy(x => x.Label)\n            .Select(g => new { Label = g.Key, Count = g.Count(), MinDistance = g.Min(item => item.Distance) })","sourceCodeStart":65,"sourceCodeEnd":101,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/KNearestNeighbors.cs#L65-L101","documentation":"Predict cannot classify without any training samples: there is nothing to compare distances against. The library throws InvalidOperationException when trainingData.Count == 0, i.e. Predict was called before any AddSample call.","triggerScenarios":"Calling Predict on a freshly constructed KNearestNeighbors instance with no prior AddSample calls; all AddSample calls skipped due to an empty or filtered training file.","commonSituations":"Training data file empty or path wrong so no samples loaded; loading code silently skipped malformed rows; model constructed but the training step accidentally removed during refactoring; deserialized model losing its training data.","solutions":["Call AddSample at least once (with valid k >= 1 data) before calling Predict.","Verify the training data source actually loaded samples; check count > 0 after loading.","Expose a check like trainingCount > 0 in application code before invoking Predict."],"exampleFix":"// before\nvar knn = new KNearestNeighbors(3);\nvar label = knn.Predict(query); // no samples added\n// after\nvar knn = new KNearestNeighbors(3);\nforeach (var s in trainingSet) knn.AddSample(s.Features, s.Label);\nif (trainingSet.Count == 0) throw new InvalidOperationException(\"Training set is empty.\");\nvar label = knn.Predict(query);","handlingStrategy":"validation","validationCode":"if (loadedSamples.Count == 0)\n    throw new InvalidOperationException(\"Cannot predict: no training samples were loaded.\");\nvar label = knn.Predict(query);","typeGuard":"static bool IsReadyForPrediction<TLabel>(KNearestNeighbors<TLabel> knn) => knn != null && loadedSampleCount > 0;","tryCatchPattern":"try\n{\n    var label = knn.Predict(query);\n}\ncatch (InvalidOperationException)\n{\n    // model has no training data — train first or return a 'model not ready' response\n    throw new ApplicationException(\"Classifier not trained yet.\");\n}","preventionTips":["Track the number of AddSample calls and gate Predict behind a 'trained' flag.","Verify the training data file exists and is non-empty before constructing the model.","Add an integration test that predicts only after loading a known dataset."],"tags":["csharp","invalid-operation","machine-learning","empty-state","predict-before-fit"],"backgroundTag":"invalid-state-transition","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"}