2017-06-06 24 views
12

Tôi đang cố gắng tìm hiểu mô hình LSTM để phân tích tình cảm bằng Tensorflow, tôi đã trải qua LSTM model.Hiểu mô hình LSTM bằng cách sử dụng lưu lượng cho phân tích tình cảm

Mã sau (create_sentiment_featuresets.py) tạo từ vựng từ 5000 câu tích cực và 5000 câu tiêu cực.

import nltk 
from nltk.tokenize import word_tokenize 
import numpy as np 
import random 
from collections import Counter 
from nltk.stem import WordNetLemmatizer 

lemmatizer = WordNetLemmatizer() 

def create_lexicon(pos, neg): 
    lexicon = [] 
    with open(pos, 'r') as f: 
     contents = f.readlines() 
     for l in contents[:len(contents)]: 
      l= l.decode('utf-8') 
      all_words = word_tokenize(l) 
      lexicon += list(all_words) 
    f.close() 

    with open(neg, 'r') as f: 
     contents = f.readlines()  
     for l in contents[:len(contents)]: 
      l= l.decode('utf-8') 
      all_words = word_tokenize(l) 
      lexicon += list(all_words) 
    f.close() 

    lexicon = [lemmatizer.lemmatize(i) for i in lexicon] 
    w_counts = Counter(lexicon) 
    l2 = [] 
    for w in w_counts: 
     if 1000 > w_counts[w] > 50: 
      l2.append(w) 
    print("Lexicon length create_lexicon: ",len(lexicon)) 
    return l2 

def sample_handling(sample, lexicon, classification): 
    featureset = [] 
    print("Lexicon length Sample handling: ",len(lexicon)) 
    with open(sample, 'r') as f: 
     contents = f.readlines() 
     for l in contents[:len(contents)]: 
      l= l.decode('utf-8') 
      current_words = word_tokenize(l.lower()) 
      current_words= [lemmatizer.lemmatize(i) for i in current_words] 
      features = np.zeros(len(lexicon)) 
      for word in current_words: 
       if word.lower() in lexicon: 
        index_value = lexicon.index(word.lower()) 
        features[index_value] +=1 
      features = list(features) 
      featureset.append([features, classification]) 
    f.close() 
    print("Feature SET------") 
    print(len(featureset)) 
    return featureset 

def create_feature_sets_and_labels(pos, neg, test_size = 0.1): 
    global m_lexicon 
    m_lexicon = create_lexicon(pos, neg) 
    features = [] 
    features += sample_handling(pos, m_lexicon, [1,0]) 
    features += sample_handling(neg, m_lexicon, [0,1]) 
    random.shuffle(features) 
    features = np.array(features) 

    testing_size = int(test_size * len(features)) 

    train_x = list(features[:,0][:-testing_size]) 
    train_y = list(features[:,1][:-testing_size]) 
    test_x = list(features[:,0][-testing_size:]) 
    test_y = list(features[:,1][-testing_size:]) 
    return train_x, train_y, test_x, test_y 

def get_lexicon(): 
    global m_lexicon 
    return m_lexicon 

Các mã sau đây (sentiment_analysis.py) là dành cho phân tích tình cảm sử dụng mô hình mạng thần kinh đơn giản và đang làm việc tốt

from create_sentiment_featuresets import create_feature_sets_and_labels 
from create_sentiment_featuresets import get_lexicon 
import tensorflow as tf 
import numpy as np 
# extras for testing 
from nltk.tokenize import word_tokenize 
from nltk.stem import WordNetLemmatizer 
lemmatizer = WordNetLemmatizer() 
#- end extras 

train_x, train_y, test_x, test_y = create_feature_sets_and_labels('pos.txt', 'neg.txt') 


# pt A------------- 

n_nodes_hl1 = 1500 
n_nodes_hl2 = 1500 
n_nodes_hl3 = 1500 

n_classes = 2 
batch_size = 100 
hm_epochs = 10 

x = tf.placeholder(tf.float32) 
y = tf.placeholder(tf.float32) 

hidden_1_layer = {'f_fum': n_nodes_hl1, 
       'weight': tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])), 
       'bias': tf.Variable(tf.random_normal([n_nodes_hl1]))} 
hidden_2_layer = {'f_fum': n_nodes_hl2, 
       'weight': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 
       'bias': tf.Variable(tf.random_normal([n_nodes_hl2]))} 
