我正在使用NLTK和nltk.sklearn包装器构建分类器。
classifier = SklearnClassifier(LinearSVC(), int,True)
classifier.train(train_set)例如,当我只使用unigram和构建功能集时:
{"Cristiano" : True, "Ronaldo : True}一切都很好。但是当我想使用搭配的时候,就会有一个问题。功能集看起来不同:
{ {"Cristiano" : True, "Ronaldo : True, ("Cristiano", "Ronaldo") : True }然后我收到错误:
feature_names.sort()TypeError: unorderable types: tuple() < str()如何使用unigram和二元语法为nltk sklearn wrapper正确创建功能集?
发布于 2015-08-31 03:21:42
您可以使用scikit-learn中的CountVectorizer来生成ngram。
演示:
import sklearn.feature_extraction.text
ngram_size = 1
train_set = ['Cristiano plays football', 'Ronaldo like football too']
vectorizer = sklearn.feature_extraction.text.CountVectorizer(ngram_range=(ngram_size,ngram_size))
vectorizer.fit(train_set) # build ngram dictionary
ngram = vectorizer.transform(train_set) # get ngram
print('ngram: {0}\n'.format(ngram))
print('ngram.shape: {0}'.format(ngram.shape))
print('vectorizer.vocabulary_: {0}'.format(vectorizer.vocabulary_))输出:
ngram: (0, 0) 1
(0, 1) 1
(0, 3) 1
(1, 1) 1
(1, 2) 1
(1, 4) 1
(1, 5) 1
ngram.shape: (2, 6)
vectorizer.vocabulary_: {u'cristiano': 0, u'plays': 3, u'like': 2,
u'ronaldo': 4, u'football': 1, u'too': 5}发布于 2016-04-20 06:32:51
如果您想继续使用NLTK warper,只需在训练分类器之前执行以下操作:
classifier._vectorizer.sort = Falsehttps://stackoverflow.com/questions/32252075
复制相似问题