sentiment_analysis_layer - LSTM - pretrained.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #%%
  2. import os
  3. import tensorflow as tf
  4. import numpy as np
  5. from tensorflow import keras
  6. from tensorflow.keras import layers, losses, optimizers, Sequential
  7. tf.random.set_seed(22)
  8. np.random.seed(22)
  9. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  10. assert tf.__version__.startswith('2.')
  11. batchsz = 128 # 批量大小
  12. total_words = 10000 # 词汇表大小N_vocab
  13. max_review_len = 80 # 句子最大长度s,大于的句子部分将截断,小于的将填充
  14. embedding_len = 100 # 词向量特征长度f
  15. # 加载IMDB数据集,此处的数据采用数字编码,一个数字代表一个单词
  16. (x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(num_words=total_words)
  17. print(x_train.shape, len(x_train[0]), y_train.shape)
  18. print(x_test.shape, len(x_test[0]), y_test.shape)
  19. #%%
  20. x_train[0]
  21. #%%
  22. # 数字编码表
  23. word_index = keras.datasets.imdb.get_word_index()
  24. # for k,v in word_index.items():
  25. # print(k,v)
  26. #%%
  27. word_index = {k:(v+3) for k,v in word_index.items()}
  28. word_index["<PAD>"] = 0
  29. word_index["<START>"] = 1
  30. word_index["<UNK>"] = 2 # unknown
  31. word_index["<UNUSED>"] = 3
  32. # 翻转编码表
  33. reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
  34. def decode_review(text):
  35. return ' '.join([reverse_word_index.get(i, '?') for i in text])
  36. decode_review(x_train[8])
  37. #%%
  38. print('Indexing word vectors.')
  39. embeddings_index = {}
  40. GLOVE_DIR = r'C:\Users\z390\Downloads\glove6b50dtxt'
  41. with open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt'),encoding='utf-8') as f:
  42. for line in f:
  43. values = line.split()
  44. word = values[0]
  45. coefs = np.asarray(values[1:], dtype='float32')
  46. embeddings_index[word] = coefs
  47. print('Found %s word vectors.' % len(embeddings_index))
  48. #%%
  49. len(embeddings_index.keys())
  50. len(word_index.keys())
  51. #%%
  52. MAX_NUM_WORDS = total_words
  53. # prepare embedding matrix
  54. num_words = min(MAX_NUM_WORDS, len(word_index))
  55. embedding_matrix = np.zeros((num_words, embedding_len))
  56. applied_vec_count = 0
  57. for word, i in word_index.items():
  58. if i >= MAX_NUM_WORDS:
  59. continue
  60. embedding_vector = embeddings_index.get(word)
  61. # print(word,embedding_vector)
  62. if embedding_vector is not None:
  63. # words not found in embedding index will be all-zeros.
  64. embedding_matrix[i] = embedding_vector
  65. applied_vec_count += 1
  66. print(applied_vec_count, embedding_matrix.shape)
  67. #%%
  68. # x_train:[b, 80]
  69. # x_test: [b, 80]
  70. # 截断和填充句子,使得等长,此处长句子保留句子后面的部分,短句子在前面填充
  71. x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=max_review_len)
  72. x_test = keras.preprocessing.sequence.pad_sequences(x_test, maxlen=max_review_len)
  73. # 构建数据集,打散,批量,并丢掉最后一个不够batchsz的batch
  74. db_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
  75. db_train = db_train.shuffle(1000).batch(batchsz, drop_remainder=True)
  76. db_test = tf.data.Dataset.from_tensor_slices((x_test, y_test))
  77. db_test = db_test.batch(batchsz, drop_remainder=True)
  78. print('x_train shape:', x_train.shape, tf.reduce_max(y_train), tf.reduce_min(y_train))
  79. print('x_test shape:', x_test.shape)
  80. #%%
  81. class MyRNN(keras.Model):
  82. # Cell方式构建多层网络
  83. def __init__(self, units):
  84. super(MyRNN, self).__init__()
  85. # 词向量编码 [b, 80] => [b, 80, 100]
  86. self.embedding = layers.Embedding(total_words, embedding_len,
  87. input_length=max_review_len,
  88. trainable=False)
  89. self.embedding.build(input_shape=(None,max_review_len))
  90. # self.embedding.set_weights([embedding_matrix])
  91. # 构建RNN
  92. self.rnn = keras.Sequential([
  93. layers.LSTM(units, dropout=0.5, return_sequences=True),
  94. layers.LSTM(units, dropout=0.5)
  95. ])
  96. # 构建分类网络,用于将CELL的输出特征进行分类,2分类
  97. # [b, 80, 100] => [b, 64] => [b, 1]
  98. self.outlayer = Sequential([
  99. layers.Dense(32),
  100. layers.Dropout(rate=0.5),
  101. layers.ReLU(),
  102. layers.Dense(1)])
  103. def call(self, inputs, training=None):
  104. x = inputs # [b, 80]
  105. # embedding: [b, 80] => [b, 80, 100]
  106. x = self.embedding(x)
  107. # rnn cell compute,[b, 80, 100] => [b, 64]
  108. x = self.rnn(x)
  109. # 末层最后一个输出作为分类网络的输入: [b, 64] => [b, 1]
  110. x = self.outlayer(x,training)
  111. # p(y is pos|x)
  112. prob = tf.sigmoid(x)
  113. return prob
  114. def main():
  115. units = 512 # RNN状态向量长度f
  116. epochs = 50 # 训练epochs
  117. model = MyRNN(units)
  118. # 装配
  119. model.compile(optimizer = optimizers.Adam(0.001),
  120. loss = losses.BinaryCrossentropy(),
  121. metrics=['accuracy'])
  122. # 训练和验证
  123. model.fit(db_train, epochs=epochs, validation_data=db_test)
  124. # 测试
  125. model.evaluate(db_test)
  126. if __name__ == '__main__':
  127. main()
  128. #%%