Mar*_*ier 7 python numpy machine-learning linear-regression
我没有看到我的正则线性回归代码出了什么问题.不合规我只是这个,我有理由肯定是正确的:
import numpy as np
def get_model(features, labels):
return np.linalg.pinv(features).dot(labels)
Run Code Online (Sandbox Code Playgroud)
这是我的规范化解决方案的代码,我没有看到它有什么问题:
def get_model(features, labels, lamb=0.0):
n_cols = features.shape[1]
return linalg.inv(features.transpose().dot(features) + lamb * np.identity(n_cols))\
.dot(features.transpose()).dot(labels)
Run Code Online (Sandbox Code Playgroud)
对于lamb的默认值为0.0,我的意图是它应该给出与(正确的)非正规化版本相同的结果,但差异实际上非常大.
有谁看到问题是什么?
问题是:
features.transpose().dot(features)
可能不可逆转.numpy.linalg.inv仅适用于根据文档的全秩矩阵.然而,(非零)正则化项总是使方程非奇异.
顺便说一句,你对实施是正确的.但效率不高.解决该等式的有效方法是最小二乘法.
np.linalg.lstsq(features, labels)
可以做的工作np.linalg.pinv(features).dot(labels)
.
一般来说,你可以这样做
def get_model(A, y, lamb=0):
n_col = A.shape[1]
return np.linalg.lstsq(A.T.dot(A) + lamb * np.identity(n_col), A.T.dot(y))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7366 次 |
最近记录: |