c# 线性回归和多项式拟合

1. 线性回归

公式: 线性回归的目标是拟合一条直线,形式为: y=mx+by=mx+b 其中:

  • yy 是因变量(目标值)
  • xx 是自变量(特征值)
  • mm 是斜率(slope)
  • bb 是截距(intercept)

优点:

  • 简单易懂
  • 计算效率高

缺点:

  • 只能拟合线性关系
  • 对于非线性关系的适应能力差

C# 线性回归示例代码

复制代码
using MathNet.Numerics;
using MathNet.Numerics.LinearRegression;

class Program
{
    static void Main()
    {
        double[] x = { 1, 2, 3, 4, 5 };
        double[] y = { 2, 4, 6, 8, 10 };

        // 进行线性回归
        var (slope, intercept) = SimpleRegression.Fit(x, y);

        Console.WriteLine($"拟合方程: y = {intercept} + {slope}x");
    }
}

2. 多项式拟合

公式: 多项式拟合的目标是拟合一个多项式,形式为: y=anxn+an−1xn−1+...+a1x+a0y=an​xn+an−1​xn−1+...+a1​x+a0​ 其中:

  • an,an−1,...,a0an,an−1,...,a0 是多项式的系数
  • nn 是多项式的最高次数

优点:

  • 能拟合更复杂的非线性关系
  • 通过增加多项式的次数,可以提高拟合的灵活性

缺点:

  • 过拟合的风险较高(尤其是在高次多项式时)
  • 计算复杂度较高

C# 多项式拟合示例代码

复制代码
using MathNet.Numerics;
using MathNet.Numerics.LinearRegression;

class Program
{
    static void Main()
    {
        double[] x = { 1, 2, 3, 4, 5 };
        double[] y = { 2, 3, 5, 7, 11 }; // 一组非线性数据

        // 进行多项式拟合,设定次数为2
        double[] coefficients = Fit.Polynomial(x, y, degree: 2);

        Console.WriteLine("拟合方程:");
        for (int i = coefficients.Length - 1; i >= 0; i--)
        {
            Console.WriteLine($"{coefficients[i]}x^{i}");
        }
    }
}

对比总结

特征 线性回归 多项式拟合
拟合形式 直线 y=mx+by=mx+b 多项式 y=anxn+...y=an​xn+...
优点 简单、快速 能拟合复杂非线性关系
缺点 只能处理线性关系 容易过拟合,计算复杂度高
适用场景 数据呈线性关系时 数据呈现非线性关系时
相关推荐
Flower#1 小时前
D. Apple Tree Traversing 【Codeforces Round 1023 (Div. 2)】
c++·算法·图论·dfs
zhangfeng11332 小时前
Matlab 遗传算法的库 gads
算法·数据分析
究极无敌暴龙战神X2 小时前
hot100-子串-JS
javascript·数据结构·算法
codists8 小时前
《算法导论(第4版)》阅读笔记:p14-p16
算法
zilpher_wang8 小时前
K-means
算法·机器学习·kmeans
柃歌8 小时前
【LeetCode Solutions】LeetCode 176 ~ 180 题解
数据结构·数据库·sql·算法·leetcode
袁气满满~_~8 小时前
LeetCode:101、对称二叉树
算法·leetcode·职场和发展
How_doyou_do9 小时前
Dijkstra
算法
赵和范9 小时前
C++:书架
开发语言·c++·算法
tmiger10 小时前
图像匹配导航定位技术 第 10 章
人工智能·算法·计算机视觉