hidden_3_layer = {'f_fum': n_nodes_hl3, 
       'weight': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 
       'bias': tf.Variable(tf.random_normal([n_nodes_hl3]))} 
output_layer = {'f_fum': None, 
       'weight': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])), 
       'bias': tf.Variable(tf.random_normal([n_classes]))} 


def nueral_network_model(data): 
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weight']), hidden_1_layer['bias']) 
    l1 = tf.nn.relu(l1) 
    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weight']), hidden_2_layer['bias']) 
    l2 = tf.nn.relu(l2) 
    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weight']), hidden_3_layer['bias']) 
    l3 = tf.nn.relu(l3) 
    output = tf.matmul(l3, output_layer['weight']) + output_layer['bias'] 
    return output 

# pt B-------------- 

def train_neural_network(x): 
    prediction = nueral_network_model(x) 
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits= prediction, labels= y)) 
    optimizer = tf.train.AdamOptimizer(learning_rate= 0.001).minimize(cost) 

    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 
     for epoch in range(hm_epochs): 
      epoch_loss = 0 
      i = 0 
      while i < len(train_x): 
       start = i 
       end = i+ batch_size 
       batch_x = np.array(train_x[start: end]) 
       batch_y = np.array(train_y[start: end]) 
       _, c = sess.run([optimizer, cost], feed_dict= {x: batch_x, y: batch_y}) 
       epoch_loss += c 
       i+= batch_size 
      print('Epoch', epoch+ 1, 'completed out of ', hm_epochs, 'loss:', epoch_loss) 

     correct= tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) 
     accuracy = tf.reduce_mean(tf.cast(correct, 'float')) 
     print('Accuracy:', accuracy.eval({x:test_x, y:test_y})) 

     # testing -------------- 
     m_lexicon= get_lexicon() 
     print('Lexicon length: ',len(m_lexicon))   
     input_data= "David likes to go out with Kary"  
     current_words= word_tokenize(input_data.lower()) 
     current_words = [lemmatizer.lemmatize(i) for i in current_words] 
     features = np.zeros(len(m_lexicon)) 
     for word in current_words: 
      if word.lower() in m_lexicon: 
       index_value = m_lexicon.index(word.lower()) 
       features[index_value] +=1 

     features = np.array(list(features)).reshape(1,-1) 
     print('features length: ',len(features)) 
     result = sess.run(tf.argmax(prediction.eval(feed_dict={x:features}), 1)) 
     print(prediction.eval(feed_dict={x:features})) 
     if result[0] == 0: 
      print('Positive: ', input_data) 
     elif result[0] == 1: 
      print('Negative: ', input_data) 

train_neural_network(x) 

Tôi cố gắng để thay đổi trên (sentiment_analysis. py) cho mô hình LSTM sau khi đọc RNN w/ LSTM cell example in TensorFlow and Python dành cho LSTM trên bộ dữ liệu hình ảnh mnist:

Một số cách thông qua nhiều hit và những con đường mòn chạy, tôi đã có thể để có được dưới chạy mã (sentiment_demo_lstm.py):

import tensorflow as tf 
from tensorflow.contrib import rnn 
from create_sentiment_featuresets import create_feature_sets_and_labels 
from create_sentiment_featuresets import get_lexicon 

import numpy as np 

# extras for testing 
from nltk.tokenize import word_tokenize 
from nltk.stem import WordNetLemmatizer 
lemmatizer = WordNetLemmatizer() 
#- end extras 

train_x, train_y, test_x, test_y = create_feature_sets_and_labels('pos.txt', 'neg.txt') 

n_steps= 100 
input_vec_size= len(train_x[0]) 
hm_epochs = 8 
n_classes = 2 
batch_size = 128 
n_hidden = 128 

x = tf.placeholder('float', [None, input_vec_size, 1]) 
y = tf.placeholder('float') 

def recurrent_neural_network(x): 
    layer = {'weights': tf.Variable(tf.random_normal([n_hidden, n_classes])), # hidden_layer, n_classes 
      'biases': tf.Variable(tf.random_normal([n_classes]))} 

    h_layer = {'weights': tf.Variable(tf.random_normal([1, n_hidden])), # hidden_layer, n_classes 
      'biases': tf.Variable(tf.random_normal([n_hidden], mean = 1.0))} 

    x = tf.transpose(x, [1,0,2]) 
    x = tf.reshape(x, [-1, 1]) 
    x= tf.nn.relu(tf.matmul(x, h_layer['weights']) + h_layer['biases']) 

    x = tf.split(x, input_vec_size, 0) 

    lstm_cell = rnn.BasicLSTMCell(n_hidden, state_is_tuple=True) 
    outputs, states = rnn.static_rnn(lstm_cell, x, dtype= tf.float32) 
    output = tf.matmul(outputs[-1], layer['weights']) + layer['biases'] 

    return output 

