简体   繁体   English

Python最小二乘回归QS

[英]Python least squares regression qs

Why doesn't this code work? 为什么此代码不起作用? I am trying to do multi-variate regression. 我正在尝试进行多元回归。 Four equations of the form: 形式的四个方程式:

Ax + By + c = d

A + 2B + C = 0.2 etc.

A = np.array([[ 0.,  1, 1.],
   [ 1.,  2, 1.],
   [ 2.,  3, 1.],
   [ 3.,  4, 1.]])

y = np.array([-1, 0.2, 0.9, 2.1])
m, c = np.linalg.lstsq(A, y)[0]
print m, c

What am I doing wrong? 我究竟做错了什么?

I assume that you took m, c = np.linalg.lstsq(A, y)[0] line from the lstsq example . 我假设您从lstsq 示例中 m, c = np.linalg.lstsq(A, y)[0]m, c = np.linalg.lstsq(A, y)[0]行。
In the example they are solving linear regression problem with one variable and constant. 在示例中,他们正在解决具有一个变量和常数的线性回归问题。 As the result, np.linalg.lstsq(A, y) for this problem returns four-element tuple (array([ 1. , -0.95]), array([ 0.05]), 2, array([ 4.10003045, 1.09075677])) (first element – solution, second – residuals, third – the coefficient matrix rank, last element – singular values of coefficient matrix). 结果,此问题的np.linalg.lstsq(A, y)返回四元素元组(array([ 1. , -0.95]), array([ 0.05]), 2, array([ 4.10003045, 1.09075677])) (第一个元素-解,第二个-残差,第三个-系数矩阵秩,最后一个元素-系数矩阵的奇异值)。 So, np.linalg.lstsq(A, y)[0] (in the example) returns array with two elements which can be unpacked the way they are doing it: m, c = np.linalg.lstsq(A, y)[0] ( m = 1., c = -0.95 ). 因此, np.linalg.lstsq(A, y)[0] (在示例中)返回带有两个元素的数组,这些元素可以m, c = np.linalg.lstsq(A, y)[0]执行的方式拆包: m, c = np.linalg.lstsq(A, y)[0]m = 1., c = -0.95 )。

You are solving regression with two variables and constant. 您正在使用两个变量和常量求解回归。 Therefore, np.linalg.lstsq(A, y)[0] will return array with three elements and if you want to unpack it the way it was in the example you can do it this way: 因此, np.linalg.lstsq(A, y)[0]将返回包含三个元素的数组,如果您要按照示例中的方式进行拆包,则可以这样操作:

x1, x2, c = np.linalg.lstsq(A, y)[0]

But more convenient way would be (in my opinion): 但更方便的方法是(我认为):

x, residuals, rank, s = np.linalg.lstsq(A, y) #lstsq func always return four-element tuple

print 'solution is %s.' % str(x)
print 'matrix A rank is %d.' % rank
print 'residuals are %s.' % str(residuals)
print 'singular values of A are %s.' % str(s)

print 'first variable is %f.' % x[0]
print 'second variable is %f.' % x[1]
print 'constant is %f.' % x[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM