【问题标题】:How to vectorize labeled bigrams with scikit learn?如何用 scikit learn 向量化标记的二元组?
【发布时间】:2015-02-11 19:42:00
【问题描述】:

我正在自学如何使用 scikit-learn,我决定使用我自己的语料库开始 second task。我手动获得了一些二元组,比如说:

training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
[('and', 'one'), ('one', 'more'), 'NEG']
[('and', 'other'), ('one', 'more'), 'NEU']]

我想以一种可以很好地填充 scikit-learn 提供的分类算法(svc、多项式朴素贝叶斯等)的格式对它们进行矢量化处理。这是我尝试过的:

from sklearn.feature_extraction.text import CountVectorizer

count_vect = CountVectorizer(analyzer='word')

X = count_vect.transform(((' '.join(x) for x in sample)
                  for sample in training_data))

print X.toarray()

问题在于我不知道如何处理标签(即'POS', 'NEG', 'NEU'),我是否也需要“矢量化”标签以便将training_data 传递给分类算法,或者我可以让它像'POS'或任何其他类型的字符串?另一个问题是我得到了这个:

raise ValueError("Vocabulary wasn't fitted or is empty!")
ValueError: Vocabulary wasn't fitted or is empty!

那么,我如何矢量化像 training_data 这样的二元组。我也在阅读有关dictvectorizerSklearn-pandas 的信息,你们认为使用它们可能是完成这项任务的更好方法吗?

【问题讨论】:

    标签: python machine-learning nlp scikit-learn nltk


    【解决方案1】:

    应该是这样的:

    >>> training_data = [[('this', 'is'), ('is', 'a'),('a', 'text'), 'POS'],
                     [('and', 'one'), ('one', 'more'), 'NEG'],
                     [('and', 'other'), ('one', 'more'), 'NEU']]
    >>> count_vect = CountVectorizer(preprocessor=lambda x:x,
                                     tokenizer=lambda x:x)
    >>> X = count_vect.fit_transform(doc[:-1] for doc in training_data)
    
    >>> print count_vect.vocabulary_
    {('and', 'one'): 1, ('a', 'text'): 0, ('is', 'a'): 3, ('and', 'other'): 2, ('this', 'is'): 5, ('one', 'more'): 4}
    >>> print X.toarray()
    [[1 0 0 1 0 1]
     [0 1 0 0 1 0]
     [0 0 1 0 1 0]]
    

    然后将标签放入目标变量中:

    y = [doc[-1] for doc in training_data] # ['POS', 'NEG', 'NEU']
    

    现在您可以训练模型了:

    model = SVC()
    model.fit(X, y)
    

    【讨论】:

    • 其实我一直在使用这种设置标签的方式。问题是我有一个更大的二元组列表,而且看起来不清楚 scikit 如何使用标签来训练和预测一些结果。是否有另一种pythonic方法来设置标签而不是逐行进行?谢谢!
    • 是的,更新了我的答案,还修复了 CountVectorizer 调用,使其不会预处理或标记您的二元组。
    • 您的代码中有几个小错误,我建议您打开一个新问题,与您现在遇到的错误和即将遇到的错误相关(提示:比较标签的代码@ 987654325@与我的)
    • 如果你的意思是“如何从列表中提取最后一个元素”,这在 python 中称为列表推导。类似于y=[]; for sublist in data_training: y.append(sublist[-1]);,其中sublist[-1]表示“子列表的最后一个元素”
    • 那么CountVectorizer 可以输入原始文本并输出二元组,查找ngram_range 参数。
    猜你喜欢
    • 1970-01-01
    • 2017-12-25
    • 2013-11-30
    • 2015-07-10
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2013-01-19
    相关资源
    最近更新 更多