|
| 1 | +"""Use Avg pooling on output of LSTM, RNN, GRU, or any recurrent layer. |
| 2 | +Author: Mohit Mayank |
| 3 | +Taken from my answer to this question: https://stackoverflow.com/questions/36428323/lstm-followed-by-mean-pooling/64630846#64630846 |
| 4 | +""" |
| 5 | + |
| 6 | +# create sample data |
| 7 | +A=np.array([[1,2,3],[4,5,6],[0,0,0],[0,0,0],[0,0,0]]) |
| 8 | +B=np.array([[1,3,0],[4,0,0],[0,0,1],[0,0,0],[0,0,0]]) |
| 9 | +C=np.array([A,B]).astype("float32") |
| 10 | +# expected answer (for temporal mean) |
| 11 | +np.mean(C, axis=1) |
| 12 | +""" |
| 13 | +The output is |
| 14 | +
|
| 15 | +array([[1. , 1.4, 1.8], |
| 16 | + [1. , 0.6, 0.2]], dtype=float32) |
| 17 | +Now using AveragePooling1D, |
| 18 | +""" |
| 19 | +model = keras.models.Sequential( |
| 20 | + tf.keras.layers.AveragePooling1D(pool_size=5) |
| 21 | +) |
| 22 | +model.predict(C) |
| 23 | +""" |
| 24 | +The output is, |
| 25 | +
|
| 26 | +array([[[1. , 1.4, 1.8]], |
| 27 | + [[1. , 0.6, 0.2]]], dtype=float32) |
| 28 | +Some points to consider, |
| 29 | +- The pool_size should be equal to the step/timesteps size of the recurrent layer. |
| 30 | +- The shape of the output is (batch_size, downsampled_steps, features), which contains one additional downsampled_steps dimension. This will be always 1 if you set the pool_size equal to timestep size in recurrent layer. |
| 31 | +""" |
0 commit comments