學(xué)習(xí)資料:
https://www.youtube.com/watch?v=si8zZHkufRY&list=PL2-dafEMk2A7YdKv4XfKpfbTH5z6rEEj3&index=5
情感分析,
就是要識別出用戶對一件事一個物或一個人的看法、態(tài)度,比如一個電影的評論,一個商品的評價,一次體驗的感想等等。根據(jù)對帶有情感色彩的主觀性文本進行分析,識別出用戶的態(tài)度,是喜歡,討厭,還是中立。

關(guān)于情感分析,之前有一篇 cs224d 的小項目:
里面用 skipgram 學(xué)習(xí)出 word vector,然后用 softmax regression 進行識別:
怎樣做情感分析
今天的方法是用 20 行代碼實現(xiàn)這個過程:
用 tflearn.data_utils 的 pad_sequences 將 strings 轉(zhuǎn)化成向量,用 tflearn.embedding 得到 word vector,再傳遞給 LSTM 得到 feature vector,經(jīng)過全聯(lián)接層后,再用一個分類器,loss 為 categorical_crossentropy
- 數(shù)據(jù)用 tflearn 里面預(yù)先處理好的 imdb,IMDB 是一個電影評論的數(shù)據(jù)庫。
from __future__ import division, print_function, absolute_import
import tflearn
from tflearn.data_utils import to_categorical, pad_sequences
from tflearn.datasets import imdb
- path 是存儲的路經(jīng),pkl 是 byte stream 格式,用這個格式在后面比較容易轉(zhuǎn)換成 list 或者 tuple。
n_words 為從數(shù)據(jù)庫中取出來的詞個數(shù)。
# IMDB Dataset loading
train, test, _ = imdb.load_data(path='imdb.pkl', n_words=10000,
valid_portion=0.1)
trainX, trainY = train
testX, testY = test
-
pad sequence 將 inputs 轉(zhuǎn)化成矩陣形式,并用 0 補齊到最大維度,這樣可以保持維度的一致性。
# Data preprocessing
# Sequence padding
trainX = pad_sequences(trainX, maxlen=100, value=0.)
testX = pad_sequences(testX, maxlen=100, value=0.)
- to_categorical 將 labels 轉(zhuǎn)化為 01 向量
# Converting labels to binary vectors
trainY = to_categorical(trainY, nb_classes=2)
testY = to_categorical(testY, nb_classes=2)
- 輸入層,batch size 設(shè)為 None,length=100=前面的max sequence length
# Network building
net = tflearn.input_data([None, 100])
- 上一層的輸出作為下一層的輸入,input_dim 是前面設(shè)定的從數(shù)據(jù)庫中取了多少個單詞,output_dim 就是得到 embedding 向量的維度

net = tflearn.embedding(net, input_dim=10000, output_dim=128)
- 模型用的 LSTM,可以保持記憶,dropout 為了減小過擬合
net = tflearn.lstm(net, 128, dropout=0.8)
- fully_connected 是指前一層的每一個神經(jīng)元都和后一層的所有神經(jīng)元相連,
將前面 LSTM 學(xué)習(xí)到的 feature vectors 傳到全網(wǎng)絡(luò)中,可以很輕松地學(xué)習(xí)它們的非線性組合關(guān)系
激活函數(shù)用 softmax 來得到概率值

net = tflearn.fully_connected(net, 2, activation='softmax')
- 最后應(yīng)用一個分類器,定義優(yōu)化器,學(xué)習(xí)率,損失函數(shù)
net = tflearn.regression(net, optimizer='adam', learning_rate=0.001,
loss='categorical_crossentropy')
# Training
# 模型初始化
model = tflearn.DNN(net, tensorboard_verbose=0)
# show_metric=True 可以看到過程中的準確率
model.fit(trainX, trainY, validation_set=(testX, testY), show_metric=True,
batch_size=32)

推薦閱讀 歷史技術(shù)博文鏈接匯總
http://www.itdecent.cn/p/28f02bb59fe5
也許可以找到你想要的:
[入門問題][TensorFlow][深度學(xué)習(xí)][強化學(xué)習(xí)][神經(jīng)網(wǎng)絡(luò)][機器學(xué)習(xí)][自然語言處理][聊天機器人]
