C# 一元线性回归算法及多元线性回归算法
By
jerryxjr1220
at 2024-03-15 • 0人收藏 • 207人看过
最近项目中正好需要用到线性回归算法,整理如下:
//需要安装Nuget包 using MathNet.Numerics.LinearAlgebra; internal class Program { static void Main(string[] args) { // 例子数据:y = 2x1 + 3x2 + 4x3 var x = new double[,] { {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}, {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {1, 1, 2}, {1, 2, 2}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}, {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {1, 1, 2}, {1, 2, 2}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}, {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {1, 1, 2}, {1, 2, 2}, }; var y = new double[] { 21, 29, 38, 47, 56, 9, 12, 11, 13, 16, 29, 38, 47, 56, 9, 12, 11, 13, 16, 29, 38, 47, 56, 9, 12, 11, 13, 16 }; var weights = MultiRegression(x, y); Console.WriteLine("回归系数:"); Console.WriteLine(weights); // 预测 Vector<double> newFeature = Vector<double>.Build.Dense(new double[] { 1, 2, 2, 2 }); double prediction = weights.DotProduct(newFeature); Console.WriteLine("预测值:"); Console.WriteLine(prediction); Console.ReadKey(); } public static Vector<double> MultiRegression(double[,] X_Mtx, double[] Y_Arr) { Matrix<double> features = Matrix<double>.Build.DenseOfArray(X_Mtx); Vector<double> labels = Vector<double>.Build.Dense(Y_Arr); Matrix<double> X = features.InsertColumn(0, Vector<double>.Build.Dense(features.RowCount, 1)); Vector<double> weights = (X.Transpose() * X).Inverse() * X.Transpose() * labels; return weights; }
一元线性回归是多元线性回归的特例,所以
public static Vector<double> SingleRegression(double[] X_Arr, double[] Y_Arr) { double[,] X_Mtx = new double[X_Arr.Length,2]; for (int i = 0; i < X_Arr.Length; i++) { X_Mtx[i, 0] = 1; X_Mtx[i, 1] = X_Arr[i]; } Matrix<double> X = Matrix<double>.Build.DenseOfArray(X_Mtx); Vector<double> labels = Vector<double>.Build.Dense(Y_Arr); Vector<double> weights = (X.Transpose() * X).Inverse() * X.Transpose() * labels; return weights; }
1 个回复 | 最后更新于 2024-03-15
登录后方可回帖
我大学数学不咋地