Python深度学习7-使用seq2seq+attention进行时序预测

本文旨在进行时间序列预测,采用seq2seq+attention的模型架构进行预测,数据集样式如下:


数据集样式

一、导入包和数据

我都tensorflow版本是2.7,keras版本2.7

import csv
import numpy as np
from keras import backend as K
from keras.models import  Model
from keras.layers import LSTM, Dense, Activation,  Lambda, RepeatVector, Input, Reshape, Concatenate, Dot
from sklearn.preprocessing import MinMaxScaler
import os
import errno
import math

def file_processing(file_path, encode=None):
    data = []

    with open(file_path, encoding=encode) as file:
        rows = csv.reader(file, delimiter=",")
        n_row = 0

        for row in rows:
            if n_row != 0:
                #column -> 0: code, 1: date
                for column in range(2, len(row)):
                    data[n_row - 1].append(float(row[column].strip()))

            data.append([])
            n_row += 1

    del data[-1]
    return np.array(data)

data = file_processing('20180504_50.csv')

二、数据集的处理

####归一化
def normalize_data(data, scaler, feature_len):
    minmaxscaler = scaler.fit(data)
    normalize_data = minmaxscaler.transform(data)

    return normalize_data

###处理成时序模型所需要的样本
def load_data(data, time_step=20, after_day=1, validate_percent=0.67):
    seq_length = time_step + after_day
    result = []
    for index in range(len(data) - seq_length + 1):
        result.append(data[index: index + seq_length])

    result = np.array(result)
    print('total data: ', result.shape)

    train_size = int(len(result) * validate_percent)
    train = result[:train_size, :]
    validate = result[train_size:, :]

    x_train = train[:, :time_step]
    y_train = train[:, time_step:]
    x_validate = validate[:, :time_step]
    y_validate = validate[:, time_step:]

    return [x_train, y_train, x_validate, y_validate]

time_step = 20  ###处理时序特征的时候20个作为一组
feature_len = data.shape[1] ###数据中有几列数据需要预测
scaler = MinMaxScaler(feature_range=(0, 1)) ###归一化
validate_percent = 0.8 ###验证集训练集拆分比例2:8
after_day = 6   ####预测之后6天
# 数据归一化
data = normalize_data(data, scaler, feature_len)
 # 以最后的历史样本作为测试集
x_test = data[-time_step:]
x_test = np.reshape(x_test, (1, x_test.shape[0], x_test.shape[1]))
# 得到训练集和验证集
x_train, y_train, x_validate, y_validate = load_data(
            data, time_step=time_step, after_day=after_day, validate_percent=validate_percent)

###一组20个特征,标签维度是6, 5列,用一步一步推进的方式构造出1025条训练样本
#x_train.shape, y_train.shape:  (1025, 20, 5) (1025, 6, 5)
##x_validate.shape, y_validate.shape: (257, 20, 5) (257, 6, 5)

数据处理样式如图:


时序数据处理样式

三、模型建立

使用seq2seq+attention方式构建时序预测模型。

def softmax(x, axis=1):
    """Softmax activation function.
    # Arguments
        x : Tensor.
        axis: Integer, axis along which the softmax normalization is applied.
    # Returns
        Tensor, output of softmax transformation.
    # Raises
        ValueError: In case `dim(x) == 1`.
    """
    ndim = K.ndim(x)
    if ndim == 2:
        return K.softmax(x)
    elif ndim > 2:
        e = K.exp(x - K.max(x, axis=axis, keepdims=True))
        s = K.sum(e, axis=axis, keepdims=True)
        return e / s
    else:
        raise ValueError('Cannot apply softmax to a tensor that is 1D')

def mean_squared_error(y_true, y_pred):
    return K.mean(K.square(y_pred[:,:,3] - y_true[:,:,3]), axis=-1)
        
def one_step_attention(a, s_prev, repeator, concatenator, densor, activator, dotor):
    ##将s_prev复制
    s_prev = repeator(s_prev)
    ### 拼接BiRNN隐层状态与s_prev
    concat = concatenator([s_prev, a])
    e = densor(concat)
    alphas = activator(e)
    # 加权得到Context Vector
    context =  dotor([alphas, a])
    return context

def seq2seq_attention(feature_len=1, after_day=1, input_shape=(20, 1), time_step=20):
    # Define the inputs of your model with a shape (Tx, feature)
    X = Input(shape=input_shape)
    
    ###Decoder端LSTM的初始状态
    s0 = Input(shape=(100, ), name='s0')
    c0 = Input(shape=(100, ), name='c0')
    ##Decoder前一时刻解码的输出s
    s = s0
   ##Eecoder输出的c
    c = c0

    # 模型输出列表,用来存储预测的结果
    all_outputs = []

    # Encoder: pre-attention LSTM
    encoder = LSTM(units=100, return_state=False, return_sequences=True, name='encoder')
    # Decoder: post-attention LSTM
    decoder = LSTM(units=100, return_state=True, name='decoder')
    # Output
    decoder_output = Dense(units=feature_len, activation='linear', name='output')
    model_output = Reshape((1, feature_len))

    # Attention
    repeator = RepeatVector(time_step)
    concatenator = Concatenate(axis=-1)
    densor = Dense(1, activation = "relu")
    activator = Activation(softmax, name='attention_weights')
    dotor =  Dot(axes = 1)

    encoder_outputs = encoder(X)

    for t in range(after_day):
        context = one_step_attention(encoder_outputs, s, repeator, concatenator, densor, activator, dotor)

        a, s, c = decoder(context, initial_state=[s, c])

        outputs = decoder_output(a)
        outputs = model_output(outputs)
        all_outputs.append(outputs)

    all_outputs = Lambda(lambda x: K.concatenate(x, axis=1))(all_outputs)
    model = Model(inputs=[X, s0, c0], outputs=all_outputs)

    return model

####输入每条构建样本大小
input_shape = (time_step, feature_len)
model = seq2seq_attention(feature_len, after_day, input_shape, time_step)
model.compile(loss=mean_squared_error, optimizer='adam')
model.summary()

四、模型的训练和评估

batch_size = 64
epochs = 300

def save_model(model, model_name):
    file_path = 'model_test/{}.h5'.format(model_name)
    if not os.path.exists(os.path.dirname(file_path)):
        try:
            os.makedirs(os.path.dirname(file_path))
        except OSError as exc: # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise

    model.save(file_path)

s0_train = np.zeros((x_train.shape[0],100))
c0_train = np.zeros((x_train.shape[0],100))
s0_validate = np.zeros((x_validate.shape[0],100))
c0_validate = np.zeros((x_validate.shape[0],100))
s0_test = np.zeros((x_test.shape[0],100))
c0_test = np.zeros((x_test.shape[0],100))
###模型的训练
history = model.fit(
    [x_train, s0_train, c0_train], y_train,
    batch_size=batch_size, epochs=epochs,
    validation_data=([x_validate, s0_validate, c0_validate], y_validate))

print('-' * 100)
train_score = model.evaluate([x_train,s0_train,c0_train], y_train, batch_size=batch_size, verbose=0)
print('Train Score: %.8f MSE (%.8f RMSE)' % (train_score, math.sqrt(train_score)))
validate_score = model.evaluate([x_validate,s0_validate,c0_validate], y_validate, batch_size=batch_size, verbose=0)
print('Test Score: %.8f MSE (%.8f RMSE)' % (validate_score, math.sqrt(validate_score)))

model_class_name = 'model23'
save_model(model, model_name=model_class_name)

五、模型预测

train_predict = model.predict([x_train,s0_train,c0_train])
validate_predict = model.predict([x_validate,s0_validate,c0_validate])
test_predict = model.predict([x_test,s0_test,c0_test])   ####预测出的真实值

###反归一化  归一化的数据要转换回去
def inverse_normalize_data(data, scaler):
    for i in range(len(data)):
        data[i] = scaler.inverse_transform(data[i])
    return data

train_predict = inverse_normalize_data(train_predict, scaler)
y_train = inverse_normalize_data(y_train, scaler)
validate_predict = inverse_normalize_data(validate_predict, scaler)
y_validate = inverse_normalize_data(y_validate, scaler)
test_predict = inverse_normalize_data(test_predict, scaler)
print(test_predict) ###接下来6天的预测结果

六、完整代码如下

