2015-05-02 68 views
0

我正在嘗試使用SVM分類器分析tweets。我能夠使用unigrams作爲功能成功執行分類。我正在使用SciKit的libSVM實現,它可以使用One-Vs-All方法執行多類分類。爲了生成一個特徵向量,我使用了一張地圖。如果該單詞存在於推文中,則將其映射爲1,否則爲0.在特徵向量中,如果地圖(單詞)的值不是停止鳴叫,則附加標籤0,否則爲1。在這裏:在python中使用bigrams訓練SVM分類器

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 

在這段代碼,鳴叫包含(單gram,標籤)的列表和featureList是從微博中提取的所有不重複的單詞的列表。 在這段代碼的同一行上,我想知道是否可以使用bigrams作爲一個功能,我該如何通過生成最佳的bigrams並創建一個特徵向量來實現它?對於產生雙字母組的樸素貝葉斯,我用這個代碼:

#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]) 

回答

0

您可以使用sklearn的CountVectorizer爲你做這個。見this guide,特別是行代碼

>>> bigram_vectorizer = CountVectorizer(ngram_range=(1, 2), 
...          token_pattern=r'\b\w+\b', min_df=1)