Keras实现LSTM

一、先看一个Example

1、描述,输入为一个字母,输出为这个字母的下一个顺序字母

  • A->B
  • B->C
  • C->D

2、Code

import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.utils import np_utils

# 固定每次的随机数都是相同的
numpy.random.seed(7)

# define the raw dataset
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# create mapping of characters to integers (0-25) and the reverse
char_to_int = dict((c, i) for i, c in enumerate(alphabet))
int_to_char = dict((i, c) for i, c in enumerate(alphabet))

# prepare the dataset of input to output pairs encoded as integers
seq_length = 1
dataX = []
dataY = []
for i in range(0, len(alphabet) - seq_length, 1):
    seq_in = alphabet[i:i + seq_length]
    seq_out = alphabet[i + seq_length]
    dataX.append([char_to_int[char] for char in seq_in])
    dataY.append(char_to_int[seq_out])
    print(seq_in, '->', seq_out)

# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (len(dataX), seq_length, 1))

# normalize
X = X / float(len(alphabet))

print(X.shape[0], X.shape[1], X.shape[2])

# one hot encode the output variable
y = np_utils.to_categorical(dataY)

# create and fit the model
model = Sequential()
model.add(LSTM(32, input_shape=(X.shape[1], X.shape[2])))

model.add(Dense(y.shape[1], activation='softmax'))


model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X, y, nb_epoch=500, batch_size=1, verbose=2)

scores = model.evaluate(X, y, verbose=0)
print("Model Accuracy: %.2f%%" % (scores[1] * 100))

二、Keras中的LSTM

1、Keras中的LSTM被reshape成的形状[samples, time steps, features]。time steps就是所谓的时间序列步骤。上述例子中,句子实际上是多个时间步骤,一个特征而并非一个时间步骤,多个特征。

看上述的这行代码

X = numpy.reshape(dataX, (len(dataX), seq_length, 1))
  • Samples:这是dataX的长度,或者数据集的大小
  • Time steps:这个和RNN的time steps等价。如果你的网络想有60个字母的记忆,那么这里面的数字就写上60
  • Features:这个是每个time steps的特征数量。如果正在处理图片的话,那么这个就是一个图片像素的个数。在这里每个time step就是一个feature

2、X = numpy.reshape(dataX, (len(dataX), 3, 1)) and X = numpy.reshape(dataX, (len(dataX), 1, 3))对LSTM最终结果有什么影响呢?

  • (len(dataX), 3, 1) 会使LSTM迭代3次,体现了循环神经网路的特点
  • (len(dataX), 1, 3) 会使得LSTM只迭代一次,对与循环神经网络这毫无意义,根本就没有使用到LS的特性

也可以理解TimeSteps就是unfold的意思,就是tensorflow中的NUM_STEPS的意思。

Features其实就是输入的纬度,也就是特征,一个纬度一个特征。

三、进阶

猜你喜欢

转载自www.cnblogs.com/ylxn/p/10722477.html