python - 类型 str 没有定义 __round__ 方法错误

标签 python arrays numpy typeerror xgboost

尝试实现 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')

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

round('a')

TypeError: type str doesn't define __round__ method

关于python - 类型 str 没有定义 __round__ 方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859609/

相关文章:

arrays - 如何从golang中的查询中获取数组键的值

c++ - 使用模板从参数列表创建 std::vector

python 3 : reading bytes from stdin pipe with readahead

python - 对列表的单个元素进行排序

python - 将 CSV 中的字符串交换为日期时间 (Python)

python - 如何将 csv 字符串转换为 pandas 中的列表?

python - 我可以制作 numpy 内存映射掩码吗?

多重继承中的 python 'super' - 意外的代码输出

c - 找到二维数组中的所有组合,以在 C 中的剧院中容纳可变数量的人?

python - Scipy 标签侵 eclipse