使用来自 Pickle 的训练模型

数据挖掘 机器学习 线性回归 泡菜
2022-02-28 08:41:59

我训练并保存了一个模型,该模型应该根据父亲的身高预测儿子的身高。然后我将模型保存到 Pickle。我现在可以加载模型并想使用它,但不幸的是,我需要第二个变量(除了父亲的身高)我认为我在训练模型时做错了什么?

我将发布我认为错误所在的代码部分,请询问您是否需要更多。

#Spliting the data into test and train data
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)

#Doing a linear regression
lm=LinearRegression()
lm.fit(X_train,y_train)

#testing the model with an example value
TestValue = 65.0
filename = 'Father_Son_Height_Model.pckl'
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.predict(TestValue)
print(result)

错误消息说:

ValueError:预期的 2D 数组,得到了标量数组:

数组=65.0。

如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1) 。

提前非常感谢。

1个回答

你需要使用loaded_model.predict(TestValue),而不是loaded_model.score(TestValue)后者用于评估模型的准确性,您还需要传递儿子的真实身高,这是y它要求的值。