知識儲備
- 情感分析定義
文本情感分析(也稱為意見挖掘)是指自然語言處理冯痢、文本挖掘以及計算機語言學等方法來識別和提取原素材中的主觀信息呀页。(摘自《維基百科》)
使用到的第三方庫文件:
snownlp TextBlob(英文) SnowNLP(中文)
TextBlob github:TextBlob
SnowNLP github :SnowNLP
樸素貝葉斯定義
樸素貝葉斯是基于貝葉斯定理與特征條件獨立假設的分類方法谈跛。貝葉斯分類器基于一個簡單的假定:給定目標值時屬性之間相互條件獨立(摘自《百度百科》)
- 停用詞定義
在信息檢索中习寸,為節(jié)省存儲空間和提高效率祭阀,在處理自然語言數(shù)據(jù)(或文本)之前或之后會自動過濾掉某些詞或字垮卓,這些詞或字即被稱為Stop Word(停用詞)(摘自《維基百科》)
目前有很多比較成熟的停用詞表垫桂,可以參考這個
github項目
- 混淆矩陣
混淆矩陣中的4個數(shù)字,分別代表:
- TP: 本來是正向扒接,預測也是正向的伪货;
- FP: 本來是負向,預測卻是正向的钾怔;
- FN: 本來是正向碱呼,預測卻是負向的;
- TN: 本來是負向宗侦,預測也是負向的愚臀。
開始干活吧
- 文本文件讀入
import pandas as pd
# 讀入文本文件
df = pd.read_csv()
- 定義函數(shù)將星級評分大于3分的,當成正向情感矾利,取值為1姑裂,反之取值為0
def make_label(df):
df["sentiment"] =df['comment_ratting'].apply(lambda x: 1 if x>3 else 0)
- 拆分特征和標簽
# 提取全部特征值
X = df[['comment']]
y = df.sentiment
- 中文分詞
# 結巴分詞工具做分詞操作
import jieba
def chinese_word_cut(content):
return ' '.join([word for word in jieba.cut(content,cut_all=False) if len(word)>=2])
# apply函數(shù),對每行評論進行分詞
X['cutted_comment'] = X.comment_infos.apply(chinese_word_cut)
- 訓練集和測試集拆分
from sklearn.model_selection import train_test_split
# from sklearn.cross_validation import train_test_split (sklearn版本低于0.18男旗,請使用該行)
# random_state 保證隨機數(shù)在不同環(huán)境中保持一致舶斧,以便驗證模型效果
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
- 中文停用詞處理
def get_custom_stopwords(stop_words_file):
with open(stop_words_file) as f:
stopwords = f.read()
stopwords_list = stopwords.split('\n')
custom_stopwords_list = [i for i in stopwords_list]
return custom_stopwords_list
stop_word_file = '中文停用詞文件'
stopwords = get_custom_stopwords(stop_words_file)
- 特征向量化
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(
max_df = 0.8,# 在超過這一比例的文檔中出現(xiàn)的關鍵詞(過于平凡),去除掉察皇。
min_df = 3, # 在低于這一數(shù)量的文檔中出現(xiàn)的關鍵詞(過于獨特)茴厉,去除掉。
token_pattern=u'(?u)\\b[^\\d\\W]\\w+\\b', #取出數(shù)字特征
stop_words=frozenset(stopwords))
)
# 向量化工具轉化分詞后的訓練集語句什荣,并轉換為DataFrame對象
term_matrix = pd.DataFrame(vect.fit_transform(X_train.cutted_comment).toarray(), columns=vect.get_feature_names())
- 利用生成矩陣訓練模型
# 樸素貝葉斯分類
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB()
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(vect, nb)
# 將未特征向量化的訓練集內容輸入矾缓,做交叉驗證,計算模型分類準確率
from sklearn.cross_validation import cross_val_score
print (cross_val_score(pipe, X_train.cutted_comment, y_train, cv=5, scoring='accuracy').mean())
結果輸出:0.819563608026
- 驗證模型準確度
# 模型擬合
pipe.fit(X_train.cutted_comment, y_train)
# 在測試集上稻爬,對情感分類進行預測
y_pred = pipe.predict(X_test.cutted_comment)
# 引入sklearn測量工具集
from sklearn import metrics
print (metrics.accuracy_score(y_test, y_pred))
結果輸出:0.80612244898
- 混淆矩陣驗證
print (metrics.confusion_matrix(y_test, y_pred))
結果輸出:[[67 3][16 12]]
- SnowNLP進行情感分析
from snownlp import SnowNLP
def get_sentiment(text):
return SnowNLP(text).sentiments
# 測試數(shù)據(jù)集 利用SnowNLP處理
y_pred_snownlp = X_test.comment_infos.apply(get_sentiment)
# 當我們查看結果就會發(fā)現(xiàn)SnowNLP輸出結果為[0-1]之間的小數(shù)值
# 所以我們將大于0.5的結果作為正向嗜闻,小于0.5的結果作為負向y_pred_snownlp_normalized = y_pred_snownlp.apply(lambda x: 1 if x>0.5 else 0)
# 查看模型的準確率
print (metrics.accuracy_score(y_test, y_pred_snownlp_normalized))
結果輸出:0.489795918367
結果很糟糕哦!
小結
- 如何利用停用詞桅锄、詞頻閥值和標記模式(token_pattern)移除無關的特征詞匯琉雳,降低模型復雜度
- 選用合適的機器學習分類模型,對詞語特征矩陣分類的重要性
- 如何使用管道模式友瘤,歸并和簡化機器學習步驟流程
- 如何選擇合適的性能測試工具咐吼,對模型的效果作出評估和對比
相關閱讀 請移步
初步學習有很多不足之處,希望大家多多指教
代碼和數(shù)據(jù)集會在整理后及時更新