def train_neural_network(x): 
    prediction = recurrent_neural_network(x) 
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits= prediction, labels= y)) 
    optimizer = tf.train.AdamOptimizer(learning_rate= 0.001).minimize(cost) 

    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 

     for epoch in range(hm_epochs): 
      epoch_loss = 0 
      i = 0 
      while (i+ batch_size) < len(train_x): 
       start = i 
       end = i+ batch_size 
       batch_x = np.array(train_x[start: end]) 
       batch_y = np.array(train_y[start: end]) 
       batch_x = batch_x.reshape(batch_size ,input_vec_size, 1) 
       _, c = sess.run([optimizer, cost], feed_dict= {x: batch_x, y: batch_y}) 
       epoch_loss += c 
       i+= batch_size 
      print('--------Epoch', epoch+ 1, 'completed out of ', hm_epochs, 'loss:', epoch_loss) 

     correct= tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) 
     accuracy = tf.reduce_mean(tf.cast(correct, 'float')) 

     print('Accuracy:', accuracy.eval({x:np.array(test_x).reshape(-1, input_vec_size, 1), y:test_y})) 

     # testing -------------- 
     m_lexicon= get_lexicon() 
     print('Lexicon length: ',len(m_lexicon)) 
     input_data= "Mary does not like pizza" #"he seems to to be healthy today" #"David likes to go out with Kary" 

     current_words= word_tokenize(input_data.lower()) 
     current_words = [lemmatizer.lemmatize(i) for i in current_words] 
     features = np.zeros(len(m_lexicon)) 
     for word in current_words: 
      if word.lower() in m_lexicon: 
       index_value = m_lexicon.index(word.lower()) 
       features[index_value] +=1 
     features = np.array(list(features)).reshape(-1, input_vec_size, 1) 
     print('features length: ',len(features)) 

     result = sess.run(tf.argmax(prediction.eval(feed_dict={x:features}), 1)) 
     print('RESULT: ', result) 
     print(prediction.eval(feed_dict={x:features})) 
     if result[0] == 0: 
      print('Positive: ', input_data) 
     elif result[0] == 1: 
      print('Negative: ', input_data) 

train_neural_network(x) 

Sản lượng

print(train_x[0]) 
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0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ều nghi ngờ.

  1. Trong sentiment_demo_lstm, tôi không thể hiểu được phần sau

    x = tf.transpose(x, [1,0,2]) 
    x = tf.reshape(x, [-1, 1]) 
    x = tf.split(x, input_vec_size, 0) 
    

    Tôi có in các hình dạng sau:

    x = tf.placeholder('float', [None, input_vec_size, 1]) ==> TensorShape([Dimension(None), Dimension(423), Dimension(1)])) 
    x = tf.transpose(x, [1,0,2]) ==> TensorShape([Dimension(423), Dimension(None), Dimension(1)])) 
    x = tf.reshape(x, [-1, 1]) ==> TensorShape([Dimension(None), Dimension(1)])) 
    x = tf.split(x, input_vec_size, 0) ==> ? 
    
  2. Ở đây tôi đã lấy số ẩn các lớp là 128, có cần phải giống với số lượng đầu vào tức là len(train_x)= 9596

  3. Giá trị 1 trong

    x = tf.placeholder('float', [None, input_vec_size, 1]) 
    

    x = tf.reshape(x, [-1, 1]) 
    

    là vì train_x[0] là 428x ?

  4. Sau đây là để phù hợp với placeholder

    batch_x = np.array(train_x[start: end]) ==> (128, 423) 
    batch_x = batch_x.reshape(batch_size ,input_vec_size, 1) ==> (128, 423, 1) 
    

    x = tf.placeholder('float', [None, input_vec_size, 1]) kích thước, phải không?

  5. Nếu tôi sửa đổi mã:

    while (i+ batch_size) < len(train_x): 
    

    như

    while i < len(train_x): 
    

    tôi nhận được lỗi sau:

    Traceback (most recent call last): 
        File "sentiment_demo_lstm.py", line 131, in <module> 
        train_neural_network(x) 
        File "sentiment_demo_lstm.py", line 86, in train_neural_network 
        batch_x = batch_x.reshape(batch_size ,input_vec_size, 1) 
    ValueError: cannot reshape array of size 52452 into shape (128,423,1) 
    

