当前位置:   article > 正文

[NLP] PyTorch 实现双向LSTM 情感分析

双向lstm

一  前言

情感分析(Sentiment Analysis),也称为情感分类,属于自然语言处理(Natural Language Processing,NLP)领域的一个分支任务,随着互联网的发展而兴起。多数情况下该任务分析一个文本所呈现的信息是正面、负面或者中性,也有一些研究会区分得更细,例如在正负极性中再进行分级,区分不同情感强度.

文本情感分析(Sentiment Analysis)是自然语言处理(NLP)方法中常见的应用,也是一个有趣的基本任务,尤其是以提炼文本情绪内容为目的的分类。它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程。
情感分析中的情感极性(倾向)分析。所谓情感极性分析,指的是对文本进行褒义、贬义、中性的判断。在大多应用场景下,只分为两类。例如对于“喜爱”和“厌恶”这两个词,就属于不同的情感倾向。

本文将采用LSTM模型,训练一个能够识别文本postive, negative情感的分类器。

RNN网络因为使用了单词的序列信息,所以准确率要比前向传递神经网络要高。
 

网络结构:

首先,将单词传入 embedding层,之所以使用嵌入层,是因为单词数量太多,使用嵌入式词向量来表示单词更有效率。在这里我们使用word2vec方式来实现,而且特别神奇的是,我们只需要加入嵌入层即可,网络会自主学习嵌入矩阵

参考下图

通过embedding 层, 新的单词表示传入 LSTM cells。这将是一个递归链接网络,所以单词的序列信息会在网络之间传递。最后, LSTM cells连接一个sigmoid output layer 。 使用sigmoid可以预测该文本是 积极的 还是 消极的 情感。输出层只有一个单元节点(使用sigmoid激活)。

只需要关注最后一个sigmoid的输出,损失只计算最后一步的输出和标签的差异。

文件说明:
(1)reviews.txt 是原始文本文件,共25000条,一行是一篇英文电影影评文本
(2)labels.txt 是标签文件,共25000条,一行是一个标签,positive 或者 negative

二   模型训练与预测

1、Data Preprocessing
建任何模型的第一步,永远是数据清洗。 因为使用embedding 层,需要将单词编码成整数。

我们要去除标点符号。 同时,去除不同文本之间有分隔符号 \n,我们先把\n当成分隔符号,分割所有评论。 然后在将所有评论再次连接成为一个大的文本。

  1. import numpy as np
  2. # read data from text files
  3. with open('./data/reviews.txt', 'r') as f:
  4. reviews = f.read()
  5. with open('./data/labels.txt', 'r') as f:
  6. labels = f.read()
  7. print(reviews[:1000])
  8. print()
  9. print(labels[:20])

  1. from string import punctuation
  2. # get rid of punctuation
  3. reviews = reviews.lower() # lowercase, standardize
  4. all_text = ''.join([c for c in reviews if c not in punctuation])
  5. # split by new lines and spaces
  6. reviews_split = all_text.split('\n')
  7. all_text = ' '.join(reviews_split)
  8. # create a list of words
  9. words = all_text.split()

2、Encoding the words

embedding lookup要求输入的网络数据是整数。最简单的方法就是创建数据字典:{单词:整数}。然后将评论全部一一对应转换成整数,传入网络。

  1. # feel free to use this import
  2. from collections import Counter
  3. ## Build a dictionary that maps words to integers
  4. counts = Counter(words)
  5. vocab = sorted(counts, key=counts.get, reverse=True)
  6. vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}
  7. ## use the dict to tokenize each review in reviews_split
  8. ## store the tokenized reviews in reviews_ints
  9. reviews_ints = []
  10. for review in reviews_split:
  11. reviews_ints.append([vocab_to_int[word] for word in review.split()])
  12. # stats about vocabulary
  13. print('Unique words: ', len((vocab_to_int))) # should ~ 74000+
  14. print()
  15. # print tokens in first review
  16. print('Tokenized review: \n', reviews_ints[:1])

补充enumerate函数用法:
在enumerate函数内写上int整型数字,则以该整型数字作为起始去迭代生成结果。

3、Encoding the labels

将标签 “positive” or "negative"转换为数值。

  1. # 1=positive, 0=negative label conversion
  2. labels_split = labels.split('\n')
  3. encoded_labels = np.array([1 if label == 'positive' else 0 for label in labels_split])
  4. # outlier review stats
  5. review_lens = Counter([len(x) for x in reviews_ints])
  6. print("Zero-length reviews: {}".format(review_lens[0]))
  7. print("Maximum review length: {}".format(max(review_lens)))

消除长度为0的行

  1. print('Number of reviews before removing outliers: ', len(reviews_ints))
  2. ## remove any reviews/labels with zero length from the reviews_ints list.
  3. # get indices of any reviews with length 0
  4. non_zero_idx = [ii for ii, review in enumerate(reviews_ints) if len(review) != 0]
  5. # remove 0-length reviews and their labels
  6. reviews_ints = [reviews_ints[ii] for ii in non_zero_idx]
  7. encoded_labels = np.array([encoded_labels[ii] for ii in non_zero_idx])
  8. print('Number of reviews after removing outliers: ', len(reviews_ints))

4、Padding sequences

将所以句子统一长度为200个单词:
1、评论长度小于200的,我们对其左边填充0
2、对于大于200的,我们只截取其前200个单词

  1. #选择每个句子长为200
  2. seq_len = 200
  3. from tensorflow.contrib.keras import preprocessing
  4. features = np.zeros((len(reviews_ints),seq_len),dtype=int)
  5. #将reviews_ints值逐行 赋值给features
  6. features = preprocessing.sequence.pad_sequences(reviews_ints,200)
  7. features.shape

或者

  1. def pad_features(reviews_ints, seq_length):
  2. ''' Return features of review_ints, where each review is padded with 0's
  3. or truncated to the input seq_length.
  4. '''
  5. # getting the correct rows x cols shape
  6. features = np.zeros((len(reviews_ints), seq_length), dtype=int)
  7. # for each review, I grab that review and
  8. for i, row in enumerate(reviews_ints):
  9. features[i, -len(row):] = np.array(row)[:seq_length]
  10. return features
  11. # Test your implementation!
  12. seq_length = 200
  13. features = pad_features(reviews_ints, seq_length=seq_length)
  14. ## test statements - do not change - ##
  15. assert len(features)==len(reviews_ints), "Your features should have as many rows as reviews."
  16. assert len(features[0])==seq_length, "Each feature row should contain seq_length values."
  17. # print first 10 values of the first 30 batches
  18. print(features[:30,:10])

5、Training, Test划分

  1. split_frac = 0.8
  2. ## split data into training, validation, and test data (features and labels, x and y)
  3. split_idx = int(len(features)*split_frac)
  4. train_x, remaining_x = features[:split_idx], features[split_idx:]
  5. train_y, remaining_y = encoded_labels[:split_idx], encoded_labels[split_idx:]
  6. test_idx = int(len(remaining_x)*0.5)
  7. val_x, test_x = remaining_x[:test_idx], remaining_x[test_idx:]
  8. val_y, test_y = remaining_y[:test_idx], remaining_y[test_idx:]
  9. ## print out the shapes of your resultant feature data
  10. print("\t\t\tFeature Shapes:")
  11. print("Train set: \t\t{}".format(train_x.shape),
  12. "\nValidation set: \t{}".format(val_x.shape),
  13. "\nTest set: \t\t{}".format(test_x.shape))

  1. from sklearn.model_selection import ShuffleSplit
  2. ss = ShuffleSplit(n_splits=1,test_size=0.2,random_state=0)
  3. for train_index,test_index in ss.split(np.array(reviews_ints)):
  4. train_x = features[train_index]
  5. train_y = labels[train_index]
  6. test_x = features[test_index]
  7. test_y = labels[test_index]
  8. print("\t\t\tFeature Shapes:")
  9. print("Train set: \t\t{}".format(train_x.shape),
  10. "\nTrain_Y set: \t{}".format(train_y.shape),
  11. "\nTest set: \t\t{}".format(test_x.shape))

6. DataLoaders and Batching

  1. import torch
  2. from torch.utils.data import TensorDataset, DataLoader
  3. # create Tensor datasets
  4. train_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))
  5. valid_data = TensorDataset(torch.from_numpy(val_x), torch.from_numpy(val_y))
  6. test_data = TensorDataset(torch.from_numpy(test_x), torch.from_numpy(test_y))
  7. # dataloaders
  8. batch_size = 50
  9. # make sure the SHUFFLE your training data
  10. train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)
  11. valid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)
  12. test_loader = DataLoader(test_data, shuffle=True, batch_size=batch_size)

  1. # obtain one batch of training data
  2. dataiter = iter(train_loader)
  3. sample_x, sample_y = dataiter.next()
  4. print('Sample input size: ', sample_x.size()) # batch_size, seq_length
  5. print('Sample input: \n', sample_x)
  6. print()
  7. print('Sample label size: ', sample_y.size()) # batch_size
  8. print('Sample label: \n', sample_y)

7. 双向LSTM模型

1. 判断是否有GPU

  1. # First checking if GPU is available
  2. train_on_gpu=torch.cuda.is_available()
  3. if(train_on_gpu):
  4. print('Training on GPU.')
  5. else:
  6. print('No GPU available, training on CPU.')
  1. import torch.nn as nn
  2. class SentimentRNN(nn.Module):
  3. """
  4. The RNN model that will be used to perform Sentiment analysis.
  5. """
  6. def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, bidirectional=True, drop_prob=0.5):
  7. """
  8. Initialize the model by setting up the layers.
  9. """
  10. super(SentimentRNN, self).__init__()
  11. self.output_size = output_size
  12. self.n_layers = n_layers
  13. self.hidden_dim = hidden_dim
  14. self.bidirectional = bidirectional
  15. # embedding and LSTM layers
  16. self.embedding = nn.Embedding(vocab_size, embedding_dim)
  17. self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers,
  18. dropout=drop_prob, batch_first=True,
  19. bidirectional=bidirectional)
  20. # dropout layer
  21. self.dropout = nn.Dropout(0.3)
  22. # linear and sigmoid layers
  23. if bidirectional:
  24. self.fc = nn.Linear(hidden_dim*2, output_size)
  25. else:
  26. self.fc = nn.Linear(hidden_dim, output_size)
  27. self.sig = nn.Sigmoid()
  28. def forward(self, x, hidden):
  29. """
  30. Perform a forward pass of our model on some input and hidden state.
  31. """
  32. batch_size = x.size(0)
  33. # embeddings and lstm_out
  34. x = x.long()
  35. embeds = self.embedding(x)
  36. lstm_out, hidden = self.lstm(embeds, hidden)
  37. # if bidirectional:
  38. # lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim*2)
  39. # else:
  40. # lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)
  41. # dropout and fully-connected layer
  42. out = self.dropout(lstm_out)
  43. out = self.fc(out)
  44. # sigmoid function
  45. sig_out = self.sig(out)
  46. # reshape to be batch_size first
  47. sig_out = sig_out.view(batch_size, -1)
  48. sig_out = sig_out[:, -1] # get last batch of labels
  49. # return last sigmoid output and hidden state
  50. return sig_out, hidden
  51. def init_hidden(self, batch_size):
  52. ''' Initializes hidden state '''
  53. # Create two new tensors with sizes n_layers x batch_size x hidden_dim,
  54. # initialized to zero, for hidden state and cell state of LSTM
  55. weight = next(self.parameters()).data
  56. number = 1
  57. if self.bidirectional:
  58. number = 2
  59. if (train_on_gpu):
  60. hidden = (weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_().cuda(),
  61. weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_().cuda()
  62. )
  63. else:
  64. hidden = (weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_(),
  65. weight.new(self.n_layers*number, batch_size, self.hidden_dim).zero_()
  66. )
  67. return hidden

是否使用双向LSTM(在测试集上效果更好一些)

  1. # Instantiate the model w/ hyperparams
  2. vocab_size = len(vocab_to_int)+1 # +1 for the 0 padding + our word tokens
  3. output_size = 1
  4. embedding_dim = 400
  5. hidden_dim = 256
  6. n_layers = 2
  7. bidirectional = False #这里为True,为双向LSTM
  8. net = SentimentRNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, bidirectional)
  9. print(net)

8 Train

  1. # loss and optimization functions
  2. lr=0.001
  3. criterion = nn.BCELoss()
  4. optimizer = torch.optim.Adam(net.parameters(), lr=lr)
  5. # training params
  6. epochs = 4 # 3-4 is approx where I noticed the validation loss stop decreasing
  7. print_every = 100
  8. clip=5 # gradient clipping
  9. # move model to GPU, if available
  10. if(train_on_gpu):
  11. net.cuda()
  12. net.train()
  13. # train for some number of epochs
  14. for e in range(epochs):
  15. # initialize hidden state
  16. h = net.init_hidden(batch_size)
  17. counter = 0
  18. # batch loop
  19. for inputs, labels in train_loader:
  20. counter += 1
  21. if(train_on_gpu):
  22. inputs, labels = inputs.cuda(), labels.cuda()
  23. # Creating new variables for the hidden state, otherwise
  24. # we'd backprop through the entire training history
  25. h = tuple([each.data for each in h])
  26. # zero accumulated gradients
  27. net.zero_grad()
  28. # get the output from the model
  29. output, h = net(inputs, h)
  30. # calculate the loss and perform backprop
  31. loss = criterion(output.squeeze(), labels.float())
  32. loss.backward()
  33. # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.
  34. nn.utils.clip_grad_norm_(net.parameters(), clip)
  35. optimizer.step()
  36. # loss stats
  37. if counter % print_every == 0:
  38. # Get validation loss
  39. val_h = net.init_hidden(batch_size)
  40. val_losses = []
  41. net.eval()
  42. for inputs, labels in valid_loader:
  43. # Creating new variables for the hidden state, otherwise
  44. # we'd backprop through the entire training history
  45. val_h = tuple([each.data for each in val_h])
  46. if(train_on_gpu):
  47. inputs, labels = inputs.cuda(), labels.cuda()
  48. output, val_h = net(inputs, val_h)
  49. val_loss = criterion(output.squeeze(), labels.float())
  50. val_losses.append(val_loss.item())
  51. net.train()
  52. print("Epoch: {}/{}...".format(e+1, epochs),
  53. "Step: {}...".format(counter),
  54. "Loss: {:.6f}...".format(loss.item()),
  55. "Val Loss: {:.6f}".format(np.mean(val_losses)))

9 Test

  1. # Get test data loss and accuracy
  2. test_losses = [] # track loss
  3. num_correct = 0
  4. # init hidden state
  5. h = net.init_hidden(batch_size)
  6. net.eval()
  7. # iterate over test data
  8. for inputs, labels in test_loader:
  9. # Creating new variables for the hidden state, otherwise
  10. # we'd backprop through the entire training history
  11. h = tuple([each.data for each in h])
  12. if(train_on_gpu):
  13. inputs, labels = inputs.cuda(), labels.cuda()
  14. # get predicted outputs
  15. output, h = net(inputs, h)
  16. # calculate loss
  17. test_loss = criterion(output.squeeze(), labels.float())
  18. test_losses.append(test_loss.item())
  19. # convert output probabilities to predicted class (0 or 1)
  20. pred = torch.round(output.squeeze()) # rounds to the nearest integer
  21. # compare predictions to true label
  22. correct_tensor = pred.eq(labels.float().view_as(pred))
  23. correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu else np.squeeze(correct_tensor.cpu().numpy())
  24. num_correct += np.sum(correct)
  25. # -- stats! -- ##
  26. # avg test loss
  27. print("Test loss: {:.3f}".format(np.mean(test_losses)))
  28. # accuracy over all test data
  29. test_acc = num_correct/len(test_loader.dataset)
  30. print("Test accuracy: {:.3f}".format(test_acc))

 三.   模型Inference

  1. # negative test review
  2. test_review_neg = 'The worst movie I have seen; acting was terrible and I want my money back. This movie had bad acting and the dialogue was slow.'
  1. from string import punctuation
  2. def tokenize_review(test_review):
  3. test_review = test_review.lower() # lowercase
  4. # get rid of punctuation
  5. test_text = ''.join([c for c in test_review if c not in punctuation])
  6. # splitting by spaces
  7. test_words = test_text.split()
  8. # tokens
  9. test_ints = []
  10. test_ints.append([vocab_to_int[word] for word in test_words])
  11. return test_ints
  12. # test code and generate tokenized review
  13. test_ints = tokenize_review(test_review_neg)
  14. print(test_ints)
  15. # test sequence padding
  16. seq_length=200
  17. features = pad_features(test_ints, seq_length)
  18. print(features)
  19. # test conversion to tensor and pass into your model
  20. feature_tensor = torch.from_numpy(features)
  21. print(feature_tensor.size())

  1. def predict(net, test_review, sequence_length=200):
  2. net.eval()
  3. # tokenize review
  4. test_ints = tokenize_review(test_review)
  5. # pad tokenized sequence
  6. seq_length=sequence_length
  7. features = pad_features(test_ints, seq_length)
  8. # convert to tensor to pass into your model
  9. feature_tensor = torch.from_numpy(features)
  10. batch_size = feature_tensor.size(0)
  11. # initialize hidden state
  12. h = net.init_hidden(batch_size)
  13. if(train_on_gpu):
  14. feature_tensor = feature_tensor.cuda()
  15. # get the output from the model
  16. output, h = net(feature_tensor, h)
  17. # convert output probabilities to predicted class (0 or 1)
  18. pred = torch.round(output.squeeze())
  19. # printing output value, before rounding
  20. print('Prediction value, pre-rounding: {:.6f}'.format(output.item()))
  21. # print custom response
  22. if(pred.item()==1):
  23. print("Positive review detected!")
  24. else:
  25. print("Negative review detected.")

  1. # positive test review
  2. test_review_pos = 'This movie had the best acting and the dialogue was so good. I loved it.'
  3. # call function
  4. seq_length=200 # good to use the length that was trained on
  5. predict(net, test_review_neg, seq_length)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/734041
推荐阅读
相关标签
  

闽ICP备14008679号