[英]How can I extract the alpha that gives me the lowest Mean Squared Error from the lasso regression that loops through multiple alphas?
I am attempting to find the optimal combination of x values, their respective exponent's, and the alpha that will allow me to find the lowest mean squared error.我试图找到 x 值、它们各自的指数和 alpha 的最佳组合,这将使我能够找到最低的均方误差。
I used a Lasso regression from SKlearn, but so far I am only able to determine the minimum MSE, and the variable combination that creates it.我使用了 SKlearn 的套索回归,但到目前为止我只能确定最小 MSE,以及创建它的变量组合。 I am not sure how to pull the alpha out that allowed it, or how to see if the combinations of variables have any exponents associated with them.我不确定如何拉出允许它的 alpha,或者如何查看变量的组合是否有任何与它们相关的指数。
The results I achieved:我取得的结果:
outcomes from the Best Lasso Regression Model: minimum Avg Test MSE: 9172.38 The Combination of Variables: ['Date', 'Cargo_size', 'Parcel_size', 'Rest', 'Sub']最佳套索回归模型的结果:最小平均测试 MSE:9172.38 变量组合:['Date', 'Cargo_size', 'Parcel_size', 'Rest', 'Sub']
x_combos = []
for n in range(1,9):
combos = combinations(['Date', 'Cargo_size', 'Parcel_size', 'Rest', 'Age',\
'Sub', 'X_coord', 'Y_coord'], n)
x_combos.extend(combos)
lasso_models = {}
alphas = 10**np.linspace(10,-2, 100)*.5
for n in range(0, len(x_combos)):
combo_list = list(x_combos[n])
x = data[combo_list]
poly = PolynomialFeatures(3)
poly_x = poly.fit_transform(x)
model = Lasso(max_iter=100000, normalize=(True))
for a in alphas:
model.set_params(alpha = a)
model.fit(poly_x,y) #
lasso_cv_scores = cross_validate(model, poly_x, y, cv=10, scoring=('neg_mean_squared_error', 'r2'), return_train_score=(True), return_estimator=(True))
lasso_models[str(combo_list)] = np.mean(lasso_cv_scores['test_neg_mean_squared_error'])
print("outcomes from the Best Lasso Regression Model:")
min_mse = abs(max(lasso_models.values()))
print("minimum Avg Test MSE:", min_mse.round(2))
for possibles, i in lasso_models.items():
if i == -min_mse:
print("The Combination of Variables:", possibles)
You can perform this operation with GridSearchCV
which is an object that perform an exhaustive search over specified parameter values for an estimator.您可以使用GridSearchCV
执行此操作, GridSearchCV
是一个对象,可以对估计器的指定参数值执行详尽搜索。
As follows:如下:
from sklearn.model_selection import GridSearchCV
param_grid = { 'alpha' : alphas}
cv = GridSearchCV(model,
n_jobs=-1,
param_grid=param_grid,
cv=5,return_train_score=(True)
).fit(poly_x, y_train)
cv.best_params_
This snippet will perfrom an hyperparameter search over the alphas and return the best set of parameters.此代码段将在 alpha 上执行超参数搜索并返回最佳参数集。 Additionally you can return the best fitted model using cv.best_estimator_
.此外,您可以使用cv.best_estimator_
返回最佳拟合模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.