【发布时间】:2021-11-03 01:29:31
【问题描述】:
我正在使用线性回归模型来预测降雨量。
dfx = df1[['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL',
'AUG', 'SEP', 'OCT', 'NOV', 'DEC']]
dfy=df1['ANNUAL']
X_train, X_test, y_train, y_test = train_test_split(dfx, dfy, test_size=0.2, random_state=0)
x 是 12 个月的降雨量,y 是年降雨量,是 12 个月的总和。
当我使用以下代码运行线性回归时。
#create a linear regression model
regressor = LinearRegression()
# fitting the model
regressor.fit(X_train, y_train)
#predicting response
y_pred = regressor.predict(X_test)
testScore = math.sqrt(mean_squared_error(y_test,y_pred))
print('testScore: %.2f RMSE' % (testScore))
print('R2 SCORE:', r2_score(y_test, y_pred))
我得到了 testScore: 0.11 RMSE 和 R2 SCORE: 0.9999999338525851。
所以为了获得更好的结果,我使用代码进行了 L1 和 L2 正则化。
##create a Ridge model
rdf = Ridge(alpha = .5)
## create Lasso model
lrf = Lasso(alpha = .5)
对于岭和套索,我得到与线性回归相同的 R2,即 0.99。 对于山脊,我的 RMSE 为 0.11,而 Lasso 的 RMSE 为 0.13。
再次改进模型,我在 Ridge 和 Lasso 中添加了超参数调整
对于山脊:
# creating a dictionary containing potential values of alpha
alpha_values = {'alpha':[0.0001,0.001, 0.01,0.02,0.03,0.04, 0.05, 0.06, 0.08, 1, 2, 3, 5, 8, 10, 20, 50, 100]}
# Passing in a Ridge estimator, potential alpha values, scoring method and cross validation parameters to the GridSearchCV
ridge= GridSearchCV(Ridge(), alpha_values, cv=10 )
# Fitting the model to the data and extracting best value of alpha
print('The best value of alpha is:',ridge.fit(X_train, y_train).best_params_)
将 alpha 设为 0.0001 以得到相同的结果。 Lasso 也是如此
如何改进这些模型
【问题讨论】:
标签: python linear-regression lasso-regression