示例代码

import json
import time
import datetime
import requests as req
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense def date2ts(date_str, layout="%Y-%m-%d %H:%M:%S"):
date_struct=time.strptime(date_str, layout)
return int(time.mktime(date_struct)) # 画图之前转换成北京时间
def to_beijing_time(datetime_index):
return datetime_index.tz_localize('UTC').tz_convert('Asia/Shanghai') # 载入原始数据
with open("dataset_2014.json", "r") as rf:
c = rf.read()
d = json.loads(c)
data = {}
for i in range(288*3):
ts = date2ts(d['data']['datetime'][i])
data[ts] = d['data']['count'][i] # 将字典转换为 DataFrame
df = pd.DataFrame(list(data.items()), columns=['timestamp', 'value'])
df['datetime'] = pd.to_datetime(df['timestamp'], unit='s')
df.set_index('datetime', inplace=True)
df.drop('timestamp', axis=1, inplace=True) # 确保数据按时间顺序排序
df = df.sort_index() # 重新采样为 5 分钟间隔,填充缺失值
df = df.resample('5T').mean()
df.interpolate(method='linear', inplace=True) # 数据标准化
scaler = MinMaxScaler(feature_range=(0, 1))
df_scaled = scaler.fit_transform(df)
print("Original Data:\n", df)
print("Scaled Data:\n", df_scaled) # 创建数据集函数
def create_dataset(data, time_step=1):
X, y = [], []
for i in range(len(data) - time_step - 1):
X.append(data[i:(i + time_step), 0])
y.append(data[i + time_step, 0])
return np.array(X), np.array(y) time_step = 10 # 设定用于输入的时间步长
X, y = create_dataset(df_scaled, time_step) # 拆分训练和测试数据集
train_size = int(len(X) * 0.7)
test_size = len(X) - train_size
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:] # 转换为 LSTM 输入格式
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1) # 构建 LSTM 模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, y_train, batch_size=1, epochs=10) # 预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test) # 反标准化预测结果
train_predict = scaler.inverse_transform(train_predict)
test_predict = scaler.inverse_transform(test_predict) # 反标准化实际值
df_inv_scaled = scaler.inverse_transform(df_scaled)
# print("Inverse Scaled Data:\n", df_inv_scaled) # 创建用于绘制图像的空数组
train_predict_plot = np.empty_like(df_scaled)
train_predict_plot[:, :] = np.nan
train_predict_plot[time_step:len(train_predict) + time_step, :] = train_predict # 计算测试预测结果的起始和结束点
start_point = len(train_predict) + time_step # 设定起始点位置
end_point = start_point + len(test_predict)
test_predict_plot = np.empty_like(df_scaled)
test_predict_plot[:, :] = np.nan
test_predict_plot[start_point:end_point, :] = test_predict[:df_scaled.shape[0] - start_point, :] # 放置到合适位置 # 将时间戳转换回原始时间格式
original = df.index
original_beijing = to_beijing_time(original)
# 创建 figure 绘图
plt.figure(figsize=(15, 6))
plt.title("Timeseries Prediction base on LSTM")
plt.plot(original_beijing, df_inv_scaled, label='True Data') # 确保这里使用适当逆标准化数据
plt.plot(original_beijing, train_predict_plot, label='Train Predict')
plt.plot(original_beijing, test_predict_plot, label='Test Predict')
# 格式化 X 轴,提高可读性
plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=12))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M', tz=original_beijing.tz))
plt.gcf().autofmt_xdate(rotation=45)
plt.xlabel('Datetime')
plt.ylabel('Value')
plt.legend()
plt.show() # # 提取最后3天的数据
# last_three_days_mask = original >= (original.max() - pd.Timedelta(days=3))
# filtered_original = original[last_three_days_mask]
# filtered_df_inv_scaled = df_inv_scaled[last_three_days_mask]
# filtered_train_predict_plot = train_predict_plot[last_three_days_mask]
# filtered_test_predict_plot = test_predict_plot[last_three_days_mask]
# # 转换时间为北京时间
# filtered_original_beijing = to_beijing_time(filtered_original) # plt.figure(figsize=(15, 6))
# plt.title("Timeseries Prediction base on LSTM (last 3 days)")
# plt.plot(filtered_original_beijing, filtered_df_inv_scaled, label='True Data') # 确保这里使用适当逆标准化数据
# plt.plot(filtered_original_beijing, filtered_train_predict_plot, label='Train Predict')
# plt.plot(filtered_original_beijing, filtered_test_predict_plot, label='Test Predict')
# # 格式化 X 轴使用年,并倾斜显示
# plt.gca().xaxis.set_major_locator(mdates.HourLocator(interval=4))
# plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M', tz=filtered_original_beijing.tz))
# plt.gcf().autofmt_xdate(rotation=45)
# plt.xlabel('Datetime')
# plt.ylabel('Value')
# plt.legend()
# plt.show()

效果对比

Timeseries Prediction Demo base on LSTM的更多相关文章

  1. 【转载】Chaotic Time-Series Prediction

    原文地址:https://cn.mathworks.com/help/fuzzy/examples/chaotic-time-series-prediction.html?requestedDomai ...

  2. 用C++调用tensorflow在python下训练好的模型(centos7)

    本文主要参考博客https://blog.csdn.net/luoyexuge/article/details/80399265 [1] bazel安装参考:https://blog.csdn.net ...

  3. 高并发下MySQL出现checking permissions

    在某些数据访问层框架中,会使用show full tables from test like 'demo',来检查数据库的状态.当数据库中表的数量较少时,并没有出现严重的问题.但是当数据库中的表数量多 ...

  4. python中from module import * 的一个陷阱

    from module import *把module中的成员全部导到了当前的global namespace,访问起来就比较方便了.当然,python style一般不建议这么做,因为可能引起nam ...

  5. JavaScript 的性能优化:加载和执行

    随着 Web2.0 技术的不断推广,越来越多的应用使用 javascript 技术在客户端进行处理,从而使 JavaScript 在浏览器中的性能成为开发者所面临的最重要的可用性问题.而这个问题又因 ...

  6. Bootstrap 栅格系统(转载)

    源地址:http://www.cnblogs.com/linjiqin/p/3559800.html Bootstrap 栅格系统 目录1.简介2.栅格选项3.列偏移4.嵌套列5.列排序 1.简介Bo ...

  7. python之import机制

    1. 标准 import        Python 中所有加载到内存的模块都放在 sys.modules .当 import 一个模块时首先会在这个列表中查找是否已经加载了此模块,如果加载了则只是将 ...

  8. c++ 虚析构函数[避免内存泄漏]

    c++  虚析构函数: 虚析构函数(1)虚析构函数即:定义声明析构函数前加virtual 修饰, 如果将基类的析构函数声明为虚析构函数时,由该基类所派生的所有派生类的析构函数也都自动成为虚析构函数. ...

  9. springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)

    这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...

  10. CMake 常用方法

    CMake 允许开发者编写平台无关的 CMakeLists.txt 文件来定制整个编译流程,然后再根据目标用户的平台进一步生成所需的本地化 Makefile 和工程文件,如 Linux 的Makefi ...

随机推荐

  1. wqs 二分

    初看这个东西可能很难理解,我个人也学习了很多遍,然后发现这个直接理解实际上并不难. wqs 二分主要是解决 恰好分成/选 \(k\) 段 这一类 DP 问题的算法.如果不知道形式可以看一下 P4983 ...

  2. C#开发的PDF文件浏览器 - 开源研究系列文章 - 个人小作品

    以前个人的PDF浏览主要是用的Adobe DC的PDF,不过它这个打开速度还是一般.后来安装的极速PDF浏览器,速度还是比较快的了.它这个主要是浏览,然后还能够安装编辑器对PDF文件进行编辑,不过就需 ...

  3. AutoCAD 逆向工程中 Shx 字体文件解析

    数据格式相关的文章 https://wenku.baidu.com/view/8abbfc33eefdc8d376ee32a1.html 代码实现 https://blog.csdn.net/qq_2 ...

  4. 初次使用 Jetbrains Rider 编写 C#(.Net) 代码

    前段时间,Jetbrains公司 公布了 Rider IDE 对非商业用途免费,看到很多业界的朋友都用到这个IDE,今天便下载下来使用一下. 1.界面的差异 Rider的界面跟我前段时间学习调试安卓代 ...

  5. Array, Set, Map知多少?

    Array,Set和Map三个作为Javascript中可迭代的集合数据类型,在编程过程中使用的频率也比较高.针对三种数据类型各自的一些特性,本文的内容将从以下几个方面来上述数据类型做一个总结. 实例 ...

  6. ResizeObserver和IntersectionObserver的详细讲解

    ResizeObserver 的介绍 ResizeObserver 用于异步观察元素的尺寸变化. 如:SVG 元素或文本节点的大小变化.调整浏览器窗口大小.动态改变某个元素的大小时 可以触发相应的回调 ...

  7. 两步实现让antd与IDE和睦相处的处理案例

    导读: Web IDE的开发从来是整个大数据平台开发中非常繁复和笨重的一环,从零搭建一个 Web IDE 通常意味着大量的殚精竭虑和苦思冥想,时间成本更是不可计数.两个UI组件库一起用更是bug的代名 ...

  8. HyperWorks使用六面体和三棱柱单元进行实体网格剖分

    本节将演示如何使用 solid map 功能对一个复杂的几何实体进行网格剖分.剖分的思路是:首先对该实体进行适当的切割,以使其各个部分均处于 mappable 的状态:然后分别对各个子块进行 soli ...

  9. 工程师都喜欢的一款自动生成网格的仿真软件——Hyperworks到底好不好用?

    HyperWorks是一款广泛应用于工程仿真和优化的软件平台,其中包括了许多强大的工具和功能.其中的网格自动生成工具是其重要组成部分之一,对于工程仿真和优化来说具有重要的意义.那么,HyperWork ...

  10. ASP.NET Core Razor Pages 使用 视图(View) 组件

    参考文章地址:为什么要在 ASP.NET Core 中使用视图组件 (telerik.com)为什么使用视图组件而不是分部视图?最大的原因是,在 Razor 页面中插入分部视图时,与调用 View 关 ...