详细解读简单的lstm的实例

时间:2023-03-09 07:46:38
详细解读简单的lstm的实例

http://blog.****.net/zjm750617105/article/details/51321889

本文是初学keras这两天来,自己仿照addition_rnn.py,写的一个实例,数据处理稍微有些不同,但是准确性相比addition_rnn.py 差一点,下面直接贴代码,
解释和注释都在代码里边。

  1. <span style="font-family: Arial, Helvetica, sans-serif;">#coding:utf-8</span>
    1. from keras.models import  Sequential
    2. from keras.layers.recurrent import LSTM
    3. from utils import  log
    4. from numpy import random
    5. import numpy as np
    6. from  keras.layers.core import RepeatVector, TimeDistributedDense, Activation
    7. '''''
    8. 先用lstm实现一个计算加法的keras版本, 根据addition_rnn.py改写
    9. size: 500
    10. 10次: test_acu = 0.3050  base_acu= 0.3600
    11. 30次: rest_acu = 0.3300  base_acu= 0.4250
    12. size: 50000
    13. 10次: test_acu: loss: 0.4749 - acc: 0.8502 - val_loss: 0.4601 - val_acc: 0.8539
    14. base_acu: loss: 0.3707 - acc: 0.9008 - val_loss: 0.3327 - val_acc: 0.9135
    15. 20次: test_acu: loss: 0.1536 - acc: 0.9505 - val_loss: 0.1314 - val_acc: 0.9584
    16. base_acu: loss: 0.0538 - acc: 0.9891 - val_loss: 0.0454 - val_acc: 0.9919
    17. 30次: test_acu: loss: 0.0671 - acc: 0.9809 - val_loss: 0.0728 - val_acc: 0.9766
    18. base_acu: loss: 0.0139 - acc: 0.9980 - val_loss: 0.0502 - val_acc: 0.9839
    19. '''
    20. log = log()
    21. #defination the global variable
    22. training_size = 50000
    23. hidden_size = 128
    24. batch_size = 128
    25. layers = 1
    26. maxlen = 7
    27. single_digit = 3
    28. def generate_data():
    29. log.info("generate the questions and answers")
    30. questions = []
    31. expected = []
    32. seen = set()
    33. while len(seen) < training_size:
    34. num1 = random.randint(1, 999) #generate a num [1,999]
    35. num2 = random.randint(1, 999)
    36. #用set来存储又有排序,来保证只有不同数据和结果
    37. key  = tuple(sorted((num1,num2)))
    38. if key in seen:
    39. continue
    40. seen.add(key)
    41. q = '{}+{}'.format(num1,num2)
    42. query = q + ' ' * (maxlen - len(q))
    43. ans = str(num1 + num2)
    44. ans = ans + ' ' * (single_digit + 1 - len(ans))
    45. questions.append(query)
    46. expected.append(ans)
    47. return questions, expected
    48. class CharacterTable():
    49. '''''
    50. encode: 将一个str转化为一个n维数组
    51. decode: 将一个n为数组转化为一个str
    52. 输入输出分别为
    53. character_table =  [' ', '+', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    54. 如果一个question = [' 123+23']
    55. 那个改question对应的数组就是(7,12):
    56. 同样expected最大是一个四位数[' 146']:
    57. 那么ans对应的数组就是[4,12]
    58. '''
    59. def __init__(self, chars, maxlen):
    60. self.chars = sorted(set(chars))
    61. '''''
    62. >>> b = [(c, i) for i, c in enumerate(a)]
    63. >>> dict(b)
    64. {' ': 0, '+': 1, '1': 3, '0': 2, '3': 5, '2': 4, '5': 7, '4': 6, '7': 9, '6': 8, '9': 11, '8': 10}
    65. 得出的结果是无序的,但是下面这种方式得出的结果是有序的
    66. '''
    67. self.char_index = dict((c, i) for i, c in enumerate(self.chars))
    68. self.index_char = dict((i, c) for i, c in enumerate(self.chars))
    69. self.maxlen = maxlen
    70. def encode(self, C, maxlen):
    71. X = np.zeros((maxlen, len(self.chars)))
    72. for i, c in enumerate(C):
    73. X[i, self.char_index[c]] = 1
    74. return X
    75. def decode(self, X, calc_argmax=True):
    76. if calc_argmax:
    77. X = X.argmax(axis=-1)
    78. return ''.join(self.index_char[x] for x in X)
    79. chars = '0123456789 +'
    80. character_table = CharacterTable(chars,len(chars))
    81. questions , expected = generate_data()
    82. log.info('Vectorization...') #失量化
    83. inputs = np.zeros((len(questions), maxlen, len(chars))) #(5000, 7, 12)
    84. labels = np.zeros((len(expected), single_digit+1, len(chars))) #(5000, 4, 12)
    85. log.info("encoding the questions and get inputs")
    86. for i, sentence in enumerate(questions):
    87. inputs[i] = character_table.encode(sentence, maxlen=len(sentence))
    88. #print("questions is ", questions[0])
    89. #print("X is ", inputs[0])
    90. log.info("encoding the expected and get labels")
    91. for i, sentence in enumerate(expected):
    92. labels[i] = character_table.encode(sentence, maxlen=len(sentence))
    93. #print("expected is ", expected[0])
    94. #print("y is ", labels[0])
    95. log.info("total inputs is %s"%str(inputs.shape))
    96. log.info("total labels is %s"%str(labels.shape))
    97. log.info("build model")
    98. model = Sequential()
    99. '''''
    100. LSTM(output_dim, init='glorot_uniform', inner_init='orthogonal',
    101. forget_bias_init='one', activation='tanh',
    102. inner_activation='hard_sigmoid',
    103. W_regularizer=None, U_regularizer=None, b_regularizer=None,
    104. dropout_W=0., dropout_U=0., **kwargs)
    105. output_dim: 输出层的维数,或者可以用output_shape
    106. init:
    107. uniform(scale=0.05) :均匀分布,最常用的。Scale就是均匀分布的每个数据在-scale~scale之间。此处就是-0.05~0.05。scale默认值是0.05;
    108. lecun_uniform:是在LeCun在98年发表的论文中基于uniform的一种方法。区别就是lecun_uniform的scale=sqrt(3/f_in)。f_in就是待初始化权值矩阵的行。
    109. normal:正态分布(高斯分布)。
    110. Identity :用于2维方阵,返回一个单位阵.
    111. Orthogonal:用于2维方阵,返回一个正交矩阵. lstm默认
    112. Zero:产生一个全0矩阵。
    113. glorot_normal:基于normal分布,normal的默认 sigma^2=scale=0.05,而此处sigma^2=scale=sqrt(2 / (f_in+ f_out)),其中,f_in和f_out是待初始化矩阵的行和列。
    114. glorot_uniform:基于uniform分布,uniform的默认scale=0.05,而此处scale=sqrt( 6 / (f_in +f_out)) ,其中,f_in和f_out是待初始化矩阵的行和列。
    115. W_regularizer , b_regularizer  and activity_regularizer:
    116. 官方文档: http://keras.io/regularizers/
    117. from keras.regularizers import l2, activity_l2
    118. model.add(Dense(64, input_dim=64, W_regularizer=l2(0.01), activity_regularizer=activity_l2(0.01)))
    119. 加入规则项主要是为了在小样本数据下过拟合现象的发生,我们都知道,一半在训练过程中解决过拟合现象的方法主要中两种,一种是加入规则项(权值衰减), 第二种是加大数据量
    120. 很显然,加大数据量一般是不容易的,而加入规则项则比较容易,所以在发生过拟合的情况下,我们一般都采用加入规则项来解决这个问题.
    121. '''
    122. model.add(LSTM(hidden_size, input_shape=(maxlen, len(chars)))) #(7,12) 输入层
    123. '''''
    124. keras.layers.core.RepeatVector(n)
    125. 把1维的输入重复n次。假设输入维度为(nb_samples, dim),那么输出shape就是(nb_samples, n, dim)
    126. inputshape: 任意。当把这层作为某个模型的第一层时,需要用到该参数(元组,不包含样本轴)。
    127. outputshape:(nb_samples,nb_input_units)
    128. '''
    129. model.add(RepeatVector(single_digit + 1))
    130. #表示有多少个隐含层
    131. for _ in range(layers):
    132. model.add(LSTM(hidden_size, return_sequences=True))
    133. '''''
    134. TimeDistributedDense:
    135. 官方文档:http://keras.io/layers/core/#timedistributeddense
    136. keras.layers.core.TimeDistributedDense(output_dim,init='glorot_uniform', activation='linear', weights=None
    137. W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None,
    138. input_dim=None, input_length=None)
    139. 这是一个基于时间维度的全连接层。主要就是用来构建RNN(递归神经网络)的,但是在构建RNN时需要设置return_sequences=True。
    140. for example:
    141. # input shape: (nb_samples, timesteps,10)
    142. model.add(LSTM(5, return_sequences=True, input_dim=10)) # output shape: (nb_samples, timesteps, 5)
    143. model.add(TimeDistributedDense(15)) # output shape:(nb_samples, timesteps, 15)
    144. W_constraint:
    145. from keras.constraints import maxnorm
    146. model.add(Dense(64, W_constraint =maxnorm(2))) #限制权值的各个参数不能大于2
    147. '''
    148. model.add(TimeDistributedDense(len(chars)))
    149. model.add(Activation('softmax'))
    150. '''''
    151. 关于目标函数和优化函数,参考另外一片博文: http://blog.****.net/zjm750617105/article/details/51321915
    152. '''
    153. model.compile(loss='categorical_crossentropy',
    154. optimizer='adam',
    155. metrics=['accuracy'])
    156. # Train the model each generation and show predictions against the validation dataset
    157. for iteration in range(1, 3):
    158. print()
    159. print('-' * 50)
    160. print('Iteration', iteration)
    161. model.fit(inputs, labels, batch_size=batch_size, nb_epoch=2,
    162. validation_split = 0.1)
    163. # Select 10 samples from the validation set at random so we can visualize errors
    164. model.get_config()