Python中的OLS:估计系数矩阵的维数不合适

时间:2018-04-12 22:06:19

标签: python numpy

我编写了一个Python代码来估算(单变量)线性回归模型中的参数,但估计系数矩阵的维数并不合适。向量的维度' beta_estimated' (下面报道)应该是(1乘1)但是(n-by-n)。任何一个人?

# Linear regression in Python (univariate)
import numpy as np     
import scipy as sci     

x_original  =  np.random.normal(1,1, 100)    
x = np.array([x_original])    
#x_transpose  = x.T                 
beta = [5]  

y_original = (beta * x) + np.random.normal(0, 10, 100)    
y = np.array(y_original)    
#y_transpos = y.T     
product1 = np.dot(x.T, x)    
product2 = np.dot(x.T, y )    
Minv = np.linalg.inv(product1)    
beta_estimated =  np.dot(Minv, product2)

1 个答案:

答案 0 :(得分:1)

我不确定你想做什么,但如果我不得不猜测产品是你没有所需尺寸的原因。在你的情况下:

x   # has a shape of (1, 100)
x.T # has a shape of (100, 1)

np.dot(x.T, x) # produces an array with shape (100, 100)
np.dot(x, x.T) # would produce an array with a shape of (1, 1) 

因此,如果我认为您应该反转两个点积np.dot()中的参数。您的代码应该成为:

product1 = np.dot(x, x.T)    
product2 = np.dot(y, x.T)