python - 类是字符串时的 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'
我认为对类进行编码会起作用,但是当类是字符串时还能做什么?
解决方案
它失败了,因为您y_pred
包含类似的字符串["Good","Bad"]
,因此您的最后一行尝试调用例如round(int("Good"))
它当然不能执行的操作(尝试调用print(y_pred[:5])
并查看它显示的内容)。
实际上,您既没有在训练集也没有在测试集上使用标签编码器(因为您对其进行了训练y
并且从不使用它来进行转换),并且在使用 XGboost 时y_pred
也不y_train
需要,它会自动处理类。
推荐阅读
- symfony - 动态查询中的查询生成器“OR”
- knockout.js - 将静态图像路径与 knockoutJs 数据绑定连接
- c# - 根据 MVVM 中的集合更改调整列表视图的列大小
- postgresql - postgresql RDS - 无法写入哈希连接临时文件:设备上没有剩余空间
- android - 如何在房间数据库中使用 ForeignKey.SET_DEFAULT?
- node.js - 如何使用官方mongodb客户端在nodejs中的mongodb中实现twitter和facebook api之类的基于光标的分页?
- android - 谷歌播放控制台应用程序因权限而被拒绝
- css - Angular Material cdk-container 和主站点固定标头 z-index 覆盖
- php - 当我使用 Graph API 将一些内容发布到 Facebook 上的页面时,它只对我可见
- f# - FSC : 错误 FS0193: 设备未准备好