{"record":{"id":"0adbba5d0c5e552d","repo":"TheAlgorithms/C-Sharp","slug":"model-must-be-fitted-before-prediction","errorCode":null,"errorMessage":"Model must be fitted before prediction.","messagePattern":"Model must be fitted before prediction\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/LinearRegression.cs","lineNumber":79,"sourceCode":"            throw new ArgumentException(\"Variance of X must not be zero.\");\n        }\n\n        Slope = numerator / denominator;\n        Intercept = yMean - Slope * xMean;\n        IsFitted = true;\n    }\n\n    /// <summary>\n    /// Predicts the output value for a given input using the fitted model.\n    /// </summary>\n    /// <param name=\"x\">Input value.</param>\n    /// <returns>Predicted output value.</returns>\n    /// <exception cref=\"InvalidOperationException\">Thrown if the model is not fitted.</exception>\n    public double Predict(double x)\n    {\n        if (!IsFitted)\n        {\n            throw new InvalidOperationException(\"Model must be fitted before prediction.\");\n        }\n\n        return Intercept + Slope * x;\n    }\n\n    /// <summary>\n    /// Predicts output values for a list of inputs using the fitted model.\n    /// </summary>\n    /// <param name=\"xValues\">List of input values.</param>\n    /// <returns>List of predicted output values.</returns>\n    /// <exception cref=\"InvalidOperationException\">Thrown if the model is not fitted.</exception>\n    public IList<double> Predict(IList<double> xValues)\n    {\n        if (!IsFitted)\n        {\n            throw new InvalidOperationException(\"Model must be fitted before prediction.\");\n        }\n","sourceCodeStart":61,"sourceCodeEnd":97,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/LinearRegression.cs#L61-L97","documentation":"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.","triggerScenarios":"Calling Predict(x) on a new LinearRegression instance, or on one whose Fit call threw (null/empty/mismatched/zero-variance data), leaving IsFitted false.","commonSituations":"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.","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."],"exampleFix":"// before\nvar regression = new LinearRegression();\nvar y = regression.Predict(2.5); // not fitted\n// after\nvar regression = new LinearRegression();\nregression.Fit(xs, ys);\nif (!regression.IsFitted) throw new InvalidOperationException(\"Fit the model first.\");\nvar y = regression.Predict(2.5);","handlingStrategy":"validation","validationCode":"if (!regression.IsFitted)\n    throw new InvalidOperationException(\"Call Fit before Predict.\");\nvar y = regression.Predict(x);","typeGuard":null,"tryCatchPattern":"try\n{\n    var y = regression.Predict(x);\n}\ncatch (InvalidOperationException)\n{\n    // model not fitted — run training first\n    regression.Fit(xs, ys);\n    var y = regression.Predict(x);\n}","preventionTips":["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."],"tags":["csharp","invalid-operation","machine-learning","linear-regression","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"}