类型 str 未定义 __round__ 方法错误

type str doesn't define __round__ method error

尝试实施 XGBoost 以确定最重要的变量时,数组出现一些错误。

我的完整代码如下

from numpy import loadtxt
from numpy import sort
import pandas as pd
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import SelectFromModel


df = pd.read_csv('data.txt')
array=df.values
X= array[:,0:330]
Y = array[:,330]

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=7)


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


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

我收到以下错误:

TypeError: type str doesn't define __round__ method

我能做什么?

您在 y_train 中的一些标签很可能实际上是字符串而不是数字。 sklearnxgboost 不要求标签为数字。

尝试检查 y_pred 的类型。

from collections import Counter

Counter([type(value) for value in y_pred])

这是我用数字标签表示的例子

import numpy as np
from sklearn.ensemble import GradientBoostingClassifier

# test with numeric labels
x = np.vstack([np.arange(100), np.sort(np.random.normal(10, size=100))]).T
y = np.hstack([np.zeros(50, dtype=int), np.ones(50, dtype=int)])
model = GradientBoostingClassifier()
model.fit(x,y)
model.predict([[10,7]])
# returns an array with a numeric 
array([0])

这里有字符串标签(相同的 x 数据)

y = ['a']*50 + ['b']*50
model.fit(x,y)
model.predict([[10,7]])
# returns an array with a string label
array(['a'], dtype='<U1')

两者都是价值标签。但是,当您尝试对字符串变量使用 round 时,您会得到与您看到的完全相同的错误。

round('a')

TypeError: type str doesn't define __round__ method

尝试将“值”表示为整数:

predictions = [round(int(value)) for value in y_pred]

为我工作