In [17]:
from keras.models import Sequential
from keras.layers import LSTM, Dense, Activation
from keras.optimizers import SGD
  • LSTMモデルへの入力は3Dテンソル (Samples, Time steps, Features)

In [13]:
model = Sequential()
model.add(LSTM(5, input_shape=(2, 1)))  # (timesteps, features)
model.add(Dense(1))
model.add(Activation('sigmoid'))

In [14]:
model.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm_8 (LSTM)                (None, 5)                 140       
_________________________________________________________________
dense_6 (Dense)              (None, 1)                 6         
_________________________________________________________________
activation_3 (Activation)    (None, 1)                 0         
=================================================================
Total params: 146
Trainable params: 146
Non-trainable params: 0
_________________________________________________________________

In [15]:
model.compile(optimizer='sgd', loss='mse')

In [20]:
algorithm = SGD(lr=0.1, momentum=0.3)
model.compile(optimizer=algorithm, loss='mean_squared_error', metrics=['accuracy'])

Examples of LSTM with Single Input Sample


In [21]:
from numpy import array

In [22]:
data = array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])

In [23]:
data = data.reshape((1, 10, 1))  # 1 sample, 10 timesteps, 1 feature

Multiple Input Features


In [27]:
data = array([
        [0.1, 1.0],
        [0.2, 0.9],
        [0.3, 0.8],
        [0.4, 0.7],
        [0.5, 0.6],
        [0.6, 0.5],
        [0.7, 0.4],
        [0.8, 0.3],
        [0.9, 0.2],
        [1.0, 0.1]
    ])

In [28]:
data.shape


Out[28]:
(10, 2)

In [29]:
data = data.reshape(1, 10, 2)

In [30]:
data.shape


Out[30]:
(1, 10, 2)

In [31]:
data


Out[31]:
array([[[ 0.1,  1. ],
        [ 0.2,  0.9],
        [ 0.3,  0.8],
        [ 0.4,  0.7],
        [ 0.5,  0.6],
        [ 0.6,  0.5],
        [ 0.7,  0.4],
        [ 0.8,  0.3],
        [ 0.9,  0.2],
        [ 1. ,  0.1]]])

In [ ]: