您必须除以用于标准化特征的缩放比例,还要乘以应用于目标的缩放比例。
认为
然后
orig_coef_i = coef_i_found_on_scaled_data / scale_x_i * scale_y
这是一个使用 pandas 和 sklearn LinearRegression 的示例
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
import numpy as np
import pandas as pd
boston = load_boston()
# Looking at the description of the data tells us the target variable name
# print boston.DESCR
data = pd.DataFrame(
data = np.c_[boston.data, boston.target],
columns = list(boston.feature_names) + ['MVAL'],
)
data.head()
X = boston.data
y = boston.target
lr = LinearRegression()
lr.fit(X,y)
orig_coefs = lr.coef_
coefs1 = pd.DataFrame(
data={
'feature': boston.feature_names,
'orig_coef' : orig_coefs,
}
)
coefs1
这向我们展示了没有应用缩放的线性回归的系数。
# | feature| orig_coef
# 0| CRIM | -0.107171
# 1| ZN | 0.046395
# 2| INDUS | 0.020860
# etc
我们现在标准化所有变量
# Now we normalise the data
scalerX = StandardScaler().fit(X)
scalery = StandardScaler().fit(y.reshape(-1,1)) # Have to reshape to avoid warnings
normed_X = scalerX.transform(X)
normed_y = scalery.transform(y.reshape(-1,1)) # Have to reshape to avoid warnings
normed_y = normed_y.ravel() # Turn y back into a vector again
# Check it's worked
# print np.mean(X, axis=0), np.mean(y, axis=0) # Should be 0s
# print np.std(X, axis=0), np.std(y, axis=0) # Should be 1s
我们可以对这个标准化数据再次进行回归...
# Now we redo our regression
lr = LinearRegression()
lr.fit(normed_X, normed_y)
coefs2 = pd.DataFrame(
data={
'feature' : boston.feature_names,
'orig_coef' : orig_coefs,
'norm_coef' : lr.coef_,
'scaleX' : scalerX.scale_,
'scaley' : scalery.scale_[0],
},
columns=['feature', 'orig_coef', 'norm_coef', 'scaleX', 'scaley']
)
coefs2
...并应用缩放来取回我们的原始系数
# We can recreate our original coefficients by dividing by the
# scale of the feature (scaleX) and multiplying by the scale
# of the target (scaleY)
coefs2['rescaled_coef'] = coefs2.norm_coef / coefs2.scaleX * coefs2.scaley
coefs2
当我们这样做时,我们看到我们已经重新创建了原始系数。
# | feature| orig_coef| norm_coef| scaleX| scaley| rescaled_coef
# 0| CRIM | -0.107171| -0.100175| 8.588284| 9.188012| -0.107171
# 1| ZN | 0.046395| 0.117651| 23.299396| 9.188012| 0.046395
# 2| INDUS | 0.020860| 0.015560| 6.853571| 9.188012| 0.020860
# 3| CHAS | 2.688561| 0.074249| 0.253743| 9.188012| 2.688561
对于某些机器学习方法,目标变量 y 必须与特征变量 x 一样进行归一化。如果你已经这样做了,你需要包括这个“乘以 y 的比例”步骤以及“除以 X_i 的比例”来取回原始回归系数。
希望有帮助