【发布时间】:2015-07-12 08:21:10
【问题描述】:
我正在尝试使用 SVM 分类器分析推文。我能够使用 unigrams 作为特征成功地执行分类。我正在使用 SciKit 的 libSVM 实现,它可以使用 One-Vs-All 方法执行多类分类。为了生成特征向量,我使用了地图。如果该词存在于推文中,则将其映射为 1,否则将其映射为 0。在特征向量中,如果没有停止推文,则将 map(word) 的值附加到标签 0,否则为 1。代码为这里:
def getSVMFeatureVectorAndLabels(tweets, featureList):
sortedFeatures = sorted(featureList)
map = {}
feature_vector = []
labels = []
for t in tweets:
label = 0
map = {}
# Initialize empty map
for w in sortedFeatures:
map[w] = 0
tweet_words = t[0]
tweet_opinion = t[1]
# Fill the map
for word in tweet_words:
# process the word (remove repetitions and punctuations)
word = replaceTwoOrMore(word)
word = word.strip('\'"?,.')
# set map[word] to 1 if word exists
if word in map:
map[word] = 1
# end for loop
values = map.values()
feature_vector.append(values)
if(tweet_opinion == '0'):
label = 0
elif(tweet_opinion == '1'):
label = 1
labels.append(label)
# return the list of feature_vector and labels
return {'feature_vector' : feature_vector, 'labels': labels}
# end
在此代码中,tweets 包含 (unigram,label) 的列表,而 featureList 是从推文中提取的所有唯一词的列表。 在这段代码的同一行中,我想知道是否可以使用二元组作为特征,如何通过生成最佳二元组并创建特征向量来做到这一点?为了为朴素贝叶斯生成二元组,我使用了以下代码:
#extract features using bigram
def extract_bigrams(tweet, score_fn=BigramAssocMeasures.chi_sq, n=10):
bigram_finder = BigramCollocationFinder.from_words(tweet)
bigrams = bigram_finder.nbest(score_fn, n)
d = dict([(ngram, True) for ngram in itertools.chain(tweet, bigrams)])
d.update(best_word_feats(tweet))
return d
def best_word_feats(words):
return dict([(word, True) for word in words if word in bestwords])
best = sorted(word_scores.iteritems(), key=lambda (w, s): s, reverse=True) [:10000]
bestwords = set([w for w, s in best])
【问题讨论】:
标签: python svm n-gram text-analysis