使用张量流理解 LSTM 模型进行情感分析

2024-03-03

我正在尝试使用 Tensorflow 学习 LSTM 模型进行情感分析,我已经经历了LSTM模型 http://colah.github.io/posts/2015-08-Understanding-LSTMs/.

以下代码(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

下面的代码(情绪分析.py) is for 使用简单的神经网络模型进行情感分析并且工作正常

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)

我正在尝试修改 LSTM 模型的上述(sentiment_analysis.py)阅读后TensorFlow 和 Python 中带有 LSTM 单元的 RNN 示例 https://pythonprogramming.net/rnn-tensorflow-python-machine-learning-tutorial/?completed=/recurrent-neural-network-rnn-lstm-machine-learning-tutorial/这是 LSTM 上的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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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, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 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 情感演示lstm,我无法理解以下部分

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

    我打印了以下形状:

    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. 这里我将隐藏层的数量设为128,它是否需要与输入的数量相同,即len(train_x)= 9596

  3. 值 1 在

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

    and

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

    是因为train_x[0] is 428x1 ?

  4. 以下是为了匹配占位符

    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])尺寸,对吗?

  5. 如果我修改代码:

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

    as

    while i < len(train_x):
    

    我收到以下错误:

    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 条记录/特征集?


这是一个有负载的问题。让我尝试用简单的英语表达它,隐藏所有复杂的内部细节:

下面显示了一个包含 3 个步骤的简单展开 LSTM 模型。每个 LSTM 单元采用一个输入向量和前一个 LSTM 单元的隐藏输出向量,并为下一个 LSTM 单元生成输出向量和隐藏输出。

同一模型的简明表示如下所示。

LSTM 模型是序列到序列模型,即,它们用于解决必须用另一个序列标记一个序列的问题,例如句子中每个单词的 POS 标记或 NER 标记。

您似乎将它用于分类问题。使用LSTM模型进行分类有两种可能的方式

1) 获取所有状态的输出(在我们的示例中为 O1、O2 和 O3)并应用 softmax 层,其中 softmax 层输出大小等于类数(在您的例子中为 2)

2) 获取最后状态 (O3) 的输出并对其应用 softmax 层。 (这就是您在 cod.outputs[-1] 中所做的事情,返回输出中的最后一行)

因此,我们对 softmax 输出的误差进行反向传播(随着时间的反向传播 - BTT)。

接下来使用 Tensorflow 进行实现,让我们看看 LSTM 模型的输入和输出是什么。

每个 LSTM 都有一个输入,但我们有 3 个这样的 LSTM 单元,因此输入(X 占位符)的大小应该为(输入大小 * 时间步长)。但我们不会计算单个输入的误差和 BTT,而是对一批输入-输出组合进行计算。因此 LSTM 的输入将为(batchsize * inputsize * time steps)。

LSTM 单元由隐藏状态的大小定义。 LSTM 单元的输出和隐藏输出向量的大小将与隐藏状态的大小相同(请检查 LSTM 内部计算以了解原因!)。然后,我们使用这些 LSTM 单元的列表定义 LSTM 模型,其中列表的大小等于模型展开的数量。因此,我们定义要完成的展开次数以及每次展开期间的输入大小。

我跳过了很多东西,比如如何处理可变长度序列、序列到序列的错误计算、LSTM 如何计算输出和隐藏输出等。

在实现过程中,您将在每个 LSTM 单元的输入之前应用一个 relu 层。我不明白你为什么这样做,但我猜你这样做是为了将你的输入大小映射到 LSTM 输入大小。

回答你的问题:

  1. x 是大小为 [None, input_vec_size, 1] 的占位符(张量/矩阵/ndarray)。即它可以采用可变数量的行,但每行都有 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['权重'] --> [1, 128]

x= tf.nn.relu(tf.matmul(x, h_layer['权重']) + h_layer['偏差']) --> [384 * 128]

  1. 没有输入大小,隐藏大小是不同的。 LSTM 对输入和前一个隐藏输出执行一组操作,并给定一个输出和下一个隐藏输出,两者的大小都是隐藏大小。

  2. x = tf.placeholder('float', [无, 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 玩具序列分类器 https://github.com/smujjiga/ml/blob/master/tf/sequence_classifier.py

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用张量流理解 LSTM 模型进行情感分析 的相关文章

随机推荐