(本文所使用的Python庫和版本號: Python 3.6, Numpy 1.14, scikit-learn 0.19, matplotlib 2.2 )git
在NLP中有一個很是實用的應用領域--情感分析,情感分析是用NLP技術分析一段給定文本的情感類型,是積極的仍是消極的,是樂觀的仍是悲觀的等。好比在股市中,咱們知道,每每大衆最悲觀的時候每每是股市的大底,而最樂觀的時候倒是股市的頂部,因此,若是咱們可以掌握大衆的內心情感情況,那麼也就能大概知道股市的底和頂,換言之,也就可以在股市上掙得大把大把的銀子了。github
本項目所使用的數據集也是由nltk內部提供,其中的corpus模塊中有movies_reviews,能夠給咱們提供「積極」和「消極」的語句文本。dom
# 1, 準備數據集
from nltk.corpus import movie_reviews
pos_fileIds=movie_reviews.fileids('pos') # 加載積極文本文件
neg_fileIds=movie_reviews.fileids('neg') # 消極文本文件
print(len(pos_fileIds)) # 1000
print(len(neg_fileIds)) # 1000
print(pos_fileIds[:5])
print(neg_fileIds[:5])
# 由此可看出,movie_reviews.fileids是加載各類類別文本的文件,
# 並返回該文件名組成的list
# 若是想要查看某個文本文件的內容,可使用
print(movie_reviews.words(fileids=['pos/cv000_29590.txt']))
複製代碼
----------------輸---------出-----------------機器學習
1000 1000 ['pos/cv000_29590.txt', 'pos/cv001_18431.txt', 'pos/cv002_15918.txt', 'pos/cv003_11664.txt', 'pos/cv004_11636.txt'] ['neg/cv000_29416.txt', 'neg/cv001_19502.txt', 'neg/cv002_17424.txt', 'neg/cv003_12683.txt', 'neg/cv004_12641.txt'] ['films', 'adapted', 'from', 'comic', 'books', 'have', ...]函數
-----------------------完---------------------學習
雖然上面把文本文件的名稱提取出來,可是咱們還須要從這些txt文件中提取出所須要的特徵,使用這些特徵才能進行後續的分類器建模。測試
# 2, 處理數據集
def extract_features(word_list):
'''專門一個函數來提取特徵'''
return dict([(word,True) for word in word_list]) # 此處加True的做用是構成dict,實質意義不大
pos_features=[(extract_features(movie_reviews.words(fileids=[f])),'Pos')
for f in pos_fileIds]
neg_features=[(extract_features(movie_reviews.words(fileids=[f])),'Neg')
for f in neg_fileIds]
print(pos_features[:3]) # 打印下看看內容是否正確
dataset=pos_features+neg_features # 將兩部分結合起來做爲一個dataset
複製代碼
打印出來的結果很長,能夠參考個人github裏面的代碼。this
# 構建模型,訓練模型
from nltk import NaiveBayesClassifier
from nltk.classify import accuracy as nltk_accuracy
np.random.shuffle(dataset)
rows=int(len(dataset)*0.8) # 80%爲train set
train_set,test_set=dataset[:rows],dataset[rows:]
print('Num of train_set: ',len(train_set),
'/nNum of test_set: ',len(test_set))
clf=NaiveBayesClassifier.train(train_set)
# 查看該模型在test set上的表現
acc=nltk_accuracy(clf,test_set)
print('Accuracy: {:.2f}%'.format(acc*100))
複製代碼
-------------------輸---------出-----------------------spa
Num of train_set: 1600
Num of test_set: 400
Accuracy: 70.75%code
-------------------------完---------------------------
由此能夠看出該模型在測試集上的表現爲:準確率70.75%
# 查看模型內部信息
# 該分類器是分析某段文本中哪些單詞與「積極」的關聯最大,
# 哪些與「消極」的關聯最大,進而分析這些關鍵詞的出現來判斷某句話是積極或消極
# 打印這些關鍵詞
for key_word in clf.most_informative_features()[:10]:
print(key_word[0])
複製代碼
----------------輸---------出-----------------------
outstanding
insulting
ludicrous
affecting
magnificent
breathtaking
avoids
strongest
fascination
slip
------------------------完-------------------------
能夠看出,這些關鍵詞對於區分一個句子是積極仍是消極有着相當重要的做用,或者說,若是某個句子中有了這些關鍵詞,就能夠區分這個句子的情感是積極仍是消極,這些單詞越多,模型預測的準確率就越高。
# 用該模型來預測新樣本,查看新句子的情感是積極仍是消極
new_samples = [
"It is an amazing movie",
"This is a dull movie. I would never recommend it to anyone.",
"The cinematography is pretty great in this movie",
"The direction was terrible and the story was all over the place"
]
for sample in new_samples:
predict_P=clf.prob_classify(extract_features(sample.split()))
pred_sentiment=predict_P.max()
print('Sample: {}, Type: {}, Probability: {:.2f}%'.format(
sample,pred_sentiment,predict_P.prob(pred_sentiment)*100))
複製代碼
----------------輸---------出-----------------------
Sample: It is an amazing movie, Type: Pos, Probability: 61.45%
Sample: This is a dull movie. I would never recommend it to anyone., Type: Neg, Probability: 80.12%
Sample: The cinematography is pretty great in this movie, Type: Pos, Probability: 63.63%
Sample: The direction was terrible and the story was all over the place, Type: Neg, Probability: 63.89%
------------------------完----------------------------
########################小**********結###############################
1,NLTK中所使用的分類器須要用dict類型的數據做爲features來數據,故而咱們須要自定義一個extract_features函數,來將單詞轉變爲dict類型。
2,NLTK中已經集成了不少分類器,好比NaiveBayesClassifier,這些分類器已經集成了字符串處理方面的各類細節,使用起來很方便。
#################################################################
注:本部分代碼已經所有上傳到(個人github)上,歡迎下載。
參考資料:
1, Python機器學習經典實例,Prateek Joshi著,陶俊傑,陳小莉譯