RandomForestClassifier.fit():ValueError:无法将字符串转换为浮点

2024-05-01 21:58:42 发布

您现在位置:Python中文网/ 问答频道 /正文

给出了一个简单的CSV文件:

A,B,C
Hello,Hi,0
Hola,Bueno,1

显然,真实的数据集远比这个复杂,但这个数据集再现了错误。我正在尝试为它构建一个随机林分类器,如下所示:

cols = ['A','B','C']
col_types = {'A': str, 'B': str, 'C': int}
test = pd.read_csv('test.csv', dtype=col_types)

train_y = test['C'] == 1
train_x = test[cols]

clf_rf = RandomForestClassifier(n_estimators=50)
clf_rf.fit(train_x, train_y)

但我只是在调用fit()时得到这个回溯:

ValueError: could not convert string to float: 'Bueno'

scikit学习版本为0.16.1


Tags: 文件csv数据testhellotraincolfit
3条回答

无法将str传递给模型fit()方法。正如它提到的here

The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.

尝试将数据转换为float并尝试LabelEncoder

LabelEncoding对我来说很有效(基本上,你必须对数据特性进行编码) (mydata是字符串数据类型的2d数组):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
    myData[:,i] = le.fit_transform(myData[:,i])

在使用fit之前,必须进行一些编码。正如前面所说,fit()不接受字符串,但您可以解决这个问题

可以使用几个类:

就我个人而言,不久前我已经在StackOverflow上发布了几乎the same question。我想有一个可扩展的解决方案,但没有得到任何答案。我选择了对所有字符串进行二值化的OneHotEncoder。这是相当有效的,但如果你有很多不同的字符串矩阵将增长非常快,内存将是必需的

相关问题 更多 >