gpt4 book ai didi

python - 如何重现 Ridge(normalize=True) 的行为?

转载 作者:行者123 更新时间:2023-12-05 05:34:56 28 4
gpt4 key购买 nike

这段代码:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge

X = 'some_data'
y = 'some_target'

penalty = 1.5e-5
A = Ridge(normalize=True, alpha=penalty).fit(X, y)

触发以下警告:

FutureWarning: 'normalize' was deprecated in version 1.0 and will be removed in 1.2.
If you wish to scale the data, use Pipeline with a StandardScaler in a preprocessing stage. To reproduce the previous behavior:

from sklearn.pipeline import make_pipeline

- model = make_pipeline(StandardScaler(with_mean=False), Ridge())

If you wish to pass a sample_weight parameter, you need to pass it as a fit parameter to each step of the pipeline as follows:
kwargs = {s[0] + '__sample_weight': sample_weight for s in model.steps}
model.fit(X, y, **kwargs)

Set parameter alpha to: original_alpha * n_samples.
warnings.warn(
Ridge(alpha=1.5e-05)

但是这些代码给了我完全不同的系数,正如预期的那样,因为归一化和标准化是不同的。

B = make_pipeline(StandardScaler(with_mean=False), Ridge(alpha=penalty))
B[1].fit(B[0].fit_transform(X), y)

输出:

A.coefs[0], B[1].coefs[0]
(124.87330648168594, 125511.75051106009)

如果我设置 alpha = penalty * n_features 结果仍然不匹配。

输出:

A.coefs[0], B[1].coefs[0]
(124.87330648168594, 114686.09835548172)

尽管 Ridge() 使用的归一化与我预期的有点不同:

the regressor X will be normalized by subtracting mean and dividing byl2-norm

那么使用带归一化的岭回归的正确方法是什么?
考虑到 l2-norm 看起来像是预测后得到的,数据再次修改和拟合
在使用 sklearn 的岭回归的情况下,我没有想到任何事情,尤其是在 1.2 版本之后


准备 data用于实验:

url = 'https://drive.google.com/file/d/1bu64NqQkG0YR8G2CQPkxR1EQUAJ8kCZ6/view?usp=sharing'
url = 'https://drive.google.com/uc?id=' + url.split('/')[-2]
data = pd.read_csv(url, index_col=0)

X = data.iloc[:,:15]
y = data['target']

最佳答案

不同之处在于,使用normalize=True 报告的系数将直接应用于未缩放的输入,而流水线方法将其系数应用于模型的输入,哪些是缩放后的特征。

您可以通过乘以/除以特征的标准差来“归一化”(不幸的是该词重载)系数。连同 future 警告中建议的惩罚更改,我得到了相同的输出:

np.allclose(A.coef_, B[1].coef_ / B[0].scale_)
# True

(我已经使用 sklearn.datasets.load_diabetes 进行了测试。)

关于python - 如何重现 Ridge(normalize=True) 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73583687/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com