我有一个数据集,包含超过2000行和23列,包括age
列。我已经完成了SVR
的所有处理过程。现在我想在训练好的SVR模型上进行预测,需要将X_test
输入到模型中吗?我遇到了一个错误:
ValueError: X.shape[1] = 1 should be equal to 22, the number of features at training time
如何解决这个问题?我该如何编写代码来对训练好的SVR模型进行预测?
import pandas as pdimport numpy as np# 生成伪数据集dataset = pd.DataFrame(data= np.random.rand(2000,22))dataset['age'] = np.random.randint(2, size=2000)# 分离目标变量和其它特征target = dataset['age']data = dataset.drop('age', axis = 1)X_train, y_train = data.loc[:1000], target.loc[:1000]X_test, y_test = data.loc[1001], target.loc[1001] X_test = np.array(X_test).reshape((len(X_test), 1))print(X_test.shape)SupportVectorRefModel = SVR()SupportVectorRefModel.fit(X_train, y_train)y_pred = SupportVectorRefModel.predict(X_test)
输出:
ValueError: X.shape[1] = 1 should be equal to 22, the number of features at training time
回答:
你对X_test
的重塑是不正确的;它应该这样做:
X_test = np.array(X_test).reshape(1, -1)print(X_test.shape) # (1, 22)
通过这个改动,其余的代码可以正常运行:
y_pred = SupportVectorRefModel.predict(X_test)y_pred# array([0.90156667])
更新
在你展示的代码中,很明显X_test
由一个单一样本组成,如下定义:
X_test, y_test = data.loc[1001], target.loc[1001]
但如果(我猜测)这不是你真正想要的,而实际上你想要剩余的数据作为测试集,你应该将定义改为:
X_test, y_test = data.loc[1001:], target.loc[1001:]X_test.shape# (999, 22)
并且不需要任何重塑
y_pred = SupportVectorRefModel.predict(X_test)y_pred.shape# (999,)
即一个包含999个预测值的y_pred
。