=> Tôi không thể bao gồm 124 bản ghi/bộ tính năng cuối cùng trong khi trainin g?

+0

bạn hiện mã hóa câu của bạn sử dụng một chiếc túi của mô hình từ, LSTMs sẽ cần một chiều thời gian (do đó, một vector đặc trưng cho mỗi từ hoặc một hình dạng của ) để làm cho nó work- thông thường bạn có thể làm điều này với một lớp nhúng. Hãy xem ví dụ trong Keras về cơ bản thực hiện những gì bạn cần (https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py). –

+1

Bạn có rất nhiều câu hỏi ở đây. Nó có thể là tốt để tách ra câu hỏi này ngoài. – erip

Trả lời

9

Đây là câu hỏi được tải. Hãy để tôi cố gắng đặt nó bằng tiếng Anh đơn giản ẩn tất cả các chi tiết bên trong phức tạp:

Một mô hình LSTM chưa được kiểm tra đơn giản với 3 bước được hiển thị bên dưới. Mỗi ô LSTM lấy một vector đầu vào và vector đầu ra ẩn của ô LSTM trước đó và tạo ra một vector đầu ra và đầu ra ẩn cho ô LSTM tiếp theo.

enter image description here

Một biểu diễn ngắn gọn về các mô hình tương tự được hiển thị dưới đây.

enter image description here

mô hình LSTM là chuỗi các mô hình chuỗi, tức là, chúng được sử dụng cho các vấn đề khi một chuỗi phải được dán nhãn với một chuỗi khác, như gắn thẻ POS hoặc gắn thẻ NER của mỗi từ trong một câu.

Dường như bạn đang sử dụng nó cho vấn đề phân loại. Có hai cách có thể sử dụng mô hình LSTM để phân loại

1) Lấy đầu ra của tất cả các trạng thái (O1, O2 và O3 trong ví dụ của chúng ta) và áp dụng lớp softmax với kích thước đầu ra lớp softmax bằng số lớp (2 trong trường hợp của bạn)

2) Lấy đầu ra của trạng thái cuối cùng (O3) và áp dụng lớp softmax cho nó. (Đây là những gì bạn đang làm trong cod của bạn. Kết quả đầu ra [-1] trả về hàng cuối cùng trong kết quả đầu ra)

Vì vậy, chúng tôi lại tuyên truyền (Backpropagation Through Time - BTT) về lỗi của đầu ra softmax.

Đến với việc triển khai sử dụng Tensorflow, hãy xem đầu vào và đầu ra cho mô hình LSTM là gì.

Mỗi LSTM nhận đầu vào, nhưng chúng tôi có 3 ô LSTM như vậy, Vì vậy, đầu vào (trình giữ chỗ X) phải có kích thước (đầu vào * bước thời gian). Nhưng chúng tôi không tính toán lỗi cho đầu vào đơn và BTT cho nó, nhưng thay vào đó chúng tôi thực hiện nó trên một loạt các kết hợp đầu vào - đầu ra. Vì vậy, đầu vào của LSTM sẽ được (batchsize * inputize * bước thời gian).

Một ô LSTM được xác định với kích thước của trạng thái ẩn. Kích cỡ đầu ra và vector đầu ra ẩn của ô LSTM sẽ giống như kích thước của các trạng thái ẩn (Kiểm tra các phép tính nội bộ LSTM vì lý do tại sao!). Sau đó chúng ta định nghĩa một mô hình LSTM bằng cách sử dụng một danh sách các ô LSTM này, trong đó kích thước của danh sách sẽ bằng với số lượng unrolling của mô hình. Vì vậy, chúng tôi xác định số lượng unrolling được thực hiện và kích thước của đầu vào trong mỗi unrolling.

Tôi đã bỏ qua rất nhiều thứ như cách xử lý chuỗi độ dài biến đổi, trình tự để tính toán sai số chuỗi, Cách LSTM tính toán đầu ra và đầu ra ẩn, v.v.

