【问题标题】:python sklearn using more than just the count features for naive bayes learningpython sklearn 不仅使用计数功能进行朴素贝叶斯学习
【发布时间】:2017-04-12 14:22:05
【问题描述】:

首先,我是 python 和 nlp / 机器学习的新手。 现在我有以下代码:

vectorizer = CountVectorizer(
   input="content", 
   decode_error="ignore", 
   strip_accents=None,
   stop_words = stopwords.words('english'),
   tokenizer=myTokenizer
)
counts = vectorizer.fit_transform(data['message'].values)
classifier = MultinomialNB()
targets = data['sentiment'].values
classifier.fit(counts, targets)

现在这实际上工作得很好。我通过CountVectorizer 得到一个稀疏矩阵,classifier 使用矩阵以及目标(0,2,4)

但是,如果我想在向量中使用更多特征而不仅仅是字数,我该怎么办?我似乎无法找到它。提前谢谢你。

【问题讨论】:

标签: python scikit-learn nlp naivebayes countvectorizer


【解决方案1】:

在您的情况下,counts 是一个稀疏矩阵;您可以向其中添加具有额外功能的列:

import numpy as np
from scipy import sparse as sp

counts = vectorizer.fit_transform(data['message'].values)
ones = np.ones(shape=(len(data), 1))
X = sp.hstack([counts, ones])

classifier.fit(X, targets)

scikit-learn 还为此提供了一个内置帮助器;它被称为FeatureUnion。在 scikit-learn docs 中有一个组合来自两个转换器的特征的示例:

estimators = [('linear_pca', PCA()), ('kernel_pca', KernelPCA())]
combined = FeatureUnion(estimators)

# then you can do this:
X = combined.fit_transform(my_data)

FeatureUnion 的作用几乎相同:它采用矢量化器列表(带有名称),为相同的输入数据调用它们,然后按列连接结果。

通常最好使用 FeatureUnion,因为您可以更轻松地使用 scikit-learn 交叉验证、酸洗最终管道等。

另请参阅这些教程:

【讨论】:

    【解决方案2】:

    这取决于您的数据以及您想要做什么。除了字数统计之外,您还可以使用不同的转换方法:Bag of Words、TFIDF、Word Vector、...

    您可以从这些文档中了解更多信息: - http://billchambers.me/tutorials/2015/01/14/python-nlp-cheatsheet-nltk-scikit-learn.html - http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html

    【讨论】:

    • 嗨,感谢您的回答。这些链接似乎很有帮助。但是,我认为我的问题实际上比您想象的还要简单。我意识到还有更多可用的矢量化器。但是,可以说我想使用消息本身的总字数作为附加功能。那将是一个简单的整数。目前,classifier.fit 函数使用CountVectorizer 返回的矩阵。如何将字数添加到classifier 使用的特征向量中,使其同时使用countsoverall word count
    猜你喜欢
    • 2016-05-01
    • 2018-12-15
    • 2011-12-27
    • 2018-12-24
    • 2019-03-01
    • 2015-10-28
    • 2016-12-11
    • 2020-02-28
    • 2016-11-09
    相关资源
    最近更新 更多