使用scikit learn的GaussianNB和nltk

2024-04-26 00:46:10 发布

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

我尝试使用nltk的包装器来实现scikitlearn的分类器。我用这段代码训练分类器:

classifier = SklearnClassifier(GaussianNB())
classifier.train(self.training_set)

其中training_set看起来像

^{pr2}$

我得到的错误是

TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.

我不知道如何转换为密集数组,尤其是因为nltk的train方法的文档需要A list of (featureset, label) where each featureset is a dict mapping strings to either numbers, booleans or strings.


Tags: to代码分类器istrainingtraindenseset
2条回答

也许已经晚了,但也许可以帮助其他有同样问题的人(cz我昨天遇到了这个问题)。在

TypeError: A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.

就像error说的,它需要转换成数组,所以我只需要像错误所说的那样把它转换成数组

vector = vectorizer.transform(corpus).toarray()

所以只要添加.toarray()就可以解决这个问题。
;)

当我切换到多项式nb或BernoulliNB时,它们都没有出错。有或没有toarray()。在

注意:别忘了转换为适合并将文本转换为单词表示(数值)。在

你有三个特征,只有两个是数值特征格式。你首先应将“name”功能转换为数字。如果name变量是分类变量,则可以按如下所述以有意义的方式对其进行编码:

http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features

我认为你的标签也有限,所以你也可以对它们进行编码。最后一步非常简单,只需将nltk格式转换为numpy数组格式。只需在一个循环中读取每个特征,然后在X(特征)和Y(标签)中插入所需的特征:

http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html

相关问题 更多 >

    热门问题