python - 无法使用 XGBoost 进行预测
问题描述
我有一个使用 XGBoost 来预测二进制分类的程序。我已经完成了大部分代码,但是在我想使用用户定义的变量来预测该类的最后,我遇到了问题。在分享代码之前,变量 'clf' 是我在执行 GridSearchCV 后选择的最佳分类器:
def prob1(LIMIT_BAL, SEX, EDUCATION, MARRIAGE, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2, BILL_AMT3,
BILL_AMT4, BILL_AMT5, BILL_AMT6, PAY_AMT1, PAY_AMT2, PAY_AMT3, PAY_AMT4, PAY_AMT5, PAY_AMT6):
#1) Store user entered information into a series, convert to dataframe, then transpose so that it is all in 1 row just like in training set.
lst = [LIMIT_BAL, SEX, EDUCATION, MARRIAGE, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2, BILL_AMT3,
BILL_AMT4, BILL_AMT5, BILL_AMT6, PAY_AMT1, PAY_AMT2, PAY_AMT3, PAY_AMT4, PAY_AMT5, PAY_AMT6]
ud_df = pd.Series(lst)
ud_df = ud_df.to_frame()
ud_df = ud_df.T
#2) Perform the same normalization and factorization of the values as done when loading the data in above.
c = [1,2,3] # index of categorical data columns
r = list(range(0,23))
r = [x for x in r if x not in c] # get list of all other columns
df_cat = ud_df.iloc[:, [2,3,4]].copy()
df_con = ud_df.iloc[:, r].copy()
# factorize categorical data
for c in df_cat:
df_cat[c] = pd.factorize(df_cat[c])[0]
# scale continuous data
scaler = preprocessing.MinMaxScaler()
df_scaled = scaler.fit_transform(df_con)
df_scaled = pd.DataFrame(df_scaled, columns=df_con.columns)
df_final = pd.concat([df_cat, df_scaled], axis=1)
#reorder columns back to original order
cols = df.columns
df_final = df_final[cols]
#Predict
prediction = clf.predict(df_final)
#Predict Probability
probability_pred = clf.predict_probab(df_final)
return(prediction, probability_pred)
因此,定义内部发生的事情是,用户给出了这些变量,并且对连续变量进行了归一化,并且通过因式分解处理了分类变量。
当我运行此代码时,我收到此错误:
prob1(50000,1, 1, 1, 37,0,0,0,0,0,0,64400,57069,57608,19394,19619,20024,2500,1815,657,1000,1000,800)
错误代码:df_con = ud_df.iloc[:, r].copy()
IndexError: positional indexers are out-of-bounds
任何帮助都会很棒!
这是一个没有任何争论的行的示例:[50000,1,1,2,37,0,0,0,0,0,0,64400,57069,57608,19394,19619,20024,2500 ,1815,657,1000,1000,800]
Edit1:原始代码中的固定界限。我收到此错误,突出显示 prob1(.....) 列:
KeyError: "Index(['ID', 'LIMIT_BAL', 'SEX', 'EDUCATION', 'MARRIAGE', 'AGE', 'PAY_0',\n 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6', 'BILL_AMT1', 'BILL_AMT2',\n 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 'PAY_AMT1',\n 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6'],\n dtype='object') not in index"
解决方案
您的列表变量有 23 个元素。
- r =
list(range(0,24))
有 24 个元素。r = {0,1..23}
当您使用基于索引iloc
查找元素时,由于它只有 23 个元素,因此您无法找到索引为 23 的元素,如错误代码所述,它超出了范围。udf
推荐阅读
- elasticsearch - Elasticsearch 文档计数不反映索引率
- powershell - 导入-CSV,更改 1 个字段,然后导出
- excel - 如何从括号中提取文本?
- .net - 如何在 Html.DropDownList 中以 dd/MMMM/yyyy 格式显示日期时间?
- python - Unable to locate element or switch to frame
- python - 不能让它成为一个列表 - python
- c# - ElasticSearch.NET 在 POST 请求中传递 AWS Signature v4?
- php - Pusher:在 private-user.6 上没有回调 pusher:subscription_error
- python - python将文本文件解压缩到单独的变量中
- perforce - 是否可以使用 P4 命令“标记删除”每个“丢失”的文件?