使用Python numpy进行线性回归 [英] Linear Regression with Python numpy

查看:229
本文介绍了使用Python numpy进行线性回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的线性回归函数,但仍然遇到

I'm trying to make a simple linear regression function but continue to encounter a

numpy.linalg.linalg.LinAlgError:奇异矩阵错误

numpy.linalg.linalg.LinAlgError: Singular matrix error

现有功能(带有调试打印):

Existing function (with debug prints):

def makeLLS(inputData, targetData):
    print "In makeLLS:"
    print "    Shape inputData:",inputData.shape
    print "    Shape targetData:",targetData.shape
    term1 = np.dot(inputData.T, inputData)
    term2 = np.dot(inputData.T, targetData)
    print "    Shape term1:",term1.shape
    print "    Shape term2:",term2.shape
    #print term1
    #print term2
    result = np.linalg.solve(term1, term2)
    return result

包含我的测试数据的控制台输出为:

The output to the console with my test data is:

In makeLLS:
    Shape trainInput1: (773, 10)
    Shape trainTargetData: (773, 1)
    Shape term1: (10, 10)
    Shape term2: (10, 1)

然后在linalg.solve行上出错.这是一本教科书的线性回归函数,我似乎无法弄清楚为什么它会失败.

Then it errors on the linalg.solve line. This is a textbook linear regression function and I can't seem to figure out why it's failing.

什么是奇异矩阵误差?

推荐答案

如另一个答案中所述,linalg.solve需要一个完整的秩矩阵.这是因为它尝试求解矩阵方程,而不是进行适用于所有等级的线性回归.

As explained in the other answer linalg.solve expects a full rank matrix. This is because it tries to solve a matrix equation rather than do linear regression which should work for all ranks.

有几种线性回归方法.我建议的最简单的方法是标准最小二乘法.只需使用numpy.linalg.lstsq即可.包含示例的文档位于此处.

There are a few methods for linear regression. The simplest one I would suggest is the standard least squares method. Just use numpy.linalg.lstsq instead. The documentation including an example is here.

这篇关于使用Python numpy进行线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