Python线性回归模型预测并优化:使用SciPy寻找最大值
使用Python线性回归模型预测并优化:使用SciPy寻找最大值
本示例展示了如何使用Python的Scikit-learn库构建线性回归模型,并使用SciPy的optimize模块寻找预测值y在特定范围内最大值,并给出相应的X矩阵。
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)
data
x = data[['接收距离(cm)', '热风速度(r/min)', '厚度mm', '孔隙率(%)', '压缩回弹性率(%)', '过滤阻力Pa','透气性 mm/s']]
y = data['过滤效率(%)']
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)
pd.DataFrame(x_poly).head()
x_train2, x_test2, y_train2, y_test2 = train_test_split(x_poly, y, test_size=0.2, random_state=1)
reg2 = LR().fit(x_train2, y_train2)
yhat2 = reg2.predict(x_test2)
yhat2
print(reg2.coef_)
print(reg2.intercept_)
#可视化
t = np.arange(len(x_test2))
plt.plot(t, y_test2, 'r-', linewidth=2, label='Actual')
plt.plot(t, yhat2, 'g-', linewidth=2, label='Predicted')
plt.title('Actual test y & Predicted test y')
plt.legend(loc='upper right')
plt.grid()
plt.show()
from scipy.optimize import minimize_scalar
# 定义目标函数
def objective_function(x):
# 构建X矩阵
x_matrix = np.array([x])
x_poly_matrix = po.transform(x_matrix)
# 预测y值
y_pred = reg2.predict(x_poly_matrix)
return -y_pred[0] # 最大化y值,因此返回-y_pred
# 最大化目标函数
result = minimize_scalar(objective_function, bounds=(0, 100), method='bounded')
# 输出最大化y值和对应的X矩阵内容
max_y = -result.fun
x_max = result.x
x_matrix_max = np.array([x_max])
x_poly_matrix_max = po.transform(x_matrix_max)
print('最大化y值:', max_y)
print('对应的X矩阵内容:', x_poly_matrix_max)
代码解释:
- 导入必要的库: 首先,我们导入NumPy、Matplotlib、Pandas、Scikit-learn和SciPy库,这些库将在我们的代码中使用。
- 加载数据: 我们从名为'C题数据.xlsx'的Excel文件中加载数据,并将其存储在名为'data'的Pandas DataFrame中。
- 数据预处理: 我们将数据划分为特征矩阵'x'和目标变量'y',并使用PolynomialFeatures类对特征矩阵进行多项式特征转换。
- 构建线性回归模型: 我们使用LinearRegression类构建线性回归模型,并使用训练数据进行训练。
- 使用SciPy优化模型: 我们定义一个名为objective_function的目标函数,该函数返回预测的y值。然后,我们使用SciPy的minimize_scalar函数在0到100的范围内最大化目标函数,并输出最大化y值和对应的X矩阵。
- 结果展示: 最后,我们打印出最大化y值和对应的X矩阵。
注意事项:
- 代码中的'C题数据.xlsx'需要替换为实际的Excel文件名称。
- 代码中的特征列名需要根据实际情况进行调整。
- 代码中的'bounds'参数表示目标函数的最大化范围。
结论:
通过使用SciPy的optimize模块,我们可以有效地找到线性回归模型预测值y在特定范围内最大值,并给出相应的X矩阵。这对于优化模型预测结果和找到最佳特征值组合非常有用。
原文地址: https://www.cveoy.top/t/topic/fOjy 著作权归作者所有。请勿转载和采集!