0

好的,这是我使用 c# 和 MathNet 计算 Normal Equation 的代码:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearRegression;
using MathNet.Numerics.LinearAlgebra.Double;

namespace ConsoleApplication1
{
    public class NormalEquation
    {
        public void Calc()
        {
            var xData = new double[4, 5]{{1, 2104, 5,1,45}, {1, 1416,3,2,40}, {1,1534,3,2,30},{1,852,2,1,36}};

            var yData = new double[4, 1] { { 460 }, { 232 }, { 315 }, { 178 } };

            Matrix<double> X = Matrix<double>.Build.DenseOfArray(xData);

            Matrix<double> Y = Matrix<double>.Build.DenseOfArray(yData);

            var beta = X.Transpose().Multiply(X).Inverse().Multiply(X.Transpose().Multiply(Y));

            foreach (double d in beta.Enumerate())
            {
                Console.WriteLine("{0}\t", d);
            }
        }
    }

    class Program
    {
        static void Main()
        {

            NormalEquation n = new NormalEquation();
            n.Calc();
        }
    }
}

还有我的八度:

X=[1 2104 5 1 45; 1 1416 3 2 40;1 1534 3 2 30; 1 852 2 1 36 ]
y=[460; 232; 315; 178]
beta= pinv(X'*X)*(X'*y)

谁能帮我理解为什么会这样-

MathNet 结果为: beta = {240, 0.125, 96, -56, -9}

八度结果为: beta ={ 188.40032, 0.38663, -56.13825, -92.96725,-3.73782}

4

1 回答 1

0

方阵X'*X几乎是奇异的。输入

X=[1 2104 5 1 45; 1 1416 3 2 40;1 1534 3 2 30; 1 852 2 1 36 ];
det(X'*X)

产量

ans =   3.4192e-007
于 2015-04-28T10:15:18.363 回答