【问题标题】:Concatenate custom features with CountVectorizer使用 CountVectorizer 连接自定义特征
【发布时间】:2014-05-06 09:52:49
【问题描述】:

我有一堆包含文章的文件。每篇文章都应该有一些特征,例如:text lengthtext_spam(都是整数或浮点数,在大多数情况下应该从 csv 加载)。而我想做的是——将这些功能与 CountVectorizer 结合起来,然后对这些文本进行分类。

我看过一些教程,但我仍然不知道如何实现这些东西。找到了一些东西 here,但实际上无法满足我的需要。

有什么想法可以用 scikit 完成吗?

谢谢。

我现在遇到的是:

from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import FeatureUnion

measurements = [
    {'text_length': 1000, 'text_spam': 4.3},
    {'text_length': 2000, 'text_spam': 4.1},
]

corpus = [
    'some text',
    'some text 2 hooray',
]

vectorizer = DictVectorizer()
count_vectorizer = CountVectorizer(min_df=1)

first_x = vectorizer.fit_transform(measurements)
second_x = count_vectorizer.fit_transform(corpus)

combined_features = FeatureUnion([('first', first_x), ('second', second_x)])

对于这堆代码,我不明白如何加载“真实”数据,因为已经加载了训练集。第二个——如何加载类别(拟合函数的y参数)?

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    你误会FeatureUnion。应该是两台变压器,不是两批样品。

    您可以强制它处理您拥有的矢量化器,但将所有特征放入每个样本的一个大袋子中并使用单个 DictVectorizer 从这些袋子中制作矢量会更容易。

    # make a CountVectorizer-style tokenizer
    tokenize = CountVectorizer().build_tokenizer()
    
    def features(document):
        terms = tokenize(document)
        d = {'text_length': len(terms), 'text_spam': whatever_this_means}
        for t in terms:
            d[t] = d.get(t, 0) + 1
        return d
    
    vect = DictVectorizer()
    X_train = vect.fit_transform(features(d) for d in documents)
    

    不要忘记使用sklearn.preprocessing.Normalizer 对其进行规范化,并注意即使在规范化之后,那些text_length 特征在规模方面也必然会主导其他特征。改用1. / text_lengthnp.log(text_length) 可能更明智。

    第二个——如何加载类别(yfit 函数的参数)?

    取决于您的数据的组织方式。 scikit-learn 有很多辅助函数和类,但如果你的设置是非标准的,它确实希望你编写代码。

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 2020-10-02
      • 2016-05-30
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2015-01-21
      • 2015-12-02
      • 2016-09-27
      相关资源
      最近更新 更多