如何将RandomForestClassifier与字符串数据一起使用

时间:2016-12-01 14:25:36

标签: python scikit-learn

我使用sklearn来构建RandomForestClassifier模型。

我的数据集中有一个字符串数据和folat数据。

会显示

could not convert string to float

我跑完后

clf = RandomForestClassifier(n_jobs=100)  
clf.fit(x1, y1)

如何使用混合数据构建RandomForest模型?

1 个答案:

答案 0 :(得分:1)

这是一种scikit-learn惯例:估算器接受数字矩阵,而不接受字符串或其他数据类型。这允许他们对数据类型不可知 - 每个估计器可以处理表格,文本数据,图像等。但这意味着您需要将数据(在您的情况下为文本)转换为数字。

将文本转换为数字的方法有很多种。最容易被称为" Bag of Words" - 对于每个可能的单词,有一列,如果本文档中有单词,则文档在列中有1(或单词计数),否则为0。 scikit-learn为此提供了CountVectorizer(以及一些其他矢量化器):

from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer()
X = vec.fit_transform(docs)
clf = RandomForestClassifier()  
clf.fit(X, y) 

有关完整示例,请参阅http://scikit-learn.org/stable/auto_examples/text/document_classification_20newsgroups.html,有关文本向量化的详情,请参见http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction