ValueError: X has 2 features, but LogisticRegression is expecting 5 features as input.
问题背景用python的sklearn库做逻辑回归模型训练后,用一些数值去预测结果时报错,已知是多项式的逻辑回归模型用的是二阶的边界函数画出来的抛物线代码如下pay1和pay2是用来预测y结果的,函数中的关键θ(用于计算x2)也提取出来了#边界函数参数获取theta0 = LR2.intercept_theta1,theta2,theta3,theta4,theta5 = LR2.coef_[0]
·
问题背景
用python的sklearn库做逻辑回归模型训练后,用一些数值去预测结果时报错,已知是多项式的逻辑回归模型
用的是二阶的边界函数画出来的抛物线
- 代码如下

pay1和pay2是用来预测y结果的,函数中的关键θ(用于计算x2)也提取出来了
#边界函数参数获取
theta0 = LR2.intercept_
theta1,theta2,theta3,theta4,theta5 = LR2.coef_[0][0],LR2.coef_[0][1],LR2.coef_[0][2],LR2.coef_[0][3],LR2.coef_[0][4]
print(theta0,theta1,theta2,theta3,theta4,theta5)

参照该图需要输出新的x2
a = theta4
b = theta5*X1_new + theta2
c = theta0+theta1*X1_new+theta3*X1_new*X1_new
x2_new_2 = (-b+np.sqrt(b*b-4*a*c))/(2*a)
print(x2_new_2)

在预测时出错了
# 预测
x_test = np.array([[80,20]])
# 第二个模型预测
y_predict = LR2.predict(x_test)
print(y_predict)
ValueError: X has 2 features, but LogisticRegression is expecting 5 features as input.
问题解决
原因是使用二阶函数计算时,其实需要放入的不仅仅是pay1和pay2这两个数这么简单了,除了x1和x2,还要输入x1x1、x2x2、x1*x2这5个数才可以
# 预测
x_test = np.array([[80,20,80*80,20*20,80*20]])
# 第二个模型预测
y_predict = LR2.predict(x_test)
print(y_predict)
输出成功
更多推荐


所有评论(0)