python - 使用 sklearn 通过类对字符串进行分类

标签 python string scipy scikit-learn gaussian

我在以 sklearn 接受的形式呈现数据时遇到问题 我的原始数据是几百个字符串,这些字符串被分为 5 个类别之一,我有一个要分类的字符串列表,以及它们各自类别的并行列表。我正在使用 GaussianNB()

示例数据:

For such a large, successful business, I really feel like they need to be 
either choosier in their employee selection or teach their employees to 
better serve their customers.|||Class:4

它代表给定的“特征”和分类

当然,字符串本身必须先转换为向量,然后才能在分类器中使用,我尝试使用 DictVector 来执行此任务

dictionaryTraining = convertListToSentence(data)
vec = DictVectorizer()
print(dictionaryTraining)
vec.fit_transform(dictionaryTraining)

但是为了做到这一点,我必须将数据的实际分类附加到字典中,否则我会收到错误 'str' object has no attribute 'items' 我明白这是因为.fit_transform 需要特征和索引,但我不完全理解索引的用途

fit_transform(X[, y])   Learn a list of feature name -> indices mappings and transform X.

我的问题是,我如何获取字符串列表和代表其分类的数字列表,并将它们提供给 gaussianNB() 分类器,以便我可以用类似的方式呈现它 future 的字符串,它会估计字符串类?

最佳答案

由于您的输入数据采用原始文本格式,而不是字典格式,例如 {"word":number_of_occurrences, } 我相信您应该使用 CountVectorizer这将在空白处分割您的输入文本并将其转换为您需要的输入向量。

这种转换的一个简单示例是:

from sklearn.feature_extraction.text import CountVectorizer
corpus = ['This is the first document.', 'This is the second second document.', 
          'And the third one.', 'Is this the first document?',]
x = CountVectorizer().fit_transform(corpus)
print x.todense() #x holds your features. Here I am only vizualizing it 

关于python - 使用 sklearn 通过类对字符串进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38016107/

相关文章:

python - 查看流.io : How can I present a custom form for gathering input for a specific task?

python - 在 pivot 期间选择不同的聚合函数

Java - 构造函数中的自动字符串实习

c++ - std::string 是如何实现的?

使用 jaccard 相似度的 Python Pandas 距离矩阵

python - grequests 与 requests 发生冲突

python - l.append[i],对象不可下标?

string - 如何根据要求对字符串进行分段

python - 为什么相同数据的 scipy.stats.gaussian_kde() 比 seaborn.kde_plot() 慢?

python - 从矩阵中有效地减去向量(Scipy)