我正在使用 Lending Club API 编写脚本来预测贷款是“全额支付”还是“冲销”。为此,我使用 scikit-learn 构建模型并坚持使用 joblib。由于持久模型中的列数与新原始数据中的列数不同,我遇到了 ValueError。 ValueError 是由为分类变量创建虚拟变量引起的。模型中使用的列数为 84,在此示例中,使用新数据的列数为 29。
在制作虚拟变量时,新数据的列数需要为 84,但我不确定如何进行,因为分类变量“homeOwnership”、“addrState”和“purpose”的所有可能值中只有一个子集存在从 API 获取新数据时。
这是我目前正在测试的代码,从分类变量转换为虚拟变量开始,到模型实现停止。
#......continued
df['mthsSinceLastDelinq'].notnull().astype('int')
df['mthsSinceLastRecord'].notnull().astype('int')
df['grade_num'] = df['grade'].map({'A':0,'B':1,'C':2,'D':3})
df['emp_length_num'] = df['empLength']
df = pd.get_dummies(df,columns=['homeOwnership','addrState','purpose'])
# df = pd.get_dummies(df,columns=['home_ownership','addr_state','verification_status','purpose'])
# step 3.5 transform data before making predictions
df.drop(['id','grade','empLength','isIncV'],axis=1,inplace=True)
dfbcd = df[df['grade_num'] != 0]
scaler = StandardScaler()
x_scbcd = scaler.fit_transform(dfbcd)
# step 4 predicting
lrbcd_test = load('lrbcd_test.joblib')
ypredbcdfinal = lrbcd_test.predict(x_scbcd)
这是错误信息
ValueError Traceback (most recent call last)
<ipython-input-239-c99611b2e48a> in <module>
11 # change name of model and file name
12 lrbcd_test = load('lrbcd_test.joblib')
---> 13 ypredbcdfinal = lrbcd_test.predict(x_scbcd)
14
15 #add model
~\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in predict(self, X)
287 Predicted class label per sample.
288 """
--> 289 scores = self.decision_function(X)
290 if len(scores.shape) == 1:
291 indices = (scores > 0).astype(np.int)
~\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in decision_function(self, X)
268 if X.shape[1] != n_features:
269 raise ValueError("X has %d features per sample; expecting %d"
--> 270 % (X.shape[1], n_features))
271
272 scores = safe_sparse_dot(X, self.coef_.T,
ValueError: X has 29 features per sample; expecting 84
原文由 jz451 发布,翻译遵循 CC BY-SA 4.0 许可协议
只使用 Transform 而不是 fit_transform。这应该可以解决问题。希望能帮助到你。