# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import Lasso, Ridge, LinearRegression as LR
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import r2_score, explained_variance_score as EVS, mean_squared_error as MSE


# 加载数据
data = pd.read_excel('C题数据.xlsx', sheet_name=2)

x = data[['接收距离(cm)', '热风速度(r/min)', '厚度mm', '孔隙率(%)', '压缩回弹性率(%)', '过滤阻力Pa','透气性 mm/s']]
y = data['过滤效率(%)']

# 使用 PolynomialFeatures 生成多项式特征
from sklearn.preprocessing import PolynomialFeatures   #StandardScaler

#degree 表示多项式的维度,即^2, interaction_only表示是否仅使用a*b, include_bias表示是否添加一列全部等于1的偏置项
po = PolynomialFeatures(degree=2, interaction_only=False, include_bias=False)
x_poly = po.fit_transform(x)

# 将数据划分成训练集和测试集
x_train2, x_test2, y_train2, y_test2 = train_test_split(x_poly, y, test_size=0.2, random_state=1)

# 使用 LinearRegression 模型进行训练
reg2 = LR().fit(x_train2, y_train2)

# 使用 GridSearchCV 寻找最佳参数
# 定义参数范围
param_grid = {'alpha': np.logspace(-4, 4, 9)}

# 创建Lasso模型
lasso = Lasso(max_iter=10000)

# 使用GridSearchCV寻找最佳参数
grid_search = GridSearchCV(lasso, param_grid, cv=5, scoring='r2')
grid_search.fit(x_poly, y)

# 输出最佳参数和对应的分数
print('Best Parameters: ', grid_search.best_params_)
print('Best Score: ', grid_search.best_score_)

# 使用最佳参数重新训练模型
reg = Lasso(alpha=grid_search.best_params_['alpha'], max_iter=10000)
reg.fit(x_poly, y)

# 输出最大预测值和对应的X矩阵内容
max_y = np.max(reg.predict(x_poly))
max_x = x[np.argmax(reg.predict(x_poly))]

print('Max Predicted y: ', max_y)
print('Corresponding X: ', max_x)

注意:上述代码假设使用Lasso模型,并使用R2评分进行模型选择。如果需要使用Ridge模型或其他评分指标,请相应修改代码。

Python 过滤效率预测模型:使用 GridSearchCV 寻找最佳参数和最大预测值

原文地址: https://www.cveoy.top/t/topic/fOhk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录