当前位置:   article > 正文

实例4:循环神经网络RNN之情感分类问题(SimpleRNNCell实现)

实例4:循环神经网络RNN之情感分类问题(SimpleRNNCell实现)

前言

SimpleRNNCell是更加底层的方法进行构造RNN神经网络来进行情感分析,能够帮助你更好的理解RNN网络

循环网络示意图:

采用了权值共享的思想

完整代码及相应注释如下:

 

  1. import os
  2. import tensorflow as tf
  3. import numpy as np
  4. from tensorflow import keras
  5. from tensorflow.keras import layers
  6. tf.random.set_seed(22)
  7. np.random.seed(22)
  8. os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
  9. assert tf.__version__.startswith('2.')
  10. batchsz = 128
  11. total_words = 10000 #常用的10000个,当出现生僻字时把它当成一个单词
  12. max_review_len = 80
  13. embedding_len = 100
  14. (x_train,y_train),(x_test,y_test)=keras.datasets.imdb.load_data(num_word=total_words) # 只给常见的10000个单词进行编码
  15. # 每个句子长度不等,将多个句子padding成相同长度的句子
  16. # x_train:[b,80]
  17. # x_test:[b,80]
  18. x_train = keras.preprocessing.sequence.pad_sequences(x_train,maxlen=max_review_len)
  19. x_test = keras.preprocessing.sequence.pad_sequences(x_test,maxlen=max_review_len)
  20. db_train = tf.data.Dataset.from_tensor_slices((x_train,y_train))
  21. db_train = db_train.shuffle(1000).batch(batchsz,drop_remainder=True) # 当最后一个batchsize小于128时,丢弃
  22. db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test))
  23. db_test = db_test.batch(batchsz,drop_remainder=True)
  24. print('x_train shape:',x_train.shape,tf.reduce_max(y_train),tf.reduce_min(y_train))
  25. print('x_test:',x_test.shape)
  26. class MyRNN(keras.Model):
  27. def __init__(self,units):
  28. super(MyRNN,self).__init__()
  29. # [b,64]
  30. self.state0 = [tf.zeros([batchsz,units])]
  31. self.state1 = [tf.zeros([batchsz, units])]
  32. # [b,80] >> [b,80,100]
  33. self.embedding = layers.Embedding(total_words,embedding_len,input_len = max_review_len)
  34. # [b,80,100], h_dim:64
  35. # SimpleRNN
  36. self.rnn_cell0 = layers.SimpleRNNCell(units,dropout=0.2) #防止过拟合
  37. self.rnn_cell1 = layers.SimpleRNNCell(units,dropout=0.2)
  38. # fc [b,80,100]>>[b,64]>>[b,1]
  39. self.outlayer = layers.Dense(1)
  40. def call(self,inputs,training=None):
  41. '''
  42. net(x) net(x,training=True) :train mode
  43. nex(x,training = False) : test mode
  44. :param inputs: [b,80]
  45. :param training:
  46. :return:
  47. '''
  48. # [b,80]
  49. x = inputs
  50. # embedding : [b,80]>>[b,80,100]
  51. x = self.embedding(x)
  52. # rnn cell comute
  53. # [b,80,100]>>[b,64]
  54. state0 = self.state0
  55. state1 = self.state1
  56. for word in tf.unstack(x,axis=1): # word:[b,100] 希望在第二个维度或者单词维度展开
  57. # h1 = x*wxh+h*whh
  58. out0,state0 = self.rnn_cell0(word,state0,training) # 注意传入training参数,令其可以在不同模式下操作.及是否使用dropout
  59. out1,state1 = self.rnn_cell1(out0,state1)
  60. # out:[b,64]>>[b,1]
  61. x = self.outlayer(out1)
  62. # p(y is pos|x)
  63. prob = tf.sigmoid(x)
  64. return prob
  65. def main():
  66. units = 64
  67. epochs = 4
  68. model = MyRNN(units)
  69. model.compile(optimizer = keras.optimizers.Adam(0.001),
  70. loss = tf.losses.BinaryCrossentropy(),
  71. metrics = ['accuracy'])
  72. model.fit(db_train,epochs = epochs,validation = db_test)
  73. model.evaluate(db_test)
  74. if __name__ == '__main__':
  75. main()

本文代码和图片来自:

课时114 RNN与情感分类问题实战-加载IMDB数据集_哔哩哔哩_bilibili

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

闽ICP备14008679号