使用TensorFlow理解LSTM模型进行情感分析

15

我正在尝试使用Tensorflow学习LSTM模型进行情感分析,我已经阅读了LSTM模型

下面的代码(create_sentiment_featuresets.py)5000个正向句子和5000个负向句子中生成词汇表。

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

以下代码 (sentiment_analysis.py) 用于使用简单神经网络模型进行情感分析,并且工作正常。
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)

我正在尝试修改上述(sentiment_analysis.py)的LSTM模型。在阅读了TensorFlow和Python中LSTM单元的RNN示例,该示例是针对mnist图像数据集的:

在经过多次尝试后,我终于得到了下面运行的代码(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)

输出

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, 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.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, 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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.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, 1.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, 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.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

print(train_y[0])
[0, 1]
len(train_x)= 9596, len(train_x[0]) = 423 意味着train_x是一个9596x423的列表?
  1. In sentiment_demo_lstm, I am not able to understand the following part

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

    I have print the following shapes:

    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. Here I took the number of hidden layers as 128, does it need to be same as the number of inputs i.e. len(train_x)= 9596

  3. The value 1 in

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

    and

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

    is because train_x[0] is 428x1 ?

  4. The following is in order to match the 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]) dimensions, right?

  5. If I modified the code:

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

    as

    while i < len(train_x):
    

    I get the following error:

    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)
    

=> 我不能在训练时包括最后124个记录/特征集吗?


你目前使用词袋模型对句子进行编码,LSTMs需要一个时间维度(因此每个单词需要一个特征向量或形状为<batch_size,timestep,features>)才能使其工作-通常可以通过嵌入层完成。看一下Keras中的示例,它基本上可以做到你所需的(https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py)。 - Thomas Jungblut
1
你在这里有很多问题。最好是将这个问题分开来。 - erip
1个回答

12
这是一个具有3个步骤的简单展开LSTM模型,下面显示了每个LSTM单元接受输入向量和前一个LSTM单元的隐藏输出向量,并产生输出向量和下一个LSTM单元的隐藏输出。请注意,本文只提供简明英语,不包含复杂内部细节。保留HTML标签。

enter image description here

下面展示了该模型的简明表示。

enter image description here

LSTM模型是序列到序列模型,即用于需要将一个序列标记为另一个序列的问题,例如POS标记或NER标记句子中每个单词。您似乎正在将其用于分类问题。使用LSTM模型进行分类有两种可能的方法:1)获取所有状态(在我们的示例中为O1、O2和O3)的输出,并应用具有softmax层输出大小等于类数(在您的情况下为2)的softmax层;2)获取最后一个状态(O3)的输出并对其应用softmax层(这是您在代码中所做的。outputs [-1]返回输出中的最后一行)。因此,我们在softmax输出的错误上进行反向传播(时间反向传播-BTT)。关于使用Tensorflow实现,让我们看看LSTM模型的输入和输出是什么。
每个LSTM都需要一个输入,但我们有3个这样的LSTM单元,因此输入(X占位符)的大小应为(输入大小*时间步长)。但是我们不会为单个输入计算错误并进行BTT,而是在一批输入 - 输出组合上执行。因此,LSTM的输入将是(批量大小*输入大小*时间步长)。
LSTM单元的大小定义为隐藏状态的大小。LSTM单元的输出大小和隐藏输出向量的大小将与隐藏状态的大小相同(请检查LSTM内部计算原理!)。然后,我们使用这些LSTM单元的列表定义LSTM模型,其中列表的大小将等于模型展开次数。因此,我们定义要执行的展开次数以及每次展开期间的输入大小。
我跳过了很多事情,例如如何处理可变长度序列,序列到序列的误差计算,LSTM如何计算输出和隐藏输出等。
谈到你的实现,你在每个LSTM单元的输入之前应用了一个relu层。我不明白为什么你这样做,但我猜你这样做是为了将输入大小映射到LSTM输入大小。
回答你的问题:
  1. x是一个占位符(张量/矩阵/ndarray),大小为[None,input_vec_size,1]。也就是说,它可以接受可变数量的行,但每行都有input_vec_size列,每个元素的向量大小为1。通常,在行中使用“None”定义占位符,以便我们可以改变输入的批处理大小。

假设input_vec_size = 3

您正在传递大小为[128 * 3 * 1]的ndarray

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

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

h_layer ['weights'] --> [1,128]

x = tf.nn.relu(tf.matmul(x,h_layer ['weights']) + h_layer ['biases']) --> [384 * 128]

  1. 没有输入大小和隐藏大小的差异。LSTM对输入和上一个隐藏输出执行一组操作,并给出大小为隐藏大小的输出和下一个隐藏输出。

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

它定义了一个张量或ndarray或变量行数,每行有input_vec_size列,每个值都是单个值向量。

x = tf.reshape(x,[-1,1]) --> 将输入x重新塑造成一个大小固定为1列和任意行数的矩阵。

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

如果batch_x中的值数量不等于batch_size * input_vec_size * 1,则batch_x.reshape将失败。这可能是最后一个批次的情况,因为len(train_x)可能不是batch_size的倍数,导致最后一个批次未完全填充。

您可以通过使用

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

但我仍然不确定为什么您要在输入层前使用Relu。

在最后一个单元格的输出处应用逻辑回归是可以的。

您可以查看我的玩具示例,其中使用双向LSTM进行分类,以识别序列是增加、减少还是混合的。

使用Tensorflow中的LSTM进行序列分类的玩具示例


请问一下x = tf.split(x, input_vec_size, 0)的具体含义。还有,您能否推荐任何参考资料、论文或教程,以深入了解LSTM模型及其在TensorFlow中进行分类的实现? - LinuxBeginner
x = tf.split(x, input_vec_size, 0) --> [每个大小为384/3 * 1的3个张量],即按第0维(在此情况下是行)将输入张量分成3份,因此每个分割张量的大小都将是384/3 * 1。您可以在我上面给出的链接中找到一个非常简单的从头开始的实现。或者您可以遵循此链接https://github.com/aymericdamien/TensorFlow-Examples,在“自然语言处理”部分下找到一些很好的实现,但它们使用tflearn,这是tensorflow中的一种抽象。 - mujjiga
sentiment_analysis.py 中,我们可以定义每个隐藏层中节点的数量,那么在 LSTM 模型中如何定义相同的节点数量呢? - LinuxBeginner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接