【发布时间】:2022-01-02 05:33:56
【问题描述】:
我是 Python 新手。我正在尝试通过使用此 CSV 进行 DataCamp 练习来练习基本的正则化: https://assets.datacamp.com/production/repositories/628/datasets/a7e65287ebb197b1267b5042955f27502ec65f31/gm_2008_region.csv
# Import numpy and pandas
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Read the CSV file into a DataFrame: df
df = pd.read_csv('gm_2008_region.csv')
# Create arrays for features and target variable
X = df.drop(['life','Region'], axis=1)
y = df['life'].values.reshape(-1,1)
df_columns = df.drop(['life','Region'], axis=1).columns
我用于 DataCamp 练习的代码如下:
# Import Lasso
from sklearn.linear_model import Lasso
# Instantiate a lasso regressor: lasso
lasso = Lasso(alpha=0.4, normalize=True)
# Fit the regressor to the data
lasso.fit(X, y)
# Compute and print the coefficients
lasso_coef = lasso.coef_
print(lasso_coef)
# Plot the coefficients
plt.plot(range(len(df_columns)), lasso_coef)
plt.xticks(range(len(df_columns)), df_columns.values, rotation=60)
plt.margins(0.02)
plt.show()
我得到上面的输出,表明 child_mortality 是预测预期寿命的最重要特征,但是由于使用了“normalize”,这段代码也导致了弃用警告。
我想使用当前的最佳做法更新此代码。我尝试了以下方法,但得到了不同的输出。我希望有人可以帮助确定我需要在更新的代码中修改什么以产生相同的输出。
# Modified based on https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-scaler
# and https://stackoverflow.com/questions/28822756/getting-model-attributes-from-pipeline
# Import Lasso
from sklearn.linear_model import Lasso
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
# Instantiate a lasso regressor: lasso
#lasso = Lasso(alpha=0.4, normalize=True)
pipe = Pipeline(steps=[
('scaler',StandardScaler()),
('lasso',Lasso(alpha=0.4))
])
# Fit the regressor to the data
#lasso.fit(X, y)
pipe.fit(X, y)
# Compute and print the coefficients
#lasso_coef = lasso.coef_
#print(lasso_coef)
lasso_coef = pipe.named_steps['lasso'].coef_
print(lasso_coef)
# Plot the coefficients
plt.plot(range(len(df_columns)), lasso_coef)
plt.xticks(range(len(df_columns)), df_columns.values, rotation=60)
plt.margins(0.02)
plt.show()
如您所见,我得出了相同的结论,但如果输出图像更相似,我会更自在地正确执行此操作。我在管道上做错了什么?
【问题讨论】:
-
有趣的是
intercept_也不同。顺便说一句,你不需要用lasso_coef = lasso.fit(X, y).coef_重新计算,lasso_coef = lasso.coef_就足够了。
标签: python scikit-learn pipeline lasso-regression regularized