TheAlgorithms/C-Sharp · error · InvalidOperationException
Model must be fitted before prediction.
Error message
Model must be fitted before prediction.
What it means
Predict uses the Slope and Intercept computed by Fit; before Fit succeeds those are meaningless defaults. LinearRegression tracks IsFitted and throws InvalidOperationException('Model must be fitted before prediction.') if Predict is called first.
Solutions
- Call Fit(x, y) successfully before any Predict call.
- Check the IsFitted property before predicting and handle the unfitted case in app code.
- If Fit failed earlier, fix the underlying data issue (null/empty/mismatch/zero variance) so it completes.
Example fix
// before
var regression = new LinearRegression();
var y = regression.Predict(2.5); // not fitted
// after
var regression = new LinearRegression();
regression.Fit(xs, ys);
if (!regression.IsFitted) throw new InvalidOperationException("Fit the model first.");
var y = regression.Predict(2.5); Defensive patterns
Strategy: validation
Validate before calling
if (!regression.IsFitted)
throw new InvalidOperationException("Call Fit before Predict.");
var y = regression.Predict(x); Try / catch
try
{
var y = regression.Predict(x);
}
catch (InvalidOperationException)
{
// model not fitted — run training first
regression.Fit(xs, ys);
var y = regression.Predict(x);
} Prevention
- Encapsulate Fit+Predict in a single train-then-serve workflow so Predict is unreachable before Fit.
- Check the IsFitted property at the prediction entry point.
- If Fit can throw on bad data, ensure failures don't leave the model half-initialized and still reachable by Predict callers.
- Avoid sharing one LinearRegression instance across threads without ensuring Fit completed first.
When it happens
Trigger: Calling Predict(x) on a new LinearRegression instance, or on one whose Fit call threw (null/empty/mismatched/zero-variance data), leaving IsFitted false.
Common situations: Using a model instance before the training pipeline ran; a silent Fit failure earlier in the flow; sharing a model across threads where Predict starts before Fit finishes.
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
- No training data available.
- Input data cannot be null.
- Input data cannot be empty.
- Input lists must have the same length.
- Variance of X must not be zero.
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/0adbba5d0c5e552d.
Report an issue: GitHub.
Appendix: source
Thrown at Algorithms/MachineLearning/LinearRegression.cs:79
throw new ArgumentException("Variance of X must not be zero.");
}
Slope = numerator / denominator;
Intercept = yMean - Slope * xMean;
IsFitted = true;
}
/// <summary>
/// Predicts the output value for a given input using the fitted model.
/// </summary>
/// <param name="x">Input value.</param>
/// <returns>Predicted output value.</returns>
/// <exception cref="InvalidOperationException">Thrown if the model is not fitted.</exception>
public double Predict(double x)
{
if (!IsFitted)
{
throw new InvalidOperationException("Model must be fitted before prediction.");
}
return Intercept + Slope * x;
}
/// <summary>
/// Predicts output values for a list of inputs using the fitted model.
/// </summary>
/// <param name="xValues">List of input values.</param>
/// <returns>List of predicted output values.</returns>
/// <exception cref="InvalidOperationException">Thrown if the model is not fitted.</exception>
public IList<double> Predict(IList<double> xValues)
{
if (!IsFitted)
{
throw new InvalidOperationException("Model must be fitted before prediction.");
}
View on GitHub (pinned to 96e2905cab)