文本情感分析:又稱意見挖掘驰坊、傾向性分析等谊迄。簡(jiǎn)單而言,是對(duì)帶有情感色彩的主觀性文本進(jìn)行分析惩琉、處理豆励、歸納和推理的過程。互聯(lián)網(wǎng)(如博客和論壇以及社會(huì)服務(wù)網(wǎng)絡(luò)如大眾點(diǎn)評(píng))上產(chǎn)生了大量的用戶參與的良蒸、對(duì)于諸如人物技扼、事件、產(chǎn)品等有價(jià)值的評(píng)論信息嫩痰。這些評(píng)論信息表達(dá)了人們的各種情感色彩和情感傾向性,如喜剿吻、怒、哀串纺、樂和批評(píng)丽旅、贊揚(yáng)等≡於猓基于此,潛在的用戶就可以通過瀏覽這些主觀色彩的評(píng)論來了解大眾輿論對(duì)于某一事件或產(chǎn)品的看法魔招。本文主要簡(jiǎn)述情感分析中的情感信息抽取,及文本粒度由大到小分別對(duì)情感分析方法進(jìn)行對(duì)比和總結(jié)五辽。
過程和環(huán)節(jié):
1:收集數(shù)據(jù)集办斑。采用用戶評(píng)論和評(píng)分作為依據(jù),通過樣本數(shù)據(jù)訓(xùn)練分類來判斷情感傾向
2:設(shè)計(jì)文本的表示模型杆逗。讓機(jī)器讀懂文本乡翅,是文本情感分析的基礎(chǔ)首先要解決的是文本表示模型。向量表示文本罪郊,向量的特征是模型的最小單元蠕蚜。
3:選擇文本的特征。中文分詞(jieba,snownlp,thuLAC),將文本轉(zhuǎn)換為詞語(yǔ)悔橄“欣郏可以使用TF-IDF算法來抽取特征,并計(jì)算出特征值
4.選擇分類模型:如 決策樹癣疟,貝葉斯挣柬,人工神經(jīng)網(wǎng)絡(luò),支持向量機(jī)等機(jī)器學(xué)習(xí)算法
示例代碼:
import pandas as pd
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt
import os
#將文本轉(zhuǎn)為小寫睛挚,并且用空格對(duì)文本進(jìn)行分割
from keras.preprocessing.text import text_to_word_sequence
import math
os.chdir("D:\python_workspace\sentimentClassification-master\data")
print("Loading data......")
#加載數(shù)據(jù)? 訓(xùn)練集和測(cè)試集
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
# print(train.head(10))
# print(test.head(10))
print("#################")
#缺失值分析
print("train訓(xùn)練集的缺失值\n",train.isnull().sum())
print("test測(cè)試集的缺失值\n",test.isnull().sum())
#文本處理
train['comment_text_words']= train.comment_text.apply(text_to_word_sequence,filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n\'')
print("訓(xùn)練集中將文本轉(zhuǎn)為小寫邪蛔,用空格分割\n",train.head())
test['comment_text_words'] = test.comment_text.apply(text_to_word_sequence, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n\'')
print("測(cè)試集將文本轉(zhuǎn)為小寫,用空格分割\n",test.head())
# 將預(yù)訓(xùn)練好的 embeddings 進(jìn)行處理扎狱,返回幾個(gè)有用的變量:
# words_to_index:將單詞和編號(hào)進(jìn)行映射
# index_to_words:將編號(hào)和單詞進(jìn)行映射侧到,與 words_to_index 相反
# word_to_vec_map:將單詞與它的 embedding 進(jìn)行映射
def read_glove_vecs(glove_file):
? ? with open(glove_file,"r",encoding="utf-8") as f:
? ? ? ? #將單詞保存到一個(gè)集合中
? ? ? ? words = set()
? ? ? ? #將單詞與embedding 的映射保存到一個(gè)字典中
? ? ? ? word_to_ver_map={}
? ? ? ? for line in f:
? ? ? ? ? ? line = line.strip().split()
? ? ? ? ? ? #列表的第一個(gè)元素是單詞
? ? ? ? ? ? curr_word = line[0]
? ? ? ? ? ? #將單詞假如到集合中
? ? ? ? ? ? words.add(curr_word)
? ? ? ? ? ? #列表的其他元素是embedding 將單詞與embedding進(jìn)行映射,然后存入在字典中
? ? ? ? ? ? word_to_ver_map[curr_word] =np.array(line[1:],dtype=np.float32)
? ? #將單詞進(jìn)行編號(hào)淤击,編號(hào)從1開始
? ? i=1
? ? word_to_index={}
? ? index_to_words ={}
? ? for w in sorted(words):
? ? ? ? #創(chuàng)建映射匠抗,key是單詞,value是編號(hào)
? ? ? ? word_to_index[w]=i
? ? ? ? #創(chuàng)建映射污抬,key是編號(hào)汞贸,value是單詞
? ? ? ? index_to_words[i]=w
? ? ? ? i=i+1
? ? return word_to_index,index_to_words,word_to_ver_map
# glove.6B.50d.txt 是網(wǎng)上已經(jīng)預(yù)訓(xùn)練好的 word embedding 文件
word_to_index, index_to_word, word_to_vec_map = read_glove_vecs('glove.6B.50d.txt')
print("word_to_index:\n",word_to_index)
print("index_to_word:\n",index_to_word)
print("word_to_ver_map:\n",word_to_vec_map)
def sentences_to_indices(X):
? ? X_indices=[]
? ? for word in X:
? ? ? ? try:
? ? ? ? ? ? X_indices.append(word_to_index[word])
? ? ? ? except:
? ? ? ? ? ? pass
? ? return X_indices
test['comment_text_indexes'] = test.comment_text_words.apply(sentences_to_indices)
#文本長(zhǎng)度分析
comment_text_max_words_length = np.max([np.max(train.comment_text_words.apply(lambda x: len(x)))
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? , np.max(test.comment_text_words.apply(lambda x: len(x)))])
print("最大文本長(zhǎng)度是 "+str(comment_text_max_words_length))
# 查看商品名的長(zhǎng)度的分布
train.comment_text_words.apply(lambda x: len(x)).hist()
#文本長(zhǎng)度集中在0-400之間,所以我們把最大文本長(zhǎng)度設(shè)置為200
MAX_COMMENT_TEXT_SEQ = 200
# 如果列表長(zhǎng)度大于最大長(zhǎng)度,那么將列表進(jìn)行裁剪著蛙,如果列表長(zhǎng)度小于最大長(zhǎng)度,那么將列表補(bǔ)充到最大長(zhǎng)度耳贬,并且默認(rèn)填充0
from keras.preprocessing.sequence import pad_sequences
def get_keras_data(dataset):
? ? X = {'comment_text': pad_sequences(dataset.comment_text_indexes, maxlen=MAX_COMMENT_TEXT_SEQ)}
? ? return X
# 將訓(xùn)練集數(shù)據(jù)的文本編號(hào)列表進(jìn)行填充踏堡,并且提取出來
X_train = get_keras_data(train)
# 將測(cè)試集數(shù)據(jù)的文本編號(hào)列表進(jìn)行填充,并且提取出來
X_test = get_keras_data(test)
#將處理好的數(shù)據(jù)保存起來
import pickle
datafile = open('data.pkl', 'wb')
pickle.dump(X_train, datafile)
pickle.dump(X_test, datafile)
pickle.dump(word_to_index, datafile)
pickle.dump(index_to_word, datafile)
pickle.dump(word_to_vec_map, datafile)
datafile.close()
(原碼鏈接:https://pan.baidu.com/s/17dsY8Jr7HE3PD8r1sXH57A 密碼:nd7p)
歡迎各位大神交流咒劲,交流QQ群:688933850