C#最小二乘法进行曲线拟合及相关系数

两个类:

类1:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 高斯消元法
{
    class Program
    {
        static void Main(string[] args)
        {
           /* double[,] xArray = new double[,]
            {
                
                    { 2.000000 ,-1.000000 , 3.000000,  1.000000},
                    { 4.000000 , 2.000000 , 5.000000,  4.000000},
                    { 1.000000 , 2.000000 , 0.000000 , 7.000000}
            };*/

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            double[] y = new double[] { 29152.3, 47025.3, 86852.3, 132450.6, 200302.3, 284688.1, 396988.3 };
            double[] x = new double[] { 1.24, 2.37, 5.12, 8.12, 12.19, 17.97, 24.99 };

           // double[,] xArray;
            double[] ratio;
            double[] yy = new double[y.Length];

            Console.WriteLine("一次拟合:");
            sw.Start();
            ratio = FittingFunct.Linear(y, x);
            sw.Stop();

            foreach (double num in ratio)
            {
                Console.WriteLine(num);
            }
            for (int i = 0; i < x.Length; i++)
            {
                yy[i] = ratio[0] + ratio[1] * x[i];
            }
            Console.WriteLine("R²=: " + FittingFunct.Pearson(y, yy) + "\r\n");
            //Console.WriteLine("一次拟合计算时间:");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            Console.WriteLine("一次拟合(截距为0,即强制过原点):");
            sw.Start();
            ratio = FittingFunct.LinearInterceptZero(y, x);
            sw.Stop();

            foreach (double num in ratio)
            {
                Console.WriteLine(num);
            }
            for (int i = 0; i < x.Length; i++)
            {
                yy[i] = ratio[0] * x[i];
            }
            Console.WriteLine("R²=: " + FittingFunct.Pearson(y, yy) + "\r\n");
            //Console.WriteLine("一次拟合计算时间:");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            Console.WriteLine("二次拟合:");
            sw.Start();
            ratio = FittingFunct.TowTimesCurve(y, x);
            sw.Stop();

            foreach (double num in ratio)
            {
                Console.WriteLine(num);
            }
            for (int i = 0; i < x.Length; i++)
            {
                yy[i] = ratio[0] + ratio[1] * x[i] + ratio[2] * x[i] * x[i];
            }
            Console.WriteLine("R²=: " + FittingFunct.Pearson(y, yy) + "\r\n");
            //Console.WriteLine("二次拟合计算时间:");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            Console.WriteLine("对数拟合计算时间:");
            sw.Start();
            ratio = FittingFunct.LOGEST(y, x);
            sw.Stop();

            foreach (double num in ratio)
            {
                Console.WriteLine(num);
            }
            for (int i = 0; i < x.Length; i++)
            {
                yy[i] = ratio[1]*Math.Log10(x[i]) + ratio[0];
            }
            Console.WriteLine("R²=: " + FittingFunct.Pearson(y, yy) + "\r\n");
            //Console.WriteLine("对数拟合计算时间:");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            Console.WriteLine("幂级数拟合:");
            sw.Start();
            ratio=FittingFunct.PowEST(y,x);
            sw.Stop();

             foreach (double num in ratio)
            {
                Console.WriteLine(num);
            }
             for (int i = 0; i < x.Length; i++)
             {
                 yy[i] = ratio[0] * Math.Pow(x[i], ratio[1]);
             }
             Console.WriteLine("R²=: " + FittingFunct.Pearson(y, yy) + "\r\n");
             //Console.WriteLine("幂级数拟合计算时间:");
             //Console.WriteLine(sw.ElapsedMilliseconds);

            Console.WriteLine("指数函数拟合:");
            sw.Start();
            ratio = FittingFunct.IndexEST(y, x);
            sw.Stop();
            foreach (double num in ratio)
            {
                Console.WriteLine(num);
            }
            for (int i = 0; i < x.Length; i++)
            {
                yy[i] = ratio[0] * Math.Exp(x[i] * ratio[1]);
            }
            Console.WriteLine("R²=: " + FittingFunct.Pearson(y, yy));
            //Console.WriteLine("指数函数拟合计算时间:");
            //Console.WriteLine(sw.ElapsedMilliseconds);

            Console.ReadKey();
       
        }
    }
}

类2:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 高斯消元法
{
    class FittingFunct
    {
          #region 多项式拟合函数,输出系数是y=a0+a1*x+a2*x*x+.........,按a0,a1,a2输出
        static public double[] Polyfit(double[] y, double[] x, int order)
        {
              double[,] guass = Get_Array(y, x, order);
           
              double[] ratio = Cal_Guass(guass, order + 1);
            
              return ratio;
        }
        #endregion

          #region 一次拟合函数,y=a0+a1*x,输出次序是a0,a1
        static public double[] Linear(double[] y,double[] x)
        {
            double[] ratio = Polyfit(y, x, 1);
            return ratio;
        }
         #endregion

        #region 一次拟合函数,截距为0,y=a0x,输出次序是a0
        static public double[] LinearInterceptZero(double[] y, double[] x)
        {
            double divisor = 0; //除数
            double dividend = 0; //被除数
            for (int i = 0; i < x.Length;i++ )
            {
                divisor += x[i] * x[i];
                dividend += x[i] * y[i];
            }
            if (divisor == 0)
            {
                throw (new Exception("除数不为0!"));
                return null;
            }
            return new double[] { dividend / divisor };

        }
        #endregion

        #region 二次拟合函数,y=a0+a1*x+a2x²,输出次序是a0,a1,a2
        static public double[] TowTimesCurve(double[] y, double[] x)
        {
            double[] ratio = Polyfit(y, x, 2);
            return ratio;
        }
        #endregion

          #region 对数拟合函数,.y= c*(ln x)+b,输出为b,c
        static public double[] LOGEST(double[] y, double[] x)
        {
            double[] lnX = new double[x.Length];

            for (int i = 0; i < x.Length; i++)
            {
                if (x[i] == 0 || x[i] < 0)
                {
                    throw (new Exception("正对非正数取对数!"));
                    return null;
                }
                lnX[i] = Math.Log(x[i]);
            }

            return Linear(y, lnX);
        }
        #endregion

          #region 幂函数拟合模型, y=c*x^b,输出为c,b
        static public double[] PowEST(double[] y, double[] x)
        {
            double[] lnX = new double[x.Length];
            double[] lnY = new double[y.Length];
            double[] dlinestRet;

            for (int i = 0; i < x.Length; i++)
            {
                lnX[i] = Math.Log(x[i]);
                lnY[i] = Math.Log(y[i]);
            }

            dlinestRet = Linear(lnY, lnX);

           dlinestRet[0] = Math.Exp(dlinestRet[0]);
           
            return dlinestRet;
        }
         #endregion

         #region 指数函数拟合函数模型,公式为 y=c*m^x;输出为 c,m
         static  public double[] IndexEST(double[] y, double[] x)
        {
            double[] lnY = new double[y.Length];
            double[] ratio;
            for (int i = 0; i < y.Length; i++)
            {
                lnY[i] = Math.Log(y[i]);
             }

            ratio = Linear(lnY, x);
            for (int i = 0; i < ratio.Length; i++)
            {
                if (i == 0)
                {
                    ratio[i] = Math.Exp(ratio[i]);
                }
             }
            return ratio;
        }
         #endregion

         #region 相关系数R²部分
         public static double Pearson(IEnumerable<double> dataA, IEnumerable<double> dataB)
         {
             int n = 0;
             double r = 0.0;

             double meanA = 0;
             double meanB = 0;
             double varA = 0;
             double varB = 0;
             int ii = 0;
             using (IEnumerator<double> ieA = dataA.GetEnumerator())
             using (IEnumerator<double> ieB = dataB.GetEnumerator())
             {
                 while (ieA.MoveNext())
                 {
                     if (!ieB.MoveNext())
                     {
                         //throw new ArgumentOutOfRangeException("dataB", Resources.ArgumentArraysSameLength);
                     }
                     ii++;
                     //Console.WriteLine("FF00::  " + ii + " --  " + meanA + " -- " + meanB + " -- " + varA + "  ---  " + varB);
                     double currentA = ieA.Current;
                     double currentB = ieB.Current;

                     double deltaA = currentA - meanA;
                     double scaleDeltaA = deltaA / ++n;

                     double deltaB = currentB - meanB;
                     double scaleDeltaB = deltaB / n;

                     meanA += scaleDeltaA;
                     meanB += scaleDeltaB;

                     varA += scaleDeltaA * deltaA * (n - 1);
                     varB += scaleDeltaB * deltaB * (n - 1);
                     r += (deltaA * deltaB * (n - 1)) / n;
                     //Console.WriteLine("FF00::  " + ii + " --  " + meanA + " -- " + meanB + " -- " + varA + "  ---  " + varB);
                 }

                 if (ieB.MoveNext())
                 {
                     //throw new ArgumentOutOfRangeException("dataA", Resources.ArgumentArraysSameLength);
                 }
             }
             return (r / Math.Sqrt(varA * varB)) * (r / Math.Sqrt(varA * varB));
         }
         #endregion

#region 最小二乘法部分

          #region 计算增广矩阵
        static  private double[] Cal_Guass(double[,] guass,int count)
        {
            double temp;
            double[] x_value;

            for (int j = 0; j < count; j++)
            {
                int k = j;
                double min = guass[j,j];

                for (int i = j; i < count; i++)
                {
                    if (Math.Abs(guass[i, j]) < min)
                    {
                        min = guass[i, j];
                        k = i;
                    }
                }

                if (k != j)
                {
                    for (int x = j; x <= count; x++)
                    {
                        temp = guass[k, x];
                        guass[k, x] = guass[j, x];
                        guass[j, x] = temp;
                    }
                }

                for (int m = j + 1; m < count; m++)
                {
                    double div = guass[m, j] / guass[j, j];
                    for (int n = j; n <= count; n++)
                    {
                        guass[m, n] = guass[m, n] - guass[j, n] * div;
                    }
                }

               /* System.Console.WriteLine("初等行变换:");
                for (int i = 0; i < count; i++)
                {
                    for (int m = 0; m < count + 1; m++)
                    {
                        System.Console.Write("{0,10:F6}", guass[i, m]);
                    }
                    Console.WriteLine();
                }*/
            }
            x_value= Get_Value(guass, count);

            return x_value;

            /*if (x_value == null)
                Console.WriteLine("方程组无解或多解!");
            else
            {
                foreach (double x in x_value)
                {
                    Console.WriteLine("{0:F6}", x);
                }
            }*/
        }

        #endregion

          #region 回带计算X值
        static private double[] Get_Value(double[,] guass,int count)
        {
            double[] x = new double[count];
            double[,] X_Array = new double[count, count];
            int rank = guass.Rank;//秩是从0开始的

            for (int i = 0; i < count; i++)
                for (int j = 0; j < count; j++)
                    X_Array[i, j] = guass[i, j];

            if (X_Array.Rank < guass.Rank)//表示无解
            {
                return null;
            }

            if (X_Array.Rank < count-1)//表示有多解
            {
                return null;
            }
            //回带计算x值
            x[count - 1] = guass[count - 1, count] / guass[count-1, count-1];
            for (int i = count - 2; i >= 0; i--)
            {
                double temp=0;
                for (int j = i; j < count; j++)
                {
                    temp += x[j] * guass[i, j];
                }
                x[i] = (guass[i, count] - temp) / guass[i, i];
            }

                return x;
        }
          #endregion

          #region  得到数据的法矩阵,输出为发矩阵的增广矩阵
        static private double[,] Get_Array(double[] y, double[] x, int n)
        {
            double[,] result = new double[n + 1, n + 2];

            if (y.Length != x.Length)
            {
                throw (new Exception("两个输入数组长度不一!"));
                //return null;
            }

            for (int i = 0; i <= n; i++)
            {
                for (int j = 0; j <= n; j++)
                {
                    result[i, j] = Cal_sum(x, i + j);
                }
                result[i, n + 1] = Cal_multi(y, x, i);
            }

            return result;
        }

     #endregion

          #region 累加的计算
        static private double Cal_sum(double[] input,int order)
        {
            double result=0;
            int length = input.Length;          

            for (int i = 0; i < length; i++)
            {
                result += Math.Pow(input[i], order);
            }

           return result;
        }
        #endregion

          #region 计算∑(x^j)*y
        static private double Cal_multi(double[] y,double[] x,int order)
        {
            double result = 0;

            int length = x.Length;

            for (int i = 0; i < length; i++)
            {
                result += Math.Pow(x[i], order) * y[i];
            }

            return result;
        }
         #endregion

#endregion
    }
}



  • 9
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
对于使用C#实现最小二乘法进行曲线拟合,你可以按照以下步骤进行操作: 1. 首先,确定你想要拟合曲线类型,例如直线、多项式等。假设你选择的是多项式曲线拟合。 2. 创建一个C#类,并添加一个方法来执行最小二乘法拟合。该方法将接受输入的数据点集合和拟合的阶数作为参数,并返回拟合结果。 3. 在最小二乘法拟合方法中,首先计算数据点的总数以及自变量和因变量的和与平方和。 4. 接下来,根据拟合的阶数,构建一个系数矩阵和一个常数向量。系数矩阵的行数等于数据点的总数,列数等于拟合的阶数加1。 5. 使用数据点的自变量值和因变量值来填充系数矩阵和常数向量。每个元素的值等于自变量值的幂次方。 6. 利用最小二乘法的公式计算出系数矩阵的逆矩阵和最终的系数向量。 7. 最后,返回拟合的系数向量作为最小二乘法曲线拟合的结果。 这是一个简单的示例代码,用于执行多项式曲线拟合最小二乘法: ```csharp using System; using MathNet.Numerics.LinearAlgebra; public class LeastSquaresFitting { public static Vector<double> PolynomialFit(Vector<double> xData, Vector<double> yData, int order) { int n = xData.Count; int m = order + 1; Matrix<double> A = Matrix<double>.Build.Dense(n, m); Vector<double> b = Vector<double>.Build.Dense(n); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { A[i, j] = Math.Pow(xData[i], j); } b[i] = yData[i]; } Matrix<double> ATransposeA = A.TransposeAndMultiply(A); Vector<double> ATransposeb = A.TransposeThisAndMultiply(b); Vector<double> coefficients = ATransposeA.Solve(ATransposeb); return coefficients; } } ``` 在这个示例中,我们使用了MathNet.Numerics库来处理线性代数运算。你可以根据你的实际需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值