如何在 XGBClassifier python 中使用分类数据

问题描述

我正在用 python 开发 XGBClassifier。我的问题是,除了一个特征之外,所有其他特征都是分类特征。但是当将它们输入模型时,它会将它们视为连续特征。另外,我尝试将它们转换为使用 One hot encoding。但是没有用。这个问题怎么解决...

Here I attached an image of the part of my tree. Here except f35,all others are categorical

在这里我附上了我的树部分的图像。这里除了 f35,其他都是分类

解决方法

您没有提到您的特征是如何存储的或者您需要编码哪个特征。因此,就本回答而言,假设您的功能名为 'cat',并且您的数据存储在名为 pandas.DataFramedf 中。

为了编码一列,您可以尝试:

# Import encoder
from sklearn.preprocessing import OneHotEncoder

# Fit encoder to categorical feature
cat_enc = OneHotEncoder(sparse=False)
cat_enc.fit(df['cat'].values.reshape(-1,1))

# Add encoded feature to DataFrame
df[cat_enc.get_feature_names()] = cat_enc.transform(df['cat'].values.reshape(-1,1))

# Drop old column
df.drop(columns='cat',axis=1,inplace=True)

如果您想要更具体的答案,请更新您的帖子,我会更新我的答案。