【发布时间】:2019-06-12 04:47:26
【问题描述】:
我正在学习 statsmodels.api 模块以使用 python 进行回归分析。所以我从简单的OLS模型开始。
在计量经济学中,函数类似于:y = Xb + e 其中X是NxK维度,b是Kx1,e是Nx1,所以将y加在一起是Nx1。从线性代数的角度来看,这完全没问题。
但我按照 Statsmodels 的教程如下:
import numpy as np
nsample = 100 # total obs is 100
x = np.linspace(0, 10, 100) # using np.linspace(start, stop, number)
X = np.column_stack((x, x**2))
beta = np.array([1, 0.1, 10])
e = np.random.normal(size = nsample) # draw numbers from normal distribution
default at mu = 0, and std.dev = 1, size = set by user
# e is n x 1
# Now, we add the constant/intercept term to X
X = sm.add_constant(X)
# Now, we compute the y
y = np.dot(X, beta) + e
所以这会产生正确的答案。但是我对 beta = np.array([1,0.1,10]) 的生成有疑问。这个测试版,如果我们使用:
beta.shape
(3,)
它的维度是(3,),除了X之外,y和e也一样:
X.shape
(100,3)
e.shape
(100,)
y.shape
(100,)
所以我猜测使用以下三种方式来初始化数组
o = array([1,2,3])
o1 = array([[1],[2],[3]])
o2 = array([[1,2,3]])
print(o.shape)
print(o1.shape)
print(o2.shape)
----------------
(3,)
(3, 1)
(1, 3)
如果我使用 beta = array([[1],[2],[3]]),它是 (3,1),并且 np.dot(X, beta) 得到了错误的答案,尽管维度似乎有效。 如果我使用 array([[1,2,3]]),它是一个行向量,那么在 numpy 中,维度与点积不匹配,在线性代数中也不匹配。
所以,我想知道为什么对于 NxK 点 Kx1 numpy 点积,我们必须使用 (N,K) 点 (K,) 而不是 (N,K) 点 (K,1) 矩阵。什么操作只使 np.array([1, 0.1, 10]) 适用于 numpy.dot() 而 np.array([[1], [0.1], [10]]) 不适用。
非常感谢。
一些更新
抱歉,Statsmodels 中的代码是随机生成的,所以我尝试修复 X 并获得以下输入:
f = array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]])
o = array([1,2,3])
o1 = array([[1],[2],[3]])
o2 = array([[1,2,3]])
print(o.shape)
print(o1.shape)
print(o2.shape)
print("---------")
print(np.dot(f,o))
print(np.dot(f,o1))
r1 = np.dot(f,o)
r2 = np.dot(f,o1)
type1 = type(np.dot(f,o))
type2 = type(np.dot(f,o1))
tf = type1 is type2
tf2 = type1 == type2
print(type1)
print(type2)
print(tf)
print(tf2)
-------------------------
(3,)
(3, 1)
(1, 3)
---------
[14 32 50 68 86]
[[14]
[32]
[50]
[68]
[86]]
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
True
True
再次为给您带来的困惑和不便深表歉意,他们工作得很好。
【问题讨论】:
-
e不是 1xn。 1xn 意味着e是二维的。 -
dot给你正确的答案。dot不是问题。 -
哦,这是代码中的错字,对不起,我会更正它。
-
哦,它应该给出相同的答案,但一个在 [x,y] 中,另一个在 [[x],[y]] 中。
-
当来自计量经济学(和 MATLAB)时,请注意
numpy也有“真正的”一维数组,形状为 (n,)(这是一个单元素元组)。 (1,n) 和 (n,1) 是不同的形状。
标签: python arrays numpy linear-regression linear-algebra