Đến với triển khai của bạn, bạn đang áp dụng một lớp relu trước đầu vào của mỗi ô LSTM. Tôi không hiểu tại sao bạn đang làm điều đó nhưng tôi đoán bạn đang làm nó để ánh xạ kích thước đầu vào của bạn với kích thước đầu vào LSTM.

Đến với câu hỏi của bạn:

  1. x là placeholder (tensor/ma trận/ndarray) kích thước [Không, input_vec_size, 1]. tức là nó có thể lấy số hàng thay đổi nhưng mỗi hàng có các cột input_vec_size và mỗi phần tử là một vectơ là kích thước 1. Các trình giữ chỗ thông thường được định nghĩa với "Không" trong các hàng để chúng ta có thể thay đổi kích cỡ lô của đầu vào.

phép nói input_vec_size = 3

Bạn đang đi qua một ndarray kích thước [128 * 3 * 1]

x = tf.transpose (x, [1,0,2]) - -> [3 * 128 * 1]

x = tf.reshape (x, [-1, 1]) -> [384 * 1]

h_layer [ 'trọng lượng'] -> [ 1, 128]

x = tf.nn.relu (tf.matmul (x, h_layer ['trọng số']) + [_4] 128]

  1. Không có kích thước đầu vào nào bị ẩn là khác nhau. LSTM thực hiện một tập hợp các phép toán trên đầu vào và đầu ra ẩn trước đó và cho ra một đầu ra và đầu ra ẩn tiếp theo, cả hai đều có kích thước ẩn kích thước.

  2. x = tf.placeholder ('phao', [Không, input_vec_size, 1])

Nó định nghĩa một tensor hoặc số ndarray hoặc biến của các hàng, mỗi hàng có cột input_vec_size một và mỗi giá trị là một vector giá trị đơn.

x = tf.reshape (x, [-1, 1]) -> định dạng lại x đầu vào thành ma trận có kích thước cố định thành 1 cột và bất kỳ số hàng nào.

  1. batch_x = batch_x.reshape (batch_size, input_vec_size, 1)

batch_x.reshape sẽ thất bại nếu số giá trị trong batch_x! = Batch_size * input_vec_size * 1. Điều này có thể là trường hợp cho đợt cuối bởi vì len (train_x) có thể không phải là bội số của batch_size dẫn đến lô không đầy đủ cuối cùng.

Bạn có thể tránh vấn đề này bằng cách sử dụng

batch_x = batch_x.reshape(-1 ,input_vec_size, 1) 

Nhưng tôi vẫn không chắc chắn lý do tại sao bạn đang sử dụng Relu ở phía trước của lớp đầu vào.

Bạn đang áp dụng hồi quy logistic ở đầu ra của ô cuối cùng.

Bạn có thể xem ví dụ về đồ chơi của tôi là một trình phân loại sử dụng LSTM hai chiều để phân loại xem chuỗi có tăng hoặc giảm hoặc trộn hay không.

Toy sequence_classifier using LSTM in Tensorflow

+0

bạn có thể cho tôi biết về x = tf.split (x, input_vec_size, 0) không. Ngoài ra, bạn có thể giới thiệu cho tôi bất kỳ tài liệu tham khảo hoặc giấy hoặc hướng dẫn nào để hiểu kỹ mô hình LSTM và việc triển khai thực hiện của nó trong tensorflow để phân loại – LinuxBeginner

+0

x = tf.split (x, input_vec_size, 0) -> [3 tensors mỗi kích thước 384/3 * 1] tức là cắt đầu vào tensor trong dimth 0 (hàng khôn ngoan trong trường hợp này) thành 3 và do đó mỗi chia tensor sẽ có kích thước 384/3 * 1. Bạn có thể tìm thấy một rất đơn giản implemetation từ đầu trong liên kết tôi đã đưa ra trong câu trả lời ở trên. Hoặc bạn có thể theo liên kết này https://github.com/aymericdamien/TensorFlow-Examples và trong phần "Xử lý ngôn ngữ tự nhiên", bạn sẽ có một số triển khai tốt nhưng họ sử dụng tflearn, đây là một trừu tượng trong tensorflow – mujjiga

+0

trong ** sentiment_analysis.py ** chúng ta có thể xác định số lượng các nút trong mỗi lớp ẩn, làm thế nào chúng ta có thể định nghĩa giống nhau trong mô hình LSTM? – LinuxBeginner

Các vấn đề liên quan