【发布时间】:2022-01-12 01:46:19
【问题描述】:
我正在尝试标准化特征,然后运行岭回归。
正如所提供的,这两个答案是不同的。
当我设置 ridge=0 时,答案是一样的。当我删除 StandardScaler 和 Dn 时,答案也是一样的。
我不知道如何协调这两个版本(原始版本和使用 sklearn)。
感谢您的帮助
from sklearn.linear_model import Ridge
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import numpy as np
np.random.seed(0)
x = np.random.randn(100, 3)
y = np.random.randn(100, 2)
xx = x.T @ x
xy = x.T @ y
Dn = np.diag(1 / np.sqrt(np.diag(xx)))
ridge = 1
xx = Dn @ xx @ Dn
xy = Dn @ xy
beta_raw = Dn @ np.linalg.solve(xx + np.eye(len(xx)) * ridge, xy)
f_raw = x @ beta_raw
model = Pipeline([("scaler", StandardScaler(with_mean=False)), ("regression", Ridge(ridge, fit_intercept=False))])
trained_model = model.fit(x, y)
f_ml = trained_model.predict(x)
print(f_ml[:3] / f_raw[:3])
【问题讨论】:
标签: python numpy scikit-learn