Math.NET Regression:如何获取回归的斜率、截距及系数?
Hey there, let's clarify exactly how to get the intercept from a simple linear regression using Math.NET Numerics, since you already know how to work with the xdata and ydata arrays.
Using the SimpleRegression class instance
The easiest way is to use the built-in SimpleRegression class, which calculates and exposes the intercept directly as a property once you've loaded your data:
using MathNet.Numerics.Statistics; // Your input data arrays double[] xdata = new double[] { 1, 2, 3, 4, 5 }; double[] ydata = new double[] { 2, 4, 5, 4, 6 }; // Initialize the regression and add your data var regression = new SimpleRegression(); regression.AddRange(xdata, ydata); // Grab the intercept directly double intercept = regression.Intercept; // You can also get the slope here for reference double slope = regression.Slope;
Using the static Fit method (shorter syntax)
If you prefer a more concise approach, the static SimpleRegression.Fit method returns a tuple containing both the slope and intercept in one go:
// Directly get slope and intercept from your data arrays var (slope, intercept) = SimpleRegression.Fit(xdata, ydata);
Manual verification (optional)
If you want to cross-check the result using the linear regression formula, the intercept is calculated as:
intercept = mean(ydata) - slope * mean(xdata)
You can compute this manually with Math.NET's built-in statistics methods too:
double meanX = xdata.Mean(); double meanY = ydata.Mean(); double manualIntercept = meanY - slope * meanX;
All these approaches will give you the exact intercept value you're looking for—no extra hoops to jump through, since Math.NET handles the heavy lifting for you.
内容的提问来源于stack exchange,提问作者Jon

