【问题标题】:How do I properly combine numerical features with text (bag of words) in scikit-learn?如何在 scikit-learn 中将数字特征与文本(词袋)正确结合?
【发布时间】:2017-01-19 13:56:08
【问题描述】:

我正在为网页编写一个分类器,所以我有数字特征的混合,我也想对文本进行分类。我正在使用词袋方法将文本转换为(大)数字向量。代码最终是这样的:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np

numerical_features = [
  [1, 0],
  [1, 1],
  [0, 0],
  [0, 1]
]
corpus = [
  'This is the first document.',
  'This is the second second document.',
  'And the third one',
  'Is this the first document?',
]
bag_of_words_vectorizer = CountVectorizer(min_df=1)
X = bag_of_words_vectorizer.fit_transform(corpus)
words_counts = X.toarray()
tfidf_transformer = TfidfTransformer()
tfidf = tfidf_transformer.fit_transform(words_counts)

bag_of_words_vectorizer.get_feature_names()
combinedFeatures = np.hstack([numerical_features, tfidf.toarray()])

这可行,但我担心准确性。请注意,有 4 个对象,只有两个数字特征。即使是最简单的文本也会产生一个具有九个特征的向量(因为语料库中有九个不同的单词)。显然,对于真实文本,会有数百或数千个不同的单词,因此最终的特征向量将是 1000 个基于单词的特征。

正因为如此,分类器 (SVM) 不会以 100 比 1 的系数对数字特征上的单词进行大量加权吗?如果是这样,我该如何补偿以确保词袋与数字特征的权重相等?

【问题讨论】:

标签: python scikit-learn classification text-classification


【解决方案1】:

我认为你的担忧是完全正确的,它以一种天真的方式(作为多热向量)从稀疏文本标记产生显着更高的维度。您至少可以通过以下两种方法来解决这个问题。它们都会从文本中生成一个低维向量(例如 100 维)。当你的词汇量增加时,维度不会增加。

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2018-10-14
    • 2018-09-15
    • 2017-06-20
    • 1970-01-01
    • 2014-09-10
    • 2016-09-11
    • 2016-03-21
    • 2017-06-12
    相关资源
    最近更新 更多