《python深度学习》读书笔记(8) - 深度学习处理时间序列

预测温度

bash 复制代码
wget https://s3.amazonaws.com/keras-datasets/jena_climate_2009_2016.csv.zip
unzip jena_climate_2009_2016.csv.zip

这份数据大概就这样:

准备数据

python 复制代码
import os

import matplotlib.pyplot as plt
import numpy as np

# 这份数据是 每10分钟记录一次 一共是14个物理量
fname = os.path.join("jena_climate_2009_2016.csv")

if __name__ == '__main__':
    with open(fname) as f:
        data = f.read()
    lines = data.split("\n")
    header = lines[0].split(",")
    lines = lines[1:]
    print(header)
    print(len(lines))

    # 舍弃了 date time 这一项
    temperature = np.zeros((len(lines),))
    raw_data = np.zeros((len(lines), len(header) - 1))
    for i, line in enumerate(lines):
        values = [float(x) for x in line.split(",")[1:]]
        temperature[i] = values[1]
        raw_data[i, :] = values[:]
    plt.plot(range(len(temperature)), temperature)
    # 时间跨度为8年的温度曲线变化
    plt.show()
    # 看下前10天的数据
    plt.plot(range(1440), temperature[:1440])
    plt.show()

可以看出来这8年的温度变化曲线是差不多的

再看下头几天的温度曲线

准备训练集

python 复制代码
# 创建3个数据集

# 每6个数据点保存一个,这个很好理解,因为数据是10分钟采集一次 2个10分钟之间 温度的变化其实很小 因此没必要保留这么多数据
sampling_rate = 6
# 给定过去5天的数据
sequence_length = 120
delay = sampling_rate * (sequence_length + 24 - 1)
batch_size = 256

train_dataset = keras.utils.timeseries_dataset_from_array(
    raw_data[:-delay],
    targets=temperature[delay:],
    sampling_rate=sampling_rate,
    sequence_length=sequence_length,
    shuffle=True,
    batch_size=batch_size,
    start_index=0,
    end_index=num_train_samples)

val_dataset = keras.utils.timeseries_dataset_from_array(
    raw_data[:-delay],
    targets=temperature[delay:],
    sampling_rate=sampling_rate,
    sequence_length=sequence_length,
    shuffle=True,
    batch_size=batch_size,
    start_index=num_train_samples,
    end_index=num_train_samples + num_val_samples)

test_dataset = keras.utils.timeseries_dataset_from_array(
    raw_data[:-delay],
    targets=temperature[delay:],
    sampling_rate=sampling_rate,
    sequence_length=sequence_length,
    shuffle=True,
    batch_size=batch_size,
    start_index=num_train_samples + num_val_samples)

可以看下这个输出

bash 复制代码
for samples, targets in train_dataset:
    print("samples shape:", samples.shape)
    print("targets shape:", targets.shape)
    break

sample就是包含256个样本的批量,每个样本是连续120小时的数据, targets 是对应的256个目标温度的数组

注意这里因为shuffle是true。所以sample0 和 sample1 不一定在时间上是连续接近的

基于LSTM的简单模型

有一种专门处理 因果关系和顺序关系都很重要的序列 的神经网络架构 RNN

其中LSTM 是应用范围最广的

这里用LSTM 来处理上述的任务

python 复制代码
inputs = keras.Input(shape=(sequence_length, raw_data.shape[-1]))
x = layers.LSTM(16)(inputs)
outputs = layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
callbacks = [
    keras.callbacks.ModelCheckpoint("jena_lstm.keras", save_best_only=True)
]
model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"])
history = model.fit(train_dataset, epochs=10, validation_data=val_dataset, callbacks=callbacks)

loss = history.history["mae"]
val_loss = history.history["val_mae"]
epochs = range(1, len(loss) + 1)
plt.figure()
plt.plot(epochs, loss, "bo", label="Training MAE")
plt.plot(epochs, val_loss, "b", label="Validation MAE")
plt.title("Training and validation MAE")
plt.legend()
plt.show()

model = keras.models.load_model("jena_lstm.keras")
print(f"Test MAE: {model.evaluate(test_dataset)[1]:.2f}")

测试的mae为

换一种写法

使用dropout正则化 总是需要更长时间才能完全收敛,所以这里 模型的训练书调整为原来的5倍

python 复制代码
inputs = keras.Input(shape=(sequence_length, raw_data.shape[-1]))
# 正则化
x = layers.LSTM(32, recurrent_dropout=0.25)(inputs)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
callbacks = [
    keras.callbacks.ModelCheckpoint("jena_lstm_dropout.keras", save_best_only=True)
]
model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"])
history = model.fit(train_dataset, epochs=50, validation_data=val_dataset, callbacks=callbacks)

总结

如果顺序对数据很重要,特别是对于时间序列数据,那么循环神经网络RNN是一种很适合的方法

相关推荐
星间都市山脉5 小时前
Android16 SystemService.onBootPhase 调用时机
android·java·linux·windows·ubuntu
swithun5 小时前
不用 WebView,我用 Kotlin + Compose Multiplatform 重写 Mermaid,并做了 2048 组对拍
android·开源·kotlin
AI吃大瓜5 小时前
人脸检测和行人检测4:Android实现YOLOv8 YOLO11 YOLO26人脸检测和人体检测(含源码,可实时检测)
android·yolo·人脸检测·人体检测·行人检测·yolo26
与海boy5 小时前
Prompt模版
android·prompt
FlightYe5 小时前
音视频修炼之编码器(一):AVC、HEVC编码器内部
android·linux·c++·音视频
智购科技无人售货机工厂6 小时前
2026自动售货机AI智能体架构:从47个小模型到33.7亿Token的工程实践~YH
android·人工智能·驱动开发·单片机·pandas
嵩风抚7 小时前
一款HK银行APP的业务+技术
android·flutter·react native·html5
00后程序员张9 小时前
怎么用 Egret(白鹭引擎)打包 iOS 应用并上架 App Store?
android·ios·小程序·https·uni-app·iphone·webview
mmsx9 小时前
MapLibre 实战 09|Bug 单写着"地图被风刮走了":一个瓦片源工厂,是三个线上事故换来的
android·前端·开源
一技安身9 小时前
【信创】统信UOS 银河麒麟离线部署Python3.11完整方案
android·java·python3.11