model.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import sys
  2. import os
  3. import numpy as np
  4. sys.path.append(os.path.abspath(os.path.dirname(__file__)))
  5. from keras.layers import Lambda, Dense, Reshape, Bidirectional, LSTM, Conv2D, BatchNormalization, LeakyReLU, Masking
  6. from keras.preprocessing.sequence import pad_sequences
  7. from models.layer_utils import BatchReshape1, BatchReshape2, MyPadding, MySplit, BatchReshape3, \
  8. BatchReshape4, BatchReshape5, BatchReshape6
  9. from keras import layers, models, Sequential
  10. import keras.backend as K
  11. import tensorflow as tf
  12. from models.my_average_pooling import MyAveragePooling1D
  13. from models.self_attention import SeqSelfAttention, MySelfAttention
  14. from models.u_net import u_net_small
  15. def model_1(input_shape, output_shape):
  16. # Input (batch, 10, 60)
  17. input_1 = layers.Input(shape=input_shape[1:], dtype="float32")
  18. input_2 = layers.Input(shape=input_shape[1:], dtype="float32")
  19. input_3 = layers.Input(shape=input_shape[1:], dtype="float32")
  20. input_4 = layers.Input(shape=input_shape[1:], dtype="float32")
  21. input_5 = layers.Input(shape=input_shape[1:], dtype="float32")
  22. input_6 = layers.Input(shape=input_shape[1:], dtype="float32")
  23. # ----------- Three box sequence -----------
  24. # Concat (batch, 30, 60)
  25. concat_1 = layers.concatenate([input_1, input_2, input_3], axis=-2, name='seq_concat')
  26. concat_2 = layers.concatenate([input_4, input_5, input_6], axis=-2)
  27. # Bi-LSTM (batch, 30, 128)
  28. bi_lstm_1 = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(concat_1)
  29. bi_lstm_2 = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(concat_2)
  30. # Self-Attention (batch, 30, 128)
  31. self_attention_1 = SeqSelfAttention(attention_activation='sigmoid')(bi_lstm_1)
  32. self_attention_2 = SeqSelfAttention(attention_activation='sigmoid')(bi_lstm_2)
  33. # Dense (batch, 30, 1)
  34. dense_1 = layers.Dense(output_shape[0], activation="relu")(self_attention_1)
  35. dense_2 = layers.Dense(output_shape[0], activation="relu")(self_attention_2)
  36. # Squeeze (batch, 30)
  37. squeeze_1 = Lambda(lambda x: K.squeeze(x, axis=-1))(dense_1)
  38. squeeze_2 = Lambda(lambda x: K.squeeze(x, axis=-1))(dense_2)
  39. # ----------- One box feature -----------
  40. # Bi-LSTM (batch, 10, 128)
  41. bi_lstm = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(input_2)
  42. # Self-Attention (batch, 10, 128)
  43. self_attention = SeqSelfAttention(attention_activation='sigmoid')(bi_lstm)
  44. # mask mean pooling
  45. # pool_1 = MyAveragePooling1D(axis=-1)(self_attention_1)
  46. # Dense (batch, 10, 1)
  47. dense = layers.Dense(output_shape[0], activation="relu")(self_attention)
  48. # Squeeze (batch, 10) - one box feature
  49. squeeze = Lambda(lambda x: K.squeeze(x, axis=-1))(dense)
  50. # ----------- Three box sequence & One box feature -----------
  51. # Dense (batch, 1)
  52. concat = layers.concatenate([squeeze, squeeze_1, squeeze_2])
  53. output = layers.Dense(64, activation='relu')(concat)
  54. output = layers.Dense(1, activation="sigmoid", name='output')(output)
  55. model = models.Model(inputs=[input_1, input_2, input_3, input_4, input_5, input_6],
  56. outputs=output)
  57. # model.summary()
  58. return model
  59. def model_2(input_shape, output_shape):
  60. # input_shape = (None, None, 10, 60)
  61. # (batch_size, row_num, col_num, character_num, character_embedding)
  62. hidden_size = 64
  63. attention_size = 64
  64. character_num = 10
  65. character_embed = 60
  66. cell_embed = 1
  67. # Input
  68. input_1 = layers.Input(shape=input_shape, dtype="float32", name="input_1")
  69. input_2 = layers.Input(shape=(None, None, None, None), dtype="int32", name="input_2")
  70. # batch = tf.shape(_input)[0]
  71. height = tf.shape(input_2)[1]
  72. width = tf.shape(input_2)[2]
  73. pad_height = tf.shape(input_2)[3]
  74. pad_width = tf.shape(input_2)[4]
  75. # print("batch, height, width", batch, height, width)
  76. # Reshape
  77. reshape = BatchReshape1(character_num, character_embed)(input_1)
  78. print("model_2_0", reshape)
  79. # Bi-LSTM + Attention
  80. bi_lstm = Bidirectional(LSTM(hidden_size))(reshape)
  81. print("model_2_1", bi_lstm)
  82. # bi_lstm = Bidirectional(LSTM(hidden_size, return_sequences=True))(reshape)
  83. # self_attention = SeqSelfAttention(attention_activation='sigmoid')(bi_lstm)
  84. # trans = Lambda(lambda x: tf.transpose(x, (0, 2, 1)))(self_attention)
  85. # dense = Dense(1, activation='relu')(trans)
  86. # squeeze = Lambda(lambda x: tf.squeeze(x, -1))(dense)
  87. dense = Dense(1, activation="sigmoid")(bi_lstm)
  88. print("model_2_2", dense)
  89. # reshape = Lambda(batch_reshape, output_shape=(height, width, cell_embed))(dense)
  90. reshape = BatchReshape2(cell_embed)([input_1, dense])
  91. print("model_2_3", reshape)
  92. # squeeze_1 = Lambda(lambda x: K.squeeze(x, axis=-1), name="output_1")(reshape)
  93. # print("model_2_4", squeeze)
  94. # Padding
  95. padding = MyPadding(pad_height, pad_width, cell_embed)(reshape)
  96. # padding = reshape
  97. print("model_2_4", padding)
  98. # U-Net
  99. # u_net = u_net_small(padding)
  100. # print("model_2_5", u_net)
  101. # Conv 5*5
  102. conv = Conv2D(1, (5, 5), padding='same')(padding)
  103. bn = BatchNormalization()(conv)
  104. relu = LeakyReLU(alpha=0.)(bn)
  105. conv = Conv2D(1, (5, 5), padding='same')(relu)
  106. bn = BatchNormalization()(conv)
  107. relu = LeakyReLU(alpha=0.)(bn)
  108. conv = Conv2D(1, (5, 5), padding='same')(relu)
  109. bn = BatchNormalization()(conv)
  110. relu_1 = LeakyReLU(alpha=0.)(bn)
  111. # Conv 3*3
  112. conv = Conv2D(1, (3, 3), padding='same')(padding)
  113. bn = BatchNormalization()(conv)
  114. relu = LeakyReLU(alpha=0.)(bn)
  115. conv = Conv2D(1, (3, 3), padding='same')(relu)
  116. bn = BatchNormalization()(conv)
  117. relu = LeakyReLU(alpha=0.)(bn)
  118. conv = Conv2D(1, (3, 3), padding='same')(relu)
  119. bn = BatchNormalization()(conv)
  120. relu_2 = LeakyReLU(alpha=0.)(bn)
  121. # Conv 1*1
  122. conv = Conv2D(1, (1, 1), padding='same')(padding)
  123. bn = BatchNormalization()(conv)
  124. relu = LeakyReLU(alpha=0.)(bn)
  125. conv = Conv2D(1, (1, 1), padding='same')(relu)
  126. bn = BatchNormalization()(conv)
  127. relu = LeakyReLU(alpha=0.)(bn)
  128. conv = Conv2D(1, (1, 1), padding='same')(relu)
  129. bn = BatchNormalization()(conv)
  130. relu_3 = LeakyReLU(alpha=0.)(bn)
  131. # conv = Conv2D(cell_embed, (3, 3), padding='same')(relu)
  132. # bn = BatchNormalization()(conv)
  133. # relu_2 = LeakyReLU(alpha=0.)(bn)
  134. # Merge
  135. # print("model_2_5", relu_1, relu_2)
  136. merge = layers.Concatenate(axis=-1)([relu_1, relu_2, relu_3])
  137. # merge = u_net
  138. # merge = relu
  139. dense = layers.Dense(1, activation='sigmoid')(merge)
  140. squeeze_2 = Lambda(lambda x: K.squeeze(x, axis=-1))(dense)
  141. # Split
  142. split = MySplit(height, width, name="output")(squeeze_2)
  143. model = models.Model(inputs=[input_1, input_2], outputs=split)
  144. model.summary(line_length=120)
  145. return model
  146. def model_3(input_shape, output_shape):
  147. # (batch_size, row_num, col_num, character_num, character_embedding)
  148. hidden_size = 16
  149. attention_size = 2*hidden_size
  150. character_num = 20
  151. character_embed = 60
  152. cell_embed = 2*hidden_size
  153. pad_len = 100
  154. mask_timestamps = pad_len
  155. # Input
  156. input_1 = layers.Input(shape=input_shape, dtype="float32", name="input_1")
  157. input_2 = layers.Input(shape=(None, None, None, None), dtype="int32", name="input_2")
  158. # Reshape
  159. reshape = BatchReshape1(character_num, character_embed)(input_1)
  160. print("model_2_0", reshape)
  161. # Bi-LSTM
  162. bi_lstm = Bidirectional(LSTM(hidden_size, return_sequences=True))(reshape)
  163. bi_lstm = Bidirectional(LSTM(hidden_size, return_sequences=False))(bi_lstm)
  164. print("model_2_1", bi_lstm)
  165. # Reshape
  166. reshape = BatchReshape2(cell_embed)([input_1, bi_lstm])
  167. print("model_2_3", reshape)
  168. # Rows Reshape
  169. reshape_1 = BatchReshape3(cell_embed)(reshape)
  170. # Cols Reshape
  171. trans = Lambda(lambda x: tf.transpose(x, (0, 2, 1, 3)))(reshape)
  172. reshape_2 = BatchReshape3(cell_embed)(trans)
  173. # All boxes Reshape
  174. reshape_3 = BatchReshape5(cell_embed)(reshape)
  175. # Masking
  176. # mask_1 = Masking(mask_value=-1, input_shape=(mask_timestamps, cell_embed))(pad_1)
  177. # mask_2 = Masking(mask_value=-1, input_shape=(mask_timestamps, cell_embed))(pad_2)
  178. # print("model_2_4", mask_1)
  179. # Padding
  180. # pad_1 = MyPadding()
  181. # Bi-LSTM
  182. # bi_lstm = Bidirectional(LSTM(hidden_size, return_sequences=True))
  183. # bi_lstm_1 = bi_lstm(reshape_1)
  184. # bi_lstm_2 = bi_lstm(reshape_2)
  185. bi_lstm_1 = Bidirectional(LSTM(hidden_size, return_sequences=True))(reshape_1)
  186. bi_lstm_2 = Bidirectional(LSTM(hidden_size, return_sequences=True))(reshape_2)
  187. # bi_lstm_1 = LSTM(2*hidden_size, return_sequences=True)(reshape_1)
  188. # print("model_2_4", bi_lstm_1)
  189. # bi_lstm_2 = LSTM(2*hidden_size, return_sequences=True)(reshape_2)
  190. # self_attention_1 = MySelfAttention(output_dim=attention_size)(bi_lstm_1)
  191. # self_attention_2 = MySelfAttention(output_dim=attention_size)(bi_lstm_2)
  192. # Bi-LSTM + Attention
  193. bi_lstm_3 = Bidirectional(LSTM(hidden_size, return_sequences=True))(reshape_3)
  194. # bi_lstm_3 = LSTM(2*hidden_size, return_sequences=True)(reshape_3)
  195. # self_attention_3 = MySelfAttention(output_dim=attention_size)(bi_lstm_3)
  196. # print("model_2_5", bi_lstm_1)
  197. # Reshape
  198. reshape_1 = BatchReshape4(cell_embed)([reshape, bi_lstm_1])
  199. reshape_2 = BatchReshape4(cell_embed)([trans, bi_lstm_2])
  200. reshape_2 = Lambda(lambda x: tf.transpose(x, (0, 2, 1, 3)))(reshape_2)
  201. reshape_3 = BatchReshape6(cell_embed)([reshape, bi_lstm_3])
  202. print("model_2_6", reshape_1)
  203. # Merge
  204. merge = layers.Concatenate(axis=-1)([reshape, reshape_1, reshape_2, reshape_3])
  205. dense = layers.Dense(hidden_size, activation='relu')(merge)
  206. dense = layers.Dense(1, activation='sigmoid')(dense)
  207. squeeze = Lambda(lambda x: K.squeeze(x, axis=-1), name="output")(dense)
  208. model = models.Model(inputs=[input_1, input_2], outputs=squeeze)
  209. model.summary(line_length=110)
  210. return model
  211. def get_model(input_shape, output_shape, model_id):
  212. if model_id == 1:
  213. return model_1(input_shape, output_shape)
  214. elif model_id == 2:
  215. return model_2(input_shape, output_shape)
  216. elif model_id == 3:
  217. return model_3(input_shape, output_shape)
  218. else:
  219. print("No such model!")
  220. raise Exception()
  221. def test_layer():
  222. model = Sequential()
  223. model.add(Masking(mask_value=-1, input_shape=(5, 8)))
  224. model.add(Lambda(lambda x: pad_sequences(x, maxlen=100, dtype='float32',
  225. padding='post', truncating='post',
  226. value=-1)))
  227. model.add(Masking(mask_value=-1, input_shape=(5, 8)))
  228. model.add(LSTM(32, return_sequences=True))
  229. model.compile(optimizer='sgd', loss='mse')
  230. x = np.zeros([1, 5, 8])
  231. print(x.shape)
  232. y = np.zeros([1, 5, 32])
  233. model.summary()
  234. model.fit(x, y, batch_size=32, epochs=10)
  235. if __name__ == "__main__":
  236. test_layer()