LSTM是優秀的循環神經網絡(RNN)結構,而LSTM在結構上也比較復雜,對RNN和LSTM還稍有疑問的朋友可以參考:Recurrent Neural Networks vs LSTM
這里我們將要使用Keras搭建LSTM.Keras封裝了一些優秀的深度學習框架的底層實現,使用起來相當簡潔,甚至不需要深度學習的理論知識,你都可以輕松快速的搭建你的深度學習網絡,強烈推薦給剛入門深度學習的同學使用,當然我也是還沒入門的那個。Keras:https://keras.io/,keras的backend有,theano,TensorFlow、CNTk,這里我使用的是TensorFlow。
下面我們就開始搭建LSTM,實現mnist數據的分類。
step 0 加載包和定義參數
mnist的image是28*28的shape,我們定義LSTM的input為(28,),將image一行一行地輸入到LSTM的cell中,這樣time_step就是28,表示一個image有28行,LSTM的output是30個。
from keras.datasets import mnist from keras.layers import Dense, LSTM from keras.utils import to_categorical from keras.models import Sequential #parameters for LSTM nb_lstm_outputs = 30 #神經元個數 nb_time_steps = 28 #時間序列長度 nb_input_vector = 28 #輸入序列
step 1 數據預處理
特別注意label要使用one_hot encoding,x_train的shape(60000, 28,28)
1 #data preprocessing: tofloat32, normalization, one_hot encoding 2 (x_train, y_train), (x_test, y_test) = mnist.load_data() 3 x_train = x_train.astype('float32') 4 x_test = x_test.astype('float32') 5 x_train /= 255 6 x_test /= 255 7 8 y_train = to_categorical(y_train, num_classes=10) 9 y_test = to_categorical(y_test, num_classes=10)
step 2 搭建模型
keras搭建模型相當簡單,只需要在Sequential容器中不斷add新的layer就可以了。
1 #build model 2 model = Sequential() 3 model.add(LSTM(units=nb_lstm_outputs, input_shape=(nb_time_steps, nb_input_vector))) 4 model.add(Dense(10, activation='softmax'))
step 3 compile
模型compile,指定loss function, optimizer, metrics
1 #compile:loss, optimizer, metrics 2 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
step 4 train
模型訓練,需要指定,epochs訓練的輪次數,batch_size。
1 #train: epcoch, batch_size 2 model.fit(x_train, y_train, epochs=20, batch_size=128, verbose=1)
step 5 evaluate
可以使用model.summary()來查看你的神經網絡的架構和參數量等信息。

1 model.summary() 2 3 score = model.evaluate(x_test, y_test,batch_size=128, verbose=1) 4 print(score)
我的最后結果是:

