类型为str的对象没有定义__round__方法错误。

9

我正在尝试使用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

我能做什么?


如果您能够发布完整的错误信息,那就太好了。 - 0TTT0
2个回答

8
很可能你在 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

-1

尝试将"value"指定为int类型:

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

对我有用


哈哈哈... round() 是用于小数的。如果我们将 str 转换为 int() 数字,为什么还需要 round()??????哈哈... - jis0324

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接