Advertisement
jack06215

[keras] LSTM-Autoencoder

May 21st, 2020
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. import tensorflow as tf
  2.  
  3. from tensorflow.keras.layers import Dense, LSTM, Masking, TimeDistributed, RepeatVector
  4. from tensorflow.keras.preprocessing.sequence import pad_sequences
  5. from tensorflow.keras.models import Sequential
  6.  
  7. import numpy as np
  8.  
  9. #(samples,timesteps,features) samples=4,features=3, timesteps=variable length
  10. train_X = np.array([
  11. [[0, 1, 2], [9, 8, 7],[3, 6, 8]],
  12. [[3, 4, 5]],
  13. [[6, 7, 8], [6, 5, 4],[1, 7, 4]],
  14. [[9, 0, 1], [3, 7, 4]]
  15. ])
  16.  
  17. train_Y = np.array([0, 1, 1, 0])
  18.  
  19. n_in = 3
  20. n_feat = 3
  21. n_out = 1
  22.  
  23. # padding
  24. '''
  25. train_X = np.array([
  26. [[0, 1, 2], [9, 8, 7],[3, 6, 8]],
  27. [[3, 4, 5], [0, 0, 0],[0, 0, 0]],
  28. [[6, 7, 8], [6, 5, 4],[1, 7, 4]],
  29. [[9, 0, 1], [3, 7, 4],[0, 0, 0]]
  30. ])
  31. '''
  32. train_X = pad_sequences(train_X, padding='post')
  33.  
  34. model = Sequential()
  35. inputs = tf.keras.Input(shape=(n_in, n_feat))
  36.  
  37. # Masking
  38. masked_input = Masking(mask_value=0)(inputs)
  39.  
  40. # encoder
  41. encoder = LSTM(100, activation='relu')(masked_input)
  42.  
  43. # decoder 1: reconstruct input sequence
  44. decoder1 = RepeatVector(n_in)(encoder)
  45. decoder1 = LSTM(100, activation='relu', return_sequences=True)(decoder1)
  46. decoder1 = TimeDistributed(Dense(3))(decoder1)
  47.  
  48. # decoder 2: reconstruct output sequence
  49. decoder2 = RepeatVector(n_out)(encoder)
  50. decoder2 = LSTM(100, activation='relu', return_sequences=True)(decoder2)
  51. decoder2 = TimeDistributed(Dense(1))(decoder2)
  52.  
  53. model = tf.keras.Model(inputs=inputs, outputs=[decoder1, decoder2])
  54. model.compile(optimizer='rmsprop', loss='mse')
  55. # print(model.summary())
  56.  
  57. model.fit(train_X, [train_X, train_Y], epochs=500, verbose=1)
  58. yhat = model.predict(train_X, verbose=0)
  59. print(yhat)
  60. print('==========================================')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement