Python Lstm库函数的调用
Talk is cheap. Show me the code.
(Linux 创始人 Linus Torvalds在2000年08月25日给linux-kernel邮件列表的一封邮件提到的。能说算不上什么,有本事就把你的代码给我看看。)
话不多说,直接上代码:
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
x=[[1],[2],[3]]#特征
y=[2,4,6]#标签
x = np.array( x )
y_train = np.array(y )
x_train = np.reshape( x, (x.shape[0], x.shape[1], 1) )#Lstm调用库函数必须要进行维度转换
model = Sequential()
model.add( LSTM( 100, input_shape=(x_train.shape[1], x_train.shape[2]), return_sequences=True) )
model.add( LSTM( 20, return_sequences=False ) )
model.add( Dropout( 0.2 ) )
model.add( Dense( 1 ) )
model.add( Activation( 'linear' ) )
model.compile( loss="mse", optimizer="rmsprop" )
model.fit( x_train, y_train, epochs=200, batch_size=1)#参数依次为特征,标签,训练循环次数,小批量(一次放入训练的数据个数)
test=[[1.5]]
test=np.array(test)
test = np.reshape( test, (test.shape[0], test.shape[1], 1) )#维度转换
res = model.predict( test )
print( res )
以上代码调用Lstm库函数拟实现让Lstm学习到从特征1,2,3
到标签2,2,6
的映射,类似函数
y
=
2
∗
x
y = 2*x
y=2∗x的功能,我们使用1.5
来测试,看测试结果与2*1.5=3
的相差程度来看模型训练的效果。
我这运行的结果如下,实验结果每次运行会有一定的出入,但误差应该不会很大。
PS:
本次运行的python版本为(Python 3.7.2):
代码运行过程中出现缺包等问题可用 “pip install '需要安装的包'
”(如“pip install numpy
”)来解决,运行代码或者python环境配置有问题可与笔者联系(ljt_IT@163.com)。
有使用过Python Lstm库函数的朋友应该会发现这种使用方法必须要求所有的特征必须是等长的,关于变长输入的问题将在“Python Lstm mask机制”这节中展示。