Advertisement
jack06215

[keras] LSTM-Autoencoder internal result experiment

May 24th, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import tensorflow as tf
  2.  
  3. from tensorflow.keras.layers import Dense, LSTM, Masking, TimeDistributed, RepeatVector, Lambda, BatchNormalization
  4. from tensorflow.keras.preprocessing.sequence import pad_sequences
  5. from tensorflow.keras.models import Model
  6. from tensorflow.keras.models import Sequential
  7.  
  8. import numpy as np
  9.  
  10.  
  11. def repeat_vector(args):
  12.     """ Repeat vector n times """
  13.     layer_to_repeat = args[0]
  14.     sequence_layer = args[1]
  15.     return RepeatVector(tf.keras.backend.shape(sequence_layer)[1])(layer_to_repeat)
  16.  
  17. #(samples,timesteps,features) samples=4,features=3, timesteps=variable length
  18. train_X = np.array([
  19. [[0, 1, 2], [9, 8, 7],[3, 6, 8]],
  20. [[3, 4, 5]],
  21. [[6, 7, 8], [6, 5, 4],[1, 7, 4]],
  22. [[9, 0, 1], [3, 7, 4]]
  23. ])
  24.  
  25. test_X = np.array([
  26. [[0, 1, 4]],
  27. [[6, 7, 4], [7, 3, 0], [5, 8, 9], [0, 2, 4]]
  28. ])
  29.  
  30. train_Y = np.array([0, 1, 1, 0])
  31.  
  32. n_feat = 3
  33.  
  34. # padding
  35. train_X = pad_sequences(train_X, padding='post')
  36. test_X = pad_sequences(test_X, padding='post')
  37.  
  38. model = Sequential()
  39.  
  40. # masking to handle variable length size
  41. inputs = tf.keras.Input(shape=(None, n_feat))
  42. masked_input = Masking(mask_value=0)(inputs)
  43.  
  44. # encoder
  45. encoder = LSTM(32, activation='tanh', return_sequences=True)(masked_input)
  46. encoder = LSTM(units=16, activation='tanh', return_sequences=False)(encoder)
  47.  
  48. # decoder
  49. decoder = Lambda(repeat_vector, output_shape=(None, n_feat)) ([encoder, masked_input])
  50. decoder = LSTM(16, activation='tanh', return_sequences=True)(decoder)
  51. decoder = LSTM(units=32, activation='tanh', return_sequences=True)(decoder)
  52. decoder = TimeDistributed(Dense(units=n_feat))(decoder)
  53.  
  54. model = Model(inputs=inputs, outputs=decoder)
  55. model.compile(optimizer='rmsprop', loss='mse')
  56.  
  57.  
  58. mask_vector_layer = Model(inputs=model.inputs, outputs=model.layers[6].output)
  59. print(mask_vector_layer.summary())
  60. mask_vector_layer_output = mask_vector_layer.predict(test_X)
  61. print(mask_vector_layer_output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement