【发布时间】:2019-12-17 16:28:40
【问题描述】:
我正在编写一个脚本,使用 Lending Club API 来预测一笔贷款是“全额支付”还是“注销”。为此,我使用 scikit-learn 构建模型并使用 joblib 进行持久化。由于持久模型中的列数与新原始数据的列数之间存在差异,我遇到了 ValueError。 ValueError 是由为分类变量创建虚拟变量引起的。模型中使用的列数为 84,在此示例中,使用新数据的列数为 29。
在制作虚拟变量时,新数据的列数需要为 84,但我不确定如何继续,因为只有分类变量“homeOwnership”、“addrState”和“用途”的所有可能值的子集' 在从 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
【问题讨论】:
标签: python pandas scikit-learn valueerror one-hot-encoding