7 时间序列单特征:多输入->多输出(LSTM/GRU/TCN)

news2024/9/21 2:34:34

        今天看到关于时间序列预测知识点,竟然要收费!本着开源第一的思想,自己也找到相关的代码尝试一下写几个通用的模版。

模型想要

        输入:Input = (input_size, hidden_size),其中:input_size = time_stemp,因为是单个变量因此hidden_size = 1;

        输出: output_size; 输出的步长;

1 数据预处理

一般数据都是按照时间步长展开,然后每一步可能有很多的特征。

比如下面的(来自科大讯飞的比赛数据,想要的可私聊):target:就是目标,new_dt 就是时间。

输出处理模块:通过这个模块就会得到一个 X =【batch_size,time_stemp, 1】y=[batch_size,output_size],batch_size 就是样本的个数;

def create_dataset(X, n_steps_in, n_steps_out):
    # n_steps_in 输入步长
    # n_steps_out输出步长
    print(f"Input data shape before processing: {X.shape}")
    
    Xs, ys = [], []
    for i in range(len(X) - n_steps_in - n_steps_out + 1):
        Xs.append(X[i:(i + n_steps_in)])
        ys.append(X[(i + n_steps_in):(i + n_steps_in + n_steps_out)])
    
    Xs = np.array(Xs)
    ys = np.array(ys)
    
    print(f"Xs shape after processing: {Xs.shape}")
    print(f"ys shape after processing: {ys.shape}")
    
    return Xs, ys

2  LSTM模型

import numpy as np
import pandas as pd

from sklearn.model_selection import train_test_split

from tqdm import tqdm
from sklearn.preprocessing import LabelEncoder
#import h3
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
from tqdm import tqdm

from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Flatten, Reshape, LSTM, Dropout, Dense, Bidirectional, BatchNormalization, Input, LayerNormalization, GRU, Conv1D, Concatenate, MaxPooling1D, MultiHeadAttention, GlobalAveragePooling1D, Activation, SpatialDropout1D, Lambda
from tensorflow.keras.losses import MeanSquaredError, Huber
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import warnings
import tensorflow as tf
from tensorflow.keras.regularizers import l2


train_df = pd.read_csv('../data/dataset/train.csv')
#train_df = train_df[train_df.dt<100].reset_index(drop=True)
test_df = pd.read_csv('../data/dataset/test.csv')
#train_df['target_div_dt'] = train_df['target'] / train_df['dt']

df_all = pd.concat([train_df,test_df])
df_all['dt_max'] = df_all.groupby('id')['dt'].transform('max')
df_all = df_all.sort_values(['id','dt']).reset_index(drop=True)
df_all['new_dt'] = df_all['dt_max']-df_all['dt']
df_all = df_all.sort_values(['id','new_dt']).reset_index(drop=True)
df_all.tail()
train_df = df_all[~df_all['target'].isna()].reset_index(drop=True)
test_df = df_all[df_all['target'].isna()].reset_index(drop=True)

# 构建训练数据
def create_dataset(X, n_steps_in, n_steps_out):
    print(f"Input data shape before processing: {X.shape}")
    
    Xs, ys = [], []
    for i in range(len(X) - n_steps_in - n_steps_out + 1):
        Xs.append(X[i:(i + n_steps_in)])
        ys.append(X[(i + n_steps_in):(i + n_steps_in + n_steps_out)])
    
    Xs = np.array(Xs)
    ys = np.array(ys)
    
    print(f"Xs shape after processing: {Xs.shape}")
    print(f"ys shape after processing: {ys.shape}")
    
    return Xs, ys

   
def create_model(input_shape, output_length,lr=1e-3, warehouse="None"):

    model = Sequential()
    model.add(Input(shape=input_shape))
    
    model.add(Conv1D(filters=32, kernel_size=3, activation='relu', padding='same', kernel_regularizer=l2()))
    model.add(BatchNormalization())
    model.add(Dropout(0.4))
    model.add(LSTM(units=64, activation='relu', return_sequences=False))
    model.add(Dense(output_length))
    model.compile(loss=MeanSquaredError(), optimizer=tf.keras.optimizers.RMSprop(learning_rate=lr, rho=0.9))
                  
    return model

# 迭代损失
def plot_loss(history, warehouse):
    plt.figure(figsize=(8, 6))

    # training and validation loss
    plt.plot(history.history['loss'], label='Training Loss', color='blue', linewidth=2)
    plt.plot(history.history['val_loss'], label='Validation Loss', color='orange', linewidth=2)
    
    # minimum validation loss
    min_val_loss = min(history.history['val_loss'])
    min_val_loss_epoch = history.history['val_loss'].index(min_val_loss)
    plt.axvline(min_val_loss_epoch, linestyle='--', color='gray', linewidth=1)
    plt.text(min_val_loss_epoch, min_val_loss, f'Min Val Loss: {min_val_loss:.4f}', 
             verticalalignment='bottom', horizontalalignment='right', color='gray', fontsize=10)
    
    plt.title(f'Training and Validation Loss for Warehouse: {warehouse}', fontsize=16)
    plt.xlabel('Epoch', fontsize=14)
    plt.ylabel('Loss', fontsize=14)
    plt.legend(fontsize=12)
    plt.grid(True)

    plt.xticks(fontsize=12)
    plt.yticks(fontsize=12)
    plt.tight_layout()
    
    #plt.savefig(f'training_validation_loss_{warehouse}.png', dpi=300)
    
    plt.show()


n_features = 1  # 因为这是一个一维序列
n_steps_in = 70  # 输入序列的长度
n_steps_out = 10  # 预测序列的长度
# 数据预处理
# 数据预处理

# 随机种子
tf.random.set_seed(42)
import numpy as np
np.random.seed(42)
import random
import os
error_df = {}
def set_random_seed(seed_value):
    # Set `PYTHONHASHSEED` environment variable at a fixed value
    os.environ['PYTHONHASHSEED']=str(seed_value)
    # Set `python` built-in pseudo-random generator at a fixed value
    random.seed(seed_value)
    # Set `numpy` pseudo-random generator at a fixed value
    np.random.seed(seed_value)
    # Set `tensorflow` pseudo-random generator at a fixed value
    tf.random.set_seed(seed_value)
set_random_seed(42)
import keras

class PrintCallback(keras.callbacks.Callback):
    def __init__(self, print_every=1):
        super(PrintCallback, self).__init__()
        self.print_every = print_every

    def on_epoch_end(self, epoch, logs=None):
        if (epoch + 1) % self.print_every == 0:
            print(f"Epoch {epoch + 1}: loss={logs['loss']:.4f}, val_loss={logs['val_loss']:.4f}")

# 使用示例
print_every_n_epochs = 5  # 每 5 个 epoch 打印一次
error_id = []
for id in tqdm(train_df.id.unique().tolist()):
    try:
        temp_df = train_df[train_df.id==id].reset_index(drop=True)
        X = temp_df.target.values
        x_test = X[-n_steps_in:]
        train_X,train_y =  create_dataset(X,n_steps_in,n_steps_out)
        X_train, X_val, y_train, y_val = train_test_split(train_X, train_y, test_size=0.2, shuffle=True)
        model = create_model(input_shape=(n_steps_in, 1),output_length=n_steps_out,lr=1e-3)
    
        callbacks = [
        PrintCallback(print_every=print_every_n_epochs),
        EarlyStopping(monitor='val_loss', patience=25, restore_best_weights=True),]
    
    
        history = model.fit(
                X_train, y_train, 
                epochs=150, 
                batch_size=64, 
                #validation_split=0.2, 
                validation_data=(X_val, y_val), 
                callbacks=callbacks,
                verbose=0
            )
        test_y = model.predict(x_test.reshape((-1,n_steps_in)))
        test_df.loc[test_df.id==id,'target'] = test_y[0]
        error = mean_squared_error(best_sub[best_sub['id']==id]['target'],test_y[0])
        error_df[id] = round(error,4)
        print(f'linear model {id} VS best sb ERROR = {error}')
        
    except Exception as e:
        error_id.append(id)
        print(f'error id = {id}',e)
    break
    pass

训练很抖:多加点归一化吧; 

import matplotlib.pyplot as plt
plot_loss(history,warehouse=id)

 3 GRU

GRU 模块要比LSTM稳定的多;

def create_model(input_shape, output_length,lr=1e-3, warehouse="None"):

    model = Sequential()
    model.add(Input(shape=input_shape))
    
    model.add(Conv1D(filters=32, kernel_size=3, activation='relu', padding='same', kernel_regularizer=l2()))
    model.add(BatchNormalization())
    model.add(Dropout(0.4))
    model.add(GRU(units=64, activation='relu', return_sequences=False))
    model.add(Dense(output_length))
    #model.compile(loss=MeanSquaredError(), optimizer=tf.keras.optimizers.RMSprop(learning_rate=lr, rho=0.9))
    model.compile(loss=MeanSquaredError(), optimizer=tf.keras.optimizers.RMSprop(lr=lr))

                  
    return model

 4  TCN

模型:收敛的也很快!运行起来很流畅!

def create_model(input_shape, output_length,lr=1e-3, warehouse="None"):

    model = Sequential()
    model.add(Input(shape=input_shape))
    
    model.add(Conv1D(filters=32, kernel_size=3, activation='relu', padding='causal',dilation_rate=1, kernel_regularizer=l2()))
    model.add(BatchNormalization())
    model.add(Dropout(0.4))

    model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding='causal',dilation_rate=1, kernel_regularizer=l2()))
    model.add(BatchNormalization())
    model.add(Dropout(0.4))

    model.add(Conv1D(filters=32, kernel_size=2, activation='relu', padding='causal',dilation_rate=1, kernel_regularizer=l2()))
    model.add(BatchNormalization())
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(output_length))
    #model.compile(loss=MeanSquaredError(), optimizer=tf.keras.optimizers.RMSprop(learning_rate=lr, rho=0.9))
    model.compile(loss=MeanSquaredError(), optimizer=tf.keras.optimizers.RMSprop(lr=lr))

                  
    return model

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1972824.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

从实现第一个ArkTs应用开始入门

前言 新建了个鸿蒙学习项目&#xff0c;后续持续学习会把代码放到这里来&#xff1a;鸿蒙项目仓库学习实践版 基本概念 从HarmonyOS NEXT Developer Preview1(API 11)版本开始&#xff0c;HarmonyOS SDK以Kit维度提供了六大领域的开放能力&#xff0c; 包括&#xff1a; 应用…

800G FR4解决方案:高速数据传输的理想选择

随着业务规模的扩大&#xff0c;数据中心面临着越来越多的数据处理需求。虚拟化、物联网&#xff08;IoT&#xff09;和云计算等数据密集型应用推动了数据中心流量的不断增长&#xff0c;从而提升了对大容量800G解决方案的市场需求。因此&#xff0c;新建800G数据中心&#xff…

marker - PDF 转 markdown

文章目录 一、关于 marker特点它是如何工作的例子性能商业用途托管API限制 二、安装Optional: OCRMyPDF 三、用法1、配置转换单个文件转换多个文件在多个GPU上转换多个文件 三、故障排除四、有用的设置五、基准测试速度精度吞吐量 六、运行自己的基准测试七、感谢 一、关于 mar…

C++初学(9)

9.1、结构简介 虽然数组能够和存储多个元素&#xff0c;但所有元素必须相同&#xff0c;也就是说&#xff0c;同一个数组不能既存放int类型也存放float类型&#xff0c;而C的结构可以满足要求。结构是一种比数组更灵活的数据格式&#xff0c;因为同一个结构可以存储多种类型的…

防御笔记第九天(持续更新)

注意&#xff1a;攻击可能只是一个点&#xff0c;而防御需要全方面进行。 1.IAE引擎 2.DPI DPI ----深度包检测 --- 针对完整的数据包&#xff0c;进行内容的识别和检测 3.基于特征字的检测技术 4&#xff0c;基于应用网关的检测技术 基于应用网关的检测技术 --- 有些应用控…

数据库方言

数据库方言&#xff0c;也称数据库领域特定语言&#xff08;DSL&#xff09;&#xff0c;是针对特定数据库系统的专有扩展或子集&#xff0c;它允许用户在特定环境内使用更高效、更简洁的查询语句。 关键字&#xff08;Keywords&#xff09; 关键字是数据库方言中预定义的单词&…

Windows 安装Redis7.4版本图文教程

本章教程&#xff0c;主要介绍如何在Windows上安装Redis7.4版本的Redis&#xff0c;并以服务方式实现开机自启动。 1、下载安装包 通过百度网盘分享的文件&#xff1a;Redis-7.4.0-Windows-x64-cygwin-with-Service.zip 链接&#xff1a;https://pan.baidu.com/s/1NFGXrCwumDzl…

【计算机毕业设计】703学生考勤管理系统

&#x1f64a;作者简介&#xff1a;拥有多年开发工作经验&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的项目或者毕业设计。 代码可以私聊博主获取。&#x1f339;赠送计算机毕业设计600个选题excel文件&#xff0c;帮助大学选题。赠送开题报告模板&#xff…

软件测试 -- 黑盒、灰盒、白盒测试,冒烟测试、回归测试

软件测试目的&#xff1a;查找软件中缺陷&#xff08;bug&#xff09;&#xff0c;保障软件质量。

IPV6公网暴露下的OPENWRT防火墙安全设置(只允许访问局域网中指定服务器指定端口其余拒绝)

首先是防火墙的常规配置和区域配置 标的有点乱但是选项含义都做了解释&#xff0c;看不懂可以直接按图抄作业。 其次是对需要访问的端口做访问放通 情况1 DDNS位于openwrt网关上&#xff0c;外网访问openwrt&#xff0c;通过端口转发访问内部服务器。此情况需要设置端口转发。 …

6-4 填充和步幅

在前面的例子 图6.2.1中&#xff0c;输入的高度和宽度都为 3 3 3&#xff0c;卷积核的高度和宽度都为 2 2 2&#xff0c;生成的输出表征的维数为 2 2 2\times 2 22。 正如我们在 6-2节中所概括的那样&#xff0c;假设输入形状为 n h n w n_{h}\times n_{w} nh​nw​&#xff…

大象机器人水星MercuryX1轮式人形机器人基于物体标记建模的键盘点按操作!

引言 在现代科技的推动下&#xff0c;机器人在日常生活和工作场景中的应用越来越广泛。本文将介绍MercuryX1&#xff0c;这款先进的机器人如何通过其手臂末端的摄像头识别并确定键盘的键位&#xff0c;从而进行精确的打字操作。通过这一案例&#xff0c;我们将展示MercuryX1在自…

xcode使用

1. 界面 1.1. Build Settings,Build Phases和Build Rules三个设置项 Build Settings(编译设置): 每个选项由标题(Title)和定义(Definition)组成。这里主要定义了Xcode在编译项目时的一些具体配置 Build Phases(编译资源):用于指定编译过程中项目所链接的原文件,依赖对象,库…

安装 electron 报错解决

1. 报错 大概率由镜像问题导致 2. 解决 2.1 打开 npm 配置 npm config edit 2.2 添加配置 registryhttps://registry.npmmirror.comelectron_mirrorhttps://cdn.npmmirror.com/binaries/electron/electron_builder_binaries_mirrorhttps://npmmirror.com/mirrors/electron…

Tensor安装和测试

1: 打开git官方 https://github.com/NVIDIA/TensorRT 2: 下载得到&#xff1a;TensorRT-10.2.0.19.Linux.x86_64-gnu.cuda-11.8.tar.gz 3: 下载后配置环境变量&#xff0c;上面地址记得改成真实地址。 4: 如果想python使用tensorrt&#xff0c;那么 解压后目录&#xff0c…

深入理解单元测试与JUnit:从基础概念到实践操作

文章目录 前言一、单元测试是什么&#xff1f;单元测试的特点单元测试的好处 二、junit是什么&#xff1f;三、操作步骤1.junit安装2.maven新建项目3. 新建java文件4. 生成测试类5. 编写测试方法6. 测试结果 总结 前言 随着软件开发行业的不断发展&#xff0c;测试的重要性日益…

清华和字节联合推出的视频理解大模型video-SALMONN(ICML 2024)

video-SALMONN: Speech-Enhanced Audio-Visual Large Language Models 论文信息 paper&#xff1a;https://arxiv.org/abs/2406.15704 code&#xff1a;https://github.com/bytedance/SALMONN/ AI也会「刷抖音」&#xff01;清华领衔发布短视频全模态理解新模型 | ICML 2024 …

Python数值计算(10)——PPoly对象

在scipy中&#xff0c;scipy.interpolate下还有一个PPoly的类&#xff0c;用于表示插值多项式&#xff0c;很多插值算法的结果&#xff0c;都以该类的实例返回&#xff0c;因此有必要了解该类的使用方法。要使用该类&#xff0c;首先要引入相应的模块&#xff1a; from scipy.…

基于docker的 nacos安装部署

一、拉取镜像 拉取nacos官方镜像&#xff0c;这里使用默认命令 docker pull nacos/nacos-server二、创建挂载目录 创建本地的映射文件application.properties mkdir -p /home/docker/nacos/conf /home/docker/nacos/logstouch /home/docker/nacos/conf/application.propert…

举个栗子!Tableau 技巧(280):创建点象限图( Dot Quadrant Chart )

之前分享过 &#x1f330; &#xff1a;四象限图 和 葡萄干布丁图。今天&#xff0c;我们将两者的呈现方式结合起来&#xff0c;创建如下的点象限图( Dot Quadrant Chart )&#xff0c;可以帮助数据粉在有限的看板区域内展示更多的数据信息。 那么&#xff0c;如何在 Tableau 中…