首页 > 解决方案 > 类是字符串时的 XGBoost

问题描述

我有一个看起来像这样的数据框:

_id    Points      Averages     Averages_2           Media               Rank 
a         324         858.2            NaN               0               Good
b         343         873.2      4.465e+06               1               Good
c         934         113.4            NaN               0                Bad
d         222         424.2            NaN               1                Bad
e         432         234.2      3.605e+06               1               Good

我想预测排名。请注意,这只是具有 2000 行且大约为 2000 行的数据框的示例。20 列,但我试图指出有些列,例如Averages_2,有很多 NaN,并且有些列的值为 0 或 1。

我做了以下事情:

import xgboost as xgb

from sklearn import datasets

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder 
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
import pandas as pd

data = 'C:\\me\\my_table.csv'
df = pd.read_csv(data)

cols_to_drop = ['_id']  #no need to write two lines if there's just one column to drop
                        #but since my original df is much bigger I used this to drop 
                        #multiple columns

df.drop(cols_to_drop, axis=1, inplace=True)

X = df.drop('Rank', axis=1)
y = df['Rank']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=5)

lc = LabelEncoder() 
lc = lc.fit(y) 
lc_y = lc.transform(y)

model = XGBClassifier() 
model.fit(X_train, y_train)

y_pred = model.predict(X_test) 
predictions = [round(int(value)) for value in y_pred]

我知道ValueError: invalid literal for int() with base 10: 'Good'我认为对类进行编码会起作用,但是当类是字符串时还能做什么?

标签: pythonpandasscikit-learn

解决方案


它失败了,因为您y_pred包含类似的字符串["Good","Bad"],因此您的最后一行尝试调用例如round(int("Good"))它当然不能执行的操作(尝试调用print(y_pred[:5])并查看它显示的内容)。

实际上,您既没有在训练集也没有在测试集上使用标签编码器(因为您对其进行了训练y并且从不使用它来进行转换),并且在使用 XGboost 时y_pred也不y_train需要,它会自动处理类。


推荐阅读