Don*_*beo 2 regression scikit-learn
众所周知,当变量(p)的数量大于样本数量(n)时,未定义最小二乘估计量.
在sklearn中,我收到了以下值:
In [30]: lm = LinearRegression().fit(xx,y_train)
In [31]: lm.coef_
Out[31]:
array([[ 0.20092363, -0.14378298, -0.33504391, ..., -0.40695124,
0.08619906, -0.08108713]])
In [32]: xx.shape
Out[32]: (1097, 3419)
Run Code Online (Sandbox Code Playgroud)
调用[30]应该返回错误.在这种情况下,当p> n时,sklearn如何工作?
编辑:似乎矩阵充满了一些值
if n > m:
# need to extend b matrix as it will be filled with
# a larger solution matrix
if len(b1.shape) == 2:
b2 = np.zeros((n, nrhs), dtype=gelss.dtype)
b2[:m,:] = b1
else:
b2 = np.zeros(n, dtype=gelss.dtype)
b2[:m] = b1
b1 = b2
Run Code Online (Sandbox Code Playgroud)
当线性系统不确定时,则sklearn.linear_model.LinearRegression找到最小L2范数解,即
argmin_w l2_norm(w) subject to Xw = y
Run Code Online (Sandbox Code Playgroud)
通过应用Xto 的伪逆y,即,总是很好地定义和获得
w = np.linalg.pinv(X).dot(y)
Run Code Online (Sandbox Code Playgroud)
用法使用的具体实现scipy.linalg.lstsq,它恰好是通过奇异值分解找到最小范数解的求解器(由LAPACK提供).LinearRegressionget_lapack_funcs(('gelss',), ...
看看这个例子
import numpy as np
rng = np.random.RandomState(42)
X = rng.randn(5, 10)
y = rng.randn(5)
from sklearn.linear_model import LinearRegression
lr = LinearRegression(fit_intercept=False)
coef1 = lr.fit(X, y).coef_
coef2 = np.linalg.pinv(X).dot(y)
print(coef1)
print(coef2)
Run Code Online (Sandbox Code Playgroud)
你会看到的coef1 == coef2.(注意,这fit_intercept=False是在sklearn估计器的构造函数中指定的,否则它会在拟合模型之前减去每个特征的平均值,从而产生不同的系数)
| 归档时间: |
|
| 查看次数: |
1385 次 |
| 最近记录: |