import csv
import numpy as np
from keras import backend as K
from keras.models import  Model
from keras.layers import LSTM, Dense, Activation,  Lambda, RepeatVector, Input, Reshape, Concatenate, Dot
from sklearn.preprocessing import MinMaxScaler
import os
import errno
import math

def file_processing(file_path, encode=None):
    data = []

    with open(file_path, encoding=encode) as file:
        rows = csv.reader(file, delimiter=",")
        n_row = 0

        for row in rows:
            if n_row != 0:
                #column -> 0: code, 1: date
                for column in range(2, len(row)):
                    data[n_row - 1].append(float(row[column].strip()))

            data.append([])
            n_row += 1

    del data[-1]
    return np.array(data)


####归一化
def normalize_data(data, scaler, feature_len):
    minmaxscaler = scaler.fit(data)
    normalize_data = minmaxscaler.transform(data)

    return normalize_data

###处理成时序模型所需要的样本
def load_data(data, time_step=20, after_day=1, validate_percent=0.67):
    seq_length = time_step + after_day
    result = []
    for index in range(len(data) - seq_length + 1):
        result.append(data[index: index + seq_length])

    result = np.array(result)
    print('total data: ', result.shape)

    train_size = int(len(result) * validate_percent)
    train = result[:train_size, :]
    validate = result[train_size:, :]

    x_train = train[:, :time_step]
    y_train = train[:, time_step:]
    x_validate = validate[:, :time_step]
    y_validate = validate[:, time_step:]

    return [x_train, y_train, x_validate, y_validate]

def softmax(x, axis=1):
    """Softmax activation function.
    # Arguments
        x : Tensor.
        axis: Integer, axis along which the softmax normalization is applied.
    # Returns
        Tensor, output of softmax transformation.
    # Raises
        ValueError: In case `dim(x) == 1`.
    """
    ndim = K.ndim(x)
    if ndim == 2:
        return K.softmax(x)
    elif ndim > 2:
        e = K.exp(x - K.max(x, axis=axis, keepdims=True))
        s = K.sum(e, axis=axis, keepdims=True)
        return e / s
    else:
        raise ValueError('Cannot apply softmax to a tensor that is 1D')

def mean_squared_error(y_true, y_pred):
    return K.mean(K.square(y_pred[:,:,3] - y_true[:,:,3]), axis=-1)
        
def one_step_attention(a, s_prev, repeator, concatenator, densor, activator, dotor):
    ##将s_prev复制
    s_prev = repeator(s_prev)
    ### 拼接BiRNN隐层状态与s_prev
    concat = concatenator([s_prev, a])
    e = densor(concat)
    alphas = activator(e)
    # 加权得到Context Vector
    context =  dotor([alphas, a])
    return context


def seq2seq_attention(feature_len=1, after_day=1, input_shape=(20, 1), time_step=20):
    # Define the inputs of your model with a shape (Tx, feature)
    X = Input(shape=input_shape)
    
    ###Decoder端LSTM的初始状态
    s0 = Input(shape=(100, ), name='s0')
    c0 = Input(shape=(100, ), name='c0')
   ##Decoder前一时刻解码的输出s
    s = s0
   ##Eecoder输出的c
    c = c0

    # 模型输出列表,用来存储预测的结果
    all_outputs = []

    # Encoder: pre-attention LSTM
    encoder = LSTM(units=100, return_state=False, return_sequences=True, name='encoder')
    # Decoder: post-attention LSTM
    decoder = LSTM(units=100, return_state=True, name='decoder')
    # Output
    decoder_output = Dense(units=feature_len, activation='linear', name='output')
    model_output = Reshape((1, feature_len))

    # Attention
    repeator = RepeatVector(time_step)
    concatenator = Concatenate(axis=-1)
    densor = Dense(1, activation = "relu")
    activator = Activation(softmax, name='attention_weights')
    dotor =  Dot(axes = 1)

    encoder_outputs = encoder(X)

    for t in range(after_day):
        context = one_step_attention(encoder_outputs, s, repeator, concatenator, densor, activator, dotor)

        a, s, c = decoder(context, initial_state=[s, c])

        outputs = decoder_output(a)
        outputs = model_output(outputs)
        all_outputs.append(outputs)

    all_outputs = Lambda(lambda x: K.concatenate(x, axis=1))(all_outputs)
    model = Model(inputs=[X, s0, c0], outputs=all_outputs)

    return model

def save_model(model, model_name):
    file_path = 'model_test/{}.h5'.format(model_name)
    if not os.path.exists(os.path.dirname(file_path)):
        try:
            os.makedirs(os.path.dirname(file_path))
        except OSError as exc: # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise

    model.save(file_path)

###反归一化
def inverse_normalize_data(data, scaler):
    for i in range(len(data)):
        data[i] = scaler.inverse_transform(data[i])

    return data


if __name__ == '__main__':
    data = file_processing('20180504_50.csv')
    time_step = 20  ###处理时序特征的时候20个作为一组
    feature_len = data.shape[1] ###数据中有几列数据需要预测
    scaler = MinMaxScaler(feature_range=(0, 1)) ###归一化
    validate_percent = 0.8 ###验证集训练集拆分比例2:8
    after_day = 6   ####预测之后6天
    # 数据归一化
    data = normalize_data(data, scaler, feature_len)
     # 以最后的历史样本作为测试集
    x_test = data[-time_step:]
    x_test = np.reshape(x_test, (1, x_test.shape[0], x_test.shape[1]))
    # 得到训练集和验证集
    x_train, y_train, x_validate, y_validate = load_data(
                data, time_step=time_step, after_day=after_day, validate_percent=validate_percent)
    
    ###一组20个特征,6个标签,5列,用一步一步推进的方式构造出1025条训练样本
    #x_train.shape, y_train.shape:  (1025, 20, 5) (1025, 6, 5)
    ##x_validate.shape, y_validate.shape: (257, 20, 5) (257, 6, 5)
    
    
    ####输入每条构建样本大小
    input_shape = (time_step, feature_len)
    
    model = seq2seq_attention(feature_len, after_day, input_shape, time_step)
    model.compile(loss=mean_squared_error, optimizer='adam')
    model.summary()
    
    batch_size = 64
    epochs = 300

    s0_train = np.zeros((x_train.shape[0],100))
    c0_train = np.zeros((x_train.shape[0],100))
    s0_validate = np.zeros((x_validate.shape[0],100))
    c0_validate = np.zeros((x_validate.shape[0],100))
    s0_test = np.zeros((x_test.shape[0],100))
    c0_test = np.zeros((x_test.shape[0],100))
    
    history = model.fit(
        [x_train, s0_train, c0_train], y_train,
        batch_size=batch_size, epochs=epochs,
        validation_data=([x_validate, s0_validate, c0_validate], y_validate))
    
    
    print('-' * 100)
    train_score = model.evaluate([x_train,s0_train,c0_train], y_train, batch_size=batch_size, verbose=0)
    print('Train Score: %.8f MSE (%.8f RMSE)' % (train_score, math.sqrt(train_score)))
    
    validate_score = model.evaluate([x_validate,s0_validate,c0_validate], y_validate, batch_size=batch_size, verbose=0)
    print('Test Score: %.8f MSE (%.8f RMSE)' % (validate_score, math.sqrt(validate_score)))
    
    model_class_name = 'model22'
    save_model(model, model_name=model_class_name)
    
    train_predict = model.predict([x_train,s0_train,c0_train])
    validate_predict = model.predict([x_validate,s0_validate,c0_validate])
    test_predict = model.predict([x_test,s0_test,c0_test])   ####预测出的真实值
    
    
    train_predict = inverse_normalize_data(train_predict, scaler)
    y_train = inverse_normalize_data(y_train, scaler)
    validate_predict = inverse_normalize_data(validate_predict, scaler)
    y_validate = inverse_normalize_data(y_validate, scaler)
    test_predict = inverse_normalize_data(test_predict, scaler)
    
    print(test_predict)

七、总结

seq2seq(sequence to sequence)模型一般包括两个部分:编码器(encoder)和解码器(decoder),其中编码器主要是用于处理序列信息,解码器将这个信息处理出来得到一个输出的序列,这样的模型允许使用长度不同的输入和输出序列。而Attention将底层特征直接传递至网络的后层,可在一定程度上解决细节丢失和梯度消失的问题。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容