TheAlgorithms/C-Sharp · error · InvalidOperationException
No training data available.
Error message
No training data available.
What it means
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.
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.
Example fix
// before
var knn = new KNearestNeighbors(3);
var label = knn.Predict(query); // no samples added
// after
var knn = new KNearestNeighbors(3);
foreach (var s in trainingSet) knn.AddSample(s.Features, s.Label);
if (trainingSet.Count == 0) throw new InvalidOperationException("Training set is empty.");
var label = knn.Predict(query); Defensive patterns
Strategy: validation
Validate before calling
if (loadedSamples.Count == 0)
throw new InvalidOperationException("Cannot predict: no training samples were loaded.");
var label = knn.Predict(query); Type guard
static bool IsReadyForPrediction<TLabel>(KNearestNeighbors<TLabel> knn) => knn != null && loadedSampleCount > 0;
Try / catch
try
{
var label = knn.Predict(query);
}
catch (InvalidOperationException)
{
// model has no training data — train first or return a 'model not ready' response
throw new ApplicationException("Classifier not trained yet.");
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Understand the failure class
Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.
Related errors
- Model must be fitted before prediction.
- k must be at least 1.
- Feature vectors must be of the same length.
- ArgumentNullException: features
- Input data cannot be null.
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/18a3a69ec82c5c69.
Report an issue: GitHub.
Appendix: source
Thrown at Algorithms/MachineLearning/KNearestNeighbors.cs:83
if (features == null)
{
throw new ArgumentNullException(nameof(features));
}
trainingData.Add((features, label));
}
/// <summary>
/// Predicts the label for a given feature vector using the KNN algorithm.
/// </summary>
/// <param name="features">Feature vector to classify.</param>
/// <returns>Predicted label.</returns>
/// <exception cref="InvalidOperationException">Thrown if there is no training data.</exception>
public TLabel Predict(double[] features)
{
if (trainingData.Count == 0)
{
throw new InvalidOperationException("No training data available.");
}
if (features == null)
{
throw new ArgumentNullException(nameof(features));
}
// Compute distances to all training samples
var distances = trainingData
.Select(td => (Label: td.Label, Distance: EuclideanDistance(features, td.Features)))
.OrderBy(x => x.Distance)
.Take(k)
.ToList();
// Majority vote
var labelCounts = distances
.GroupBy(x => x.Label)
.Select(g => new { Label = g.Key, Count = g.Count(), MinDistance = g.Min(item => item.Distance) })View on GitHub (pinned to 96e2905cab)