Advertisement
jack06215

[keras] batch size 1 training

May 29th, 2020
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.06 KB | None | 0 0
  1. from tensorflow.keras import Sequential
  2. from tensorflow.keras.utils import Sequence
  3. from tensorflow.keras.layers import LSTM, Dense, Masking, BatchNormalization, TimeDistributed, Lambda, RepeatVector
  4. from tensorflow.keras.optimizers import RMSprop
  5. import numpy as np
  6. from tensorflow.keras.preprocessing.sequence import pad_sequences
  7.  
  8. import matplotlib.pyplot as plt
  9. import tensorflow as tf
  10.  
  11. import math
  12.  
  13. # Parameters
  14. N = 30000
  15. halfN = int(N/2)
  16. dimension = 10
  17. rand_seq_len = 100
  18.  
  19. # Data
  20. np.random.seed(123)  # to generate the same numbers
  21.  
  22. # create sequence lengths between 1 to rand_seq_len
  23. seq_lens = np.random.randint(1, rand_seq_len, halfN)
  24. X_zero = np.array([np.random.normal(0, 1, size=(seq_len, dimension)) for seq_len in seq_lens])
  25. y_zero = np.zeros((halfN, 1))
  26.  
  27. X_one = np.array([np.random.normal(1, 1, size=(seq_len, dimension)) for seq_len in seq_lens])
  28. y_one = np.ones((halfN, 1))
  29.  
  30. # shuffle zero and one classes
  31. p = np.random.permutation(N)  
  32. X = np.concatenate((X_zero, X_one))[p]
  33. y = np.concatenate((y_zero, y_one))[p]
  34.  
  35. class MyBatchGenerator(Sequence):
  36.     'Generates data for Keras'
  37.     def __init__(self, X, y, batch_size=1, shuffle=True):
  38.         'Initialization'
  39.         self.X = X
  40.         self.y = y
  41.         self.batch_size = batch_size
  42.         self.shuffle = shuffle
  43.         self.on_epoch_end()
  44.  
  45.     def __len__(self):
  46.         'Denotes the number of batches per epoch'
  47.         return int(np.floor(len(self.y)/self.batch_size))
  48.  
  49.     def __getitem__(self, index):
  50.         return self.__data_generation(index)
  51.  
  52.     def on_epoch_end(self):
  53.         'Shuffles indexes after each epoch'
  54.         self.indexes = np.arange(len(self.y))
  55.         if self.shuffle == True:
  56.             np.random.shuffle(self.indexes)
  57.  
  58.     def __data_generation(self, index):
  59.         Xb = np.empty((self.batch_size, *X[index].shape))
  60.         yb = np.empty((self.batch_size, *y[index].shape))
  61.         # naively use the same sample over and over again
  62.         for s in range(0, self.batch_size):
  63.             Xb[s] = X[index]
  64.             yb[s] = y[index]
  65.         return Xb, yb
  66.  
  67. lstm_units = 3
  68. # Batch = 1
  69. model = Sequential()
  70. model.add(LSTM(lstm_units, input_shape=(None, dimension)))
  71. model.add(Dense(1, activation='sigmoid'))
  72. model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
  73. print(model.summary())
  74. model.fit_generator(MyBatchGenerator(X, y, batch_size=1), epochs=2)
  75.  
  76. # Padding and Masking
  77. special_value = -10.0
  78. max_seq_len = max(seq_lens)
  79. # Xpad = np.full((N, max_seq_len, dimension), fill_value=special_value)
  80. # for s, x in enumerate(X):
  81. #     seq_len = x.shape[0]
  82. #     Xpad[s, 0:seq_len, :] = x
  83. Xpad = pad_sequences(X, maxlen=max_seq_len, dtype='float', padding='post')  
  84.  
  85. model2 = Sequential()
  86. model2.add(Masking(mask_value=special_value, input_shape=(max_seq_len, dimension)))
  87. model2.add(LSTM(lstm_units))
  88. model2.add(Dense(1, activation='tanh'))
  89. model2.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
  90. print(model2.summary())
  91. history = model2.fit(Xpad, y, epochs=50, batch_size=32)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement