错误提示是:Expected 2D array, got 1D array instead。

问题出在 objective_function 函数中,x_matrix 是一个一维数组,而 PolynomialFeatures.transform 方法需要接收一个二维数组作为输入。

解决方法是将 x_matrix 转换为二维数组,可以使用 reshape 方法实现:

x_matrix = np.array([x]).reshape(1, -1)

修改后的代码如下:

import numpy as np
from scipy.optimize import minimize_scalar
from sklearn.preprocessing import PolynomialFeatures

# 构建X矩阵
X = np.array([[ 0.        ],
              [ 5.55555556],
              [11.11111111],
              [16.66666667],
              [22.22222222],
              [27.77777778],
              [33.33333333],
              [38.88888889],
              [44.44444444],
              [50.        ]])

# 构建y矩阵
y = np.array([ 0.        ,  7.94328235, 10.        ,  9.23871968,  7.94328235,
              6.34960421,  5.62341325,  5.62341325,  6.34960421,  7.94328235])

# 创建多项式特征对象
po = PolynomialFeatures(degree=2, include_bias=False)
# 对X矩阵进行多项式转换
X_poly = po.fit_transform(X)

# 创建线性回归对象
reg2 = LinearRegression()
# 训练模型
reg2.fit(X_poly, y)

def objective_function(x):
    # 构建X矩阵
    x_matrix = np.array([x]).reshape(1, -1)
    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
max_x = result.x
print("最大化的y值:", max_y)
print("对应的X值:", max_x)

这样就能够成功运行并输出结果了。

ValueError Traceback most recent call lastCell In61 line 13 10 return -y_pred0 # 最大化y值因此返回-y_pred 12 # 最大化目标函数--- 13 result = minimize_scalarobjective_funct

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

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