lstm原理
rnn lstm实例
lstm原理文本相关。主要应用于自然语言处理(NLP)、对话系统、情感分析、机器翻译等等领域,Google翻译用的就是一个7-8层的LSTM模型。时序相关:就是时间序列的预测,诸如预测天气/温度/.为何全连接层和卷积神经网络无法处理序列问题,因为缺乏记忆模块,无法记忆之前输入的内容. rnn
- 简单的rnn。输入是2维的(timesteps, input_features). 这里的loop就是在timesteps上的loop:每一个时刻t,RNN会考虑当前时刻t 的状态state,以及当前时刻t 的输入(维度是(input_features,)),然后总和得到在时刻t的输出。并且为当前时刻t的输出去更新状态state。但是最初的时刻,没有上一个时刻的输出,所以state会被全初始化为0,叫做initial state of the network.
state_t = 0 #时刻t的状态
for input_t in input_sequence: # 在timesteps上loop
output_t = f(input_t, state_t) # input_t state_t得到时刻t输出
state_t = output_t #用当前输出去更新内部状态
f是一个函数
简单的rnn例子:rnn其实就是在时间的闭环循环,每次的输入都需要上次的结果
import numpy as np
timesteps = 100
input_features = 32
output_features = 64
inputs = np.random.random(shape=(timesteps, input_features))
state_t = np.zeros(shape=(output_features,)) # init state
W = np.random.random(shape=(output_features, input_features))
U = np.random.random(shape=(output_features, output_features))
b = np.random.random(shape=(output_features,))
successive_outputs = []
for input_t in inputs:
output_t = np.tanh(np.dot(W, input_t) + np.dot(U, state_t) + b) #input_t state_t => output_t
successive_outputs.append(output_t)
state_t = output_t # update state_t using output_t
final_outputs = np.concatenate(successive_outputs, axis=0)
rnn 优点: 效果肯定比DNN好,毕竟有中间状态的信息输入rnn 缺点: 梯度消失,导致长跨度的时间序列模型无法训练. lstm实例
lstm就是解决RNN梯度消失的问题.[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OO6Flycm-1645781319754)(https://raw.githubusercontent.com/errolyan/tuchuang/master/uPic/3wiNmA.jpg)]
当前时刻的输出就应该收到三个信息的影响:当前时刻的输入、当前时刻的状态、传送带上带来的很久以前的信息。如下:output_t = activation(dot(state_t, Uo) + dot(input_t, Wo) + dot(C_t, Vo) + bo)传送带上的状态更新就是LSTM的重点了,也是复杂的地方:
根据input_t, state_t以及三套不同的W U b,来计算出三个值: i_t = activation(dot(state_t, Ui) + dot(input_t, Wi)+ bi) f_t = activation(dot(state_t, Uf) + dot(input_t, Wf) + bf) k_t = activation(dot(state_t, Uk) + dot(input_t, Wk) + bk) 然后组合这三个值来更新C_t: c_t+1 = i_t * k_t + c_t * f_t 1. c_t * f_t 是为了让模型忘记一些不相关的信息,在carry dataflow的时候。即时是很久之前的信息,模型也有不用他的选择权利,所以模型要有忘记不相关信息的能力。 这也就是常说的遗忘门(我觉得翻译成中文真的很没意思,因为中文的“门”意思是在是太多了,你懂得)。 2. i_t * k_t 为模型提供关于当前时刻的信息,给carry track增加一些新的信息。
from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import Dataframe
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
import numpy as np
from datetime import datetime
# load data
def parse(x):
return datetime.strptime(x, '%Y %m %d %H')
dataset = read_csv('datasets/raw.csv', parse_dates = [['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse)
dataset.drop('No', axis=1, inplace=True)
dataset.columns = ['pollution', 'dew', 'temp', 'press', 'wnd_dir', 'wnd_spd', 'snow', 'rain'] # manually specify column names
dataset.index.name = 'date'
dataset['pollution'].fillna(0, inplace=True) # mark all NA values with 0
dataset = dataset[24:] # drop the first 24 hours
print(dataset.head(5)) # summarize first 5 rows
dataset.to_csv('datasets/pollution.csv') # save to file
#转成有监督数据
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = Dataframe(data)
cols, names = list(), list()
#数据序列(也将就是input) input sequence (t-n, ... t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
#预测数据(input对应的输出值) forecast sequence (t, t+1, ... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
#拼接 put it all together
agg = concat(cols, axis=1)
agg.columns = names
# 删除值为NAN的行 drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
return agg
##数据预处理 load dataset
dataset = read_csv('datasets/pollution.csv', header=0, index_col=0)
values = dataset.values
encoder = LabelEncoder() #标签编码 integer encode direction
values[:, 4] = encoder.fit_transform(values[:, 4])
values = values.astype('float32') #保证为float ensure all data is float
scaler = MinMaxScaler(feature_range=(0, 1)) #归一化 normalize features
scaled = scaler.fit_transform(values)
reframed = series_to_supervised(scaled, 1, 1) #转成有监督数据 frame as supervised learning
reframed.drop(reframed.columns[[9, 10, 11, 12, 13, 14, 15]], axis=1, inplace=True) #删除不预测的列 drop columns we don't want to predict
print(reframed.head())
#数据准备
values = reframed.values #把数据分为训练数据和测试数据 split into train and test sets
n_train_hours = 365 * 24 #拿一年的时间长度训练
train = values[:n_train_hours, :] #划分训练数据和测试数据
test = values[n_train_hours:, :]
train_X, train_y = train[:, :-1], train[:, -1] #拆分输入输出 split into input and outputs
test_X, test_y = test[:, :-1], test[:, -1]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1])) #reshape输入为LSTM的输入格式 reshape input to be 3D [samples, timesteps, features]
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print ('train_x.shape, train_y.shape, test_x.shape, test_y.shape')
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
##模型定义 design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
history = model.fit(train_X, train_y, epochs=5, batch_size=72, validation_data=(test_X, test_y), verbose=2,shuffle=False)
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:, 0]
inv_yhat = np.array(inv_yhat)
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, 1:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:, 0]
#画出真实数据和预测数据
pyplot.plot(inv_yhat,label='prediction')
pyplot.plot(inv_y,label='true')
pyplot.legend()
pyplot.show()
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)



