时间序列算法总结

一. 使用场景

  1. 趋势识别:帮助我们识别数据中的长期趋势和季节性变化,为预测未来趋势提供依据。
  2. 异常检测:能够检测数据中的异常值和异常模式,及时发现潜在问题。
  3. 决策支持:为政策制定和战略规划提供数据驱动的洞察,帮助优化决策过程。

二. 常见时间序列算法归纳总结

1. 自回归 (AR, Autoregressive Model)

自回归模型假设当前值 是过去若干时刻值的线性组合。

原理

模型利用前 p 个时间点的数据预测当前时间点的数据。

核心公式

X t = c + ∑ i = 1 P ϕ i X t − i + ϵ t X_t = c + \sum_{i=1}^{P}\phi_i X_{t-i} + \epsilon_t Xt=c+i=1PϕiXti+ϵt

其中:

  • c c c 是常数项,
  • ϕ i \phi_i ϕi 是自回归系数,
  • ϵ t \epsilon_t ϵt 是白噪声误差。
    自回归模型的推导可以通过对时间序列数据进行线性回归得到,即:
    X t = Φ X t − 1 + e t \mathbf{X}_t = \boldsymbol{\Phi} \mathbf{X}_{t-1} + \mathbf{e}_t Xt=ΦXt1+et 使用最小二乘法求解系数 ϕ i \phi_i ϕi

案例

案例中,使用了股票价格数据,展示如何拟合AR模型并进行预测,并生成两个以上的数据分析图形。

使用一个股票价格的时间序列数据,首先对数据进行预处理,然后拟合一个自回归模型,最后生成几个图形,包括时间序列图、ACF图、PACF图和预测图。

使用 yfinance 库来获取股票价格数据。

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.ar_model import AutoReg
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 下载数据
ticker = 'AAPL'  # 以苹果公司股票为例
start_date = '2020-01-01'
end_date = '2023-01-01'
data = yf.download(ticker, start=start_date, end=end_date)
close_prices = data['Close']

# 绘制时间序列图
plt.figure(figsize=(14, 7))
plt.plot(close_prices, label='Close Price')
plt.title('Apple Stock Close Prices')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()

# ACF和PACF图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10))
plot_acf(close_prices, ax=ax1, lags=50)
plot_pacf(close_prices, ax=ax2, lags=50)
plt.show()

# 拟合自回归模型
lags = 30
model = AutoReg(close_prices, lags=lags)
model_fit = model.fit()

# 模型预测
pred_start = len(close_prices)
pred_end = pred_start + 50
predictions = model_fit.predict(start=pred_start, end=pred_end)

# 绘制预测结果
plt.figure(figsize=(14, 7))
plt.plot(close_prices, label='Observed')
plt.plot(predictions, label='Forecast', linestyle='--')
plt.title('Apple Stock Close Price Forecast')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()

  1. 时间序列图:展示了苹果公司股票的每日收盘价。
  2. ACF和PACF图:用于检查时间序列的自相关性和部分自相关性,帮助确定AR模型的阶数。
  3. 预测图:展示了拟合AR模型后的未来50天的股票价格预测

2. 移动平均 (MA, Moving Average Model)

移动平均模型假设当前值 是过去若干时刻误差的线性组合。

原理

模型利用前 q 个时间点的误差预测当前时间点的数据。

核心公式

X t = μ + ϵ t + ∑ i = 1 q θ i ϵ t − i X_t = \mu + \epsilon_t + \sum_{i=1}^{q}\theta_i\epsilon_{t-i} Xt=μ+ϵt+i=1qθiϵti

其中:

  • X t X_t Xt 是时间 t 的观测值。
  • μ \mu μ 是均值参数。
  • ϵ t \epsilon_t ϵt 是误差项,通常假设其服从正态分布。
  • θ i \theta_i θi 是移动平均参数。
  • q q q 是移动平均项的数量。

案例

假设我们有一个月度的销售数据,该数据包含一些季节性和随机波动。我们将使用移动平均模型来平滑数据,并比较平滑后的数据与原始数据。此外,我们还将计算并绘制残差。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 生成模拟的时间序列数据
np.random.seed(42)
n_periods = 120
date_range = pd.date_range(start='2010-01', periods=n_periods, freq='M')
seasonal_pattern = np.sin(2 * np.pi * date_range.month / 12)
random_noise = np.random.normal(scale=0.5, size=n_periods)
sales = 10 + seasonal_pattern + random_noise

# 创建数据框
data = pd.DataFrame({'Date': date_range, 'Sales': sales})
data.set_index('Date', inplace=True)

# 绘制原始数据
plt.figure(figsize=(14, 6))
plt.plot(data.index, data['Sales'], label='Original Sales Data')
plt.title('Monthly Sales Data')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.show()

# 使用移动平均模型进行平滑
window_size = 12
data['Sales_MA'] = data['Sales'].rolling(window=window_size).mean()

# 绘制平滑后的数据
plt.figure(figsize=(14, 6))
plt.plot(data.index, data['Sales'], label='Original Sales Data')
plt.plot(data.index, data['Sales_MA'], label=f'{window_size}-month Moving Average', color='red')
plt.title('Monthly Sales Data with Moving Average')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.show()

# 计算残差
data['Residual'] = data['Sales'] - data['Sales_MA']

# 绘制残差
plt.figure(figsize=(14, 6))
plt.plot(data.index, data['Residual'], label='Residuals', color='green')
plt.title('Residuals from Moving Average Model')
plt.xlabel('Date')
plt.ylabel('Residual')
plt.legend()
plt.show()

# 绘制自相关图和偏自相关图
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
plot_acf(data['Residual'].dropna(), ax=axes[0], lags=40)
plot_pacf(data['Residual'].dropna(), ax=axes[1], lags=40)
axes[0].set_title('ACF of Residuals')
axes[1].set_title('PACF of Residuals')
plt.show()
  1. 生成时间序列数据:使用正弦函数生成季节性模式,并添加随机噪声。
  2. 绘制原始数据:绘制原始的月度销售数据。
  3. 计算移动平均:使用滚动窗口方法计算移动平均。
  4. 绘制平滑后的数据:比较平滑后的数据与原始数据。
  5. 计算并绘制残差:计算残差并绘制残差时间序列。
  6. 绘制自相关图和偏自相关图:分析残差的自相关性和偏自相关性。

3. 自回归滑动平均 (ARMA, Autoregressive Moving Average Model)

ARMA模型结合了自回归和移动平均模型。

原理

模型利用前 p 个时间点的数据和前 q 个时间点的误差预测当前时间点的数据。

核心公式

X t = c + ∑ i = 1 p ϕ i X t − i + ϵ t + ∑ j = 1 q θ j ϵ t − j X_t = c + \sum_{i=1}^p \phi_i X_{t-i} + \epsilon_t + \sum_{j=1}^q \theta_j \epsilon_{t-j} Xt=c+i=1pϕiXti+ϵt+j=1qθjϵtj

其中:

  • X t X_t Xt:在时间 t t t上的观察值;
  • c c c:常数项;
  • ϕ i \phi_i ϕi:自回归系数;
  • θ j \theta_j θj:移动平均系数;
  • ϵ t \epsilon_t ϵt:误差项,通常假定它是一个零均值的随机过程;

ARMA模型是将自回归模型和移动平均模型结合,利用两者的推导方法,对两个模型的参数进行联合估计。

案例

代码中,我们使用Python中的 statsmodels 库来进行ARMA建模和分析,并使用 matplotlib 来绘制图形。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 生成示例时间序列数据
np.random.seed(42)
n = 200
ar_params = np.array([0.75, -0.25])
ma_params = np.array([0.65, 0.35])
ar = np.r_[1, -ar_params]  # add zero-lag and negate
ma = np.r_[1, ma_params]   # add zero-lag
y = np.random.normal(size=n)
x = np.convolve(y, ma)[:n] + np.random.normal(size=n)
time_series = pd.Series(x)

# 绘制原始时间序列数据
plt.figure(figsize=(12, 6))
plt.plot(time_series, label='Original Time Series')
plt.title('Original Time Series')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.show()

# 绘制自相关图 (ACF) 和偏自相关图 (PACF)
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
plot_acf(time_series, ax=axes[0], title='Autocorrelation Function (ACF)')
plot_pacf(time_series, ax=axes[1], title='Partial Autocorrelation Function (PACF)')
plt.show()

# 建立并拟合ARMA模型
model = ARIMA(time_series, order=(2, 0, 2))
arma_result = model.fit()

# 打印模型摘要
print(arma_result.summary())

# 绘制拟合后的时间序列和残差图
plt.figure(figsize=(12, 6))
plt.plot(time_series, label='Original Time Series')
plt.plot(arma_result.fittedvalues, color='red', label='Fitted Values')
plt.title('Original and Fitted Time Series')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.show()

# 绘制残差图
residuals = arma_result.resid
plt.figure(figsize=(12, 6))
plt.plot(residuals, label='Residuals')
plt.title('Residuals of ARMA Model')
plt.xlabel('Time')
plt.ylabel('Residual')
plt.legend()
plt.show()
  1. 生成示例时间序列数据:我们生成一个包含200个数据点的时间序列,使用自回归参数 ar_params 和移动平均参数 ma_params。
  2. 绘制原始时间序列数据:使用 matplotlib 绘制原始时间序列数据。
  3. 绘制ACF和PACF图:使用 statsmodels 库的 plot_acf 和 plot_pacf 函数绘制自相关函数 (ACF) 和偏自相关函数 (PACF) 图。
  4. 建立并拟合ARMA模型:使用 statsmodels 库中的 ARIMA 函数建立ARMA模型并进行拟合。
  5. 打印模型摘要:打印拟合结果的摘要,包含模型参数和统计信息。
  6. 绘制拟合后的时间序列和残差图:绘制原始时间序列与模型拟合值的对比图,以及模型残差图

4. 自回归积分滑动平均 (ARIMA, Autoregressive Integrated Moving Average Model)

ARIMA模型扩展了ARMA模型,适用于非平稳时间序列。

原理

模型通过对数据进行差分处理,使其平稳,然后再应用ARMA模型。

核心公式

( 1 − B ) d X t = c + ∑ i = 1 p ϕ i ( 1 − B ) i X t − i + ϵ t + ∑ j = 1 q θ j ( 1 − B ) j ϵ t − j (1−B) ^d X_t =c + \sum_{i=1}^{p} \phi_i (1 - B)^i X_{t-i} + \epsilon_t + \sum_{j=1}^{q} \theta_j (1 - B)^j \epsilon_{t-j} (1B)dXt=c+i=1pϕi(1B)iXti+ϵt+j=1qθj(1B)jϵtj

其中:

  • B B B 是滞后算子。
  • d d d 是差分次数。

通过对原始序列 X t X_t Xt 进行 d d d 次差分,使其变为平稳序列 Y t Y_t Yt,然后对平稳序列应用ARMA模型进行参数估计。

案例

创建一个模拟的时间序列数据,应用 ARIMA 模型进行建模和预测,并画出原始数据、ACF (自相关函数) 图和预测结果图。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 1. 创建模拟时间序列数据
np.random.seed(42)
n = 200
time = np.arange(n)
data = np.sin(0.1 * time) + 0.5 * np.random.randn(n)

# 转换为 Pandas DataFrame
df = pd.DataFrame(data, columns=['Value'])
df.index = pd.date_range(start='2020-01-01', periods=n, freq='D')

# 2. 绘制原始时间序列图
plt.figure(figsize=(14, 7))
plt.subplot(3, 1, 1)
plt.plot(df.index, df['Value'], label='Original Data')
plt.title('Original Time Series')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()

# 3. 绘制自相关函数 (ACF) 和偏自相关函数 (PACF) 图
plt.subplot(3, 1, 2)
plot_acf(df['Value'], ax=plt.gca(), lags=30)
plt.title('ACF of Time Series')

plt.subplot(3, 1, 3)
plot_pacf(df['Value'], ax=plt.gca(), lags=30)
plt.title('PACF of Time Series')

plt.tight_layout()
plt.show()

# 4. 应用 ARIMA 模型
from statsmodels.tsa.arima.model import ARIMA

# 拟合 ARIMA 模型
model = ARIMA(df['Value'], order=(5, 0, 0))  # (p, d, q) 这里 d=0 是因为数据没有差分
model_fit = model.fit()

# 打印模型摘要
print(model_fit.summary())

# 5. 预测未来 20 个时间点
forecast = model_fit.forecast(steps=20)

# 创建预测数据的时间序列
forecast_index = pd.date_range(start=df.index[-1] + pd.Timedelta(days=1), periods=20, freq='D')
forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=['Forecast'])

# 6. 绘制预测结果图
plt.figure(figsize=(14, 7))
plt.plot(df.index, df['Value'], label='Original Data')
plt.plot(forecast_df.index, forecast_df['Forecast'], color='red', linestyle='--', label='Forecast')
plt.title('Forecast using ARIMA Model')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

5. 季节性自回归积分滑动平均 (SARIMA, Seasonal ARIMA)

SARIMA模型扩展了ARIMA模型,适用于季节性时间序列。

原理

模型结合了季节性自回归、季节性差分和季节性移动平均成分。

核心公式

( 1 − B ) d ( 1 − B s ) D X t = c + ∑ i = 1 p ϕ i ( 1 − B ) i ( 1 − B s ) I X t − i + ϵ t + ∑ j = 1 q θ j ( 1 − B ) j ( 1 − B s ) J ϵ t − j (1-B)^{d}(1-B^{s})^{D}X_{t}=c+\sum\limits _{i=1}^{p}\phi_{i}(1-B)^{i}(1-B^{s})^{I}X_{t-i}+\epsilon_{t}+\sum\limits _{j=1}^{q}\theta_{j}(1-B)^{j}(1-B^{s})^{J}\epsilon_{t-j} (1B)d(1Bs)DXt=c+i=1pϕi(1B)i(1Bs)IXti+ϵt+j=1qθj(1B)j(1Bs)Jϵtj

其中:

  • s s s 是季节周期。
  • D D D 是季节差分次数。

案例

以下是一个关于月度航空乘客数量数据的案例分析,该数据集包含1949年1月到1960年12月之间的月度航空乘客数量。我们使用SARIMA模型对该数据进行建模,并绘制相关的图形进行数据分析。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.stattools import adfuller, acf, pacf

# 加载航空乘客数据集
file = 'airline-passengers.csv'
data = pd.read_csv(file, index_col='Month', parse_dates=True)
data.index.freq = 'MS'

# 绘制原始数据
plt.figure(figsize=(10, 6))
plt.plot(data, label='Monthly Airline Passengers')
plt.title('Monthly Airline Passengers from 1949 to 1960')
plt.xlabel('Date')
plt.ylabel('Number of Passengers')
plt.legend()
plt.show()

# 进行ADF检验
adf_result = adfuller(data['Passengers'])
print(f'ADF Statistic: {adf_result[0]}')
print(f'p-value: {adf_result[1]}')

# 绘制ACF和PACF图
lag_acf = acf(data['Passengers'], nlags=40)
lag_pacf = pacf(data['Passengers'], nlags=40, method='ols')

plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.stem(range(len(lag_acf)), lag_acf, linefmt='b-', markerfmt='bo', basefmt='r-')
plt.axhline(y=0, linestyle='--', color='gray')
plt.axhline(y=-1.96/np.sqrt(len(data)), linestyle='--', color='gray')
plt.axhline(y=1.96/np.sqrt(len(data)), linestyle='--', color='gray')
plt.title('Autocorrelation Function')

plt.subplot(122)
plt.stem(range(len(lag_pacf)), lag_pacf, linefmt='b-', markerfmt='bo', basefmt='r-')
plt.axhline(y=0, linestyle='--', color='gray')
plt.axhline(y=-1.96/np.sqrt(len(data)), linestyle='--', color='gray')
plt.axhline(y=1.96/np.sqrt(len(data)), linestyle='--', color='gray')
plt.title('Partial Autocorrelation Function')
plt.tight_layout()
plt.show()

# 拟合SARIMA模型
model = SARIMAX(data['Passengers'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
results = model.fit()

# 打印模型总结
print(results.summary())

# 绘制预测结果
data['forecast'] = results.predict(start=120, end=144, dynamic=True)
plt.figure(figsize=(10, 6))
plt.plot(data['Passengers'], label='Actual Passengers')
plt.plot(data['forecast'], label='Forecasted Passengers', color='red')
plt.title('Actual vs Forecasted Passengers')
plt.xlabel('Date')
plt.ylabel('Number of Passengers')
plt.legend()
plt.show()

6. 向量自回归 (VAR, Vector Autoregression)

VAR模型是自回归模型的多变量扩展,适用于多变量时间序列。

原理

模型利用多个时间序列的历史数据进行联合预测。

核心公式

Y t = c + ∑ i = 1 P A i Y t − i + ε t Y_{t}=c+\sum\limits _{i=1}^{P}A_{i}Y_{t-i}+\varepsilon_{t} Yt=c+i=1PAiYti+εt

其中:

  • Y t Y_{t} Yt是多变量时间序列向量
  • A i A_{i} Ai是多变量时间序列向量

案例

使用美国经济时间序列数据集,该数据集包括了消费、收入和投资的月度数据。这个数据集可以在 statsmodels 库中找到。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.api import VAR

# 加载数据集
from statsmodels.datasets.macrodata import load_pandas
data = load_pandas().data

# 选择感兴趣的变量
df = data[['realgdp', 'realcons', 'realinv']]

# 设置时间索引
dates = pd.date_range(start='1959Q1', periods=len(df), freq='Q')
df.index = dates

# 绘制原始数据的时间序列图
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))
df.plot(subplots=True, ax=axes)
plt.tight_layout()
plt.show()

# 计算一阶差分
df_diff = df.diff().dropna()

# 绘制差分后的数据
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))
df_diff.plot(subplots=True, ax=axes)
plt.tight_layout()
plt.show()

# 构建并训练VAR模型
model = VAR(df_diff)
results = model.fit(maxlags=15, ic='aic')

# 打印模型摘要
print(results.summary())

# 绘制模型残差的时间序列图
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))
for i, column in enumerate(df_diff.columns):
    axes[i].plot(results.resid[:, i])
    axes[i].set_title(f'Residuals of {column}')
plt.tight_layout()
plt.show()

# 预测未来的时间序列
lag_order = results.k_ar
forecast = results.forecast(df_diff.values[-lag_order:], steps=10)
forecast_index = pd.date_range(start=df.index[-1], periods=10, freq='Q')
forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=df.columns)

# 绘制预测结果
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))
for i, column in enumerate(df.columns):
    axes[i].plot(df.index, df[column], label='Original')
    axes[i].plot(forecast_df.index, forecast_df[column], label='Forecast')
    axes[i].set_title(f'{column} - Original vs Forecast')
    axes[i].legend()
plt.tight_layout()
plt.show()

7. 长短期记忆网络 (LSTM, Long Short-Term Memory)

LSTM是一种特殊的递归神经网络(RNN),适用于捕捉长时间依赖关系。

原理

LSTM通过引入记忆单元和门控机制,有效解决了RNN的梯度消失问题。

核心公式

  1. 遗忘门计算:

f t = σ ( W f ⋅ [ h t − 1 , x t ] + U f ⋅ h t − 1 + b f ) f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + U_f \cdot h_{t-1} + b_f) ft=σ(Wf[ht1,xt]+Ufht1+bf)

  1. 输入门计算:

i t = σ ( W i ⋅ [ h t − 1 , x t ] + U i ⋅ h t − 1 + b i )   i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + U_i \cdot h_{t-1} + b_i) \ it=σ(Wi[ht1,xt]+Uiht1+bi) 

  1. 候选记忆单元内容计算:

g t = t a n h ( W g ⋅ [ h t − 1 , x t ] + U g ⋅ h t − 1 + b g )   g_t = tanh(W_g \cdot [h_{t-1}, x_t] + U_g \cdot h_{t-1} + b_g) \ gt=tanh(Wg[ht1,xt]+Ught1+bg) 

  1. 更新记忆单元内容:

c t = f t ⊙ c t − 1 + i t ⊙ g t   c_t = f_t \odot c_{t-1} + i_t \odot g_t \ ct=ftct1+itgt 

  1. 输出门计算:
    [ o t = σ ( W o ⋅ [ h t − 1 , x t ] + U o ⋅ h t − 1 + b o ) [ o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + U_o \cdot h_{t-1} + b_o) [ot=σ(Wo[ht1,xt]+Uoht1+bo)

  2. 计算隐藏状态:
    [ h t = o t ⊙ t a n h ( c t ) [ h_t = o_t \odot tanh(c_t) [ht=ottanh(ct)

案例

使用Keras来构建和训练LSTM模型,并使用Matplotlib来绘制数据分析图形。我们使用一个简单的模拟时间序列数据来演示LSTM模型的应用。该数据代表某种时间序列,例如每日温度变化。

import numpy as np
import matplotlib.pyplot as plt

# 生成模拟时间序列数据
np.random.seed(0)
time_steps = 100
data = np.sin(np.linspace(0, 10 * np.pi, time_steps)) + np.random.normal(0, 0.5, time_steps)

# 绘制原始数据
plt.figure(figsize=(14, 6))
plt.plot(data, label='Original Data')
plt.title('Simulated Time Series Data')
plt.xlabel('Time Step')
plt.ylabel('Value')
plt.legend()
plt.show()

# 构建LSTM模型
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# 准备训练数据
def create_dataset(data, look_back=1):
    X, y = [], []
    for i in range(len(data) - look_back):
        X.append(data[i:(i + look_back)])
        y.append(data[i + look_back])
    return np.array(X), np.array(y)

look_back = 3
X, y = create_dataset(data, look_back)
X = X.reshape(X.shape[0], X.shape[1], 1)  # LSTM 需要 3D 输入

# 构建 LSTM 模型
model = Sequential()
model.add(LSTM(50, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')

# 训练模型
model.fit(X, y, epochs=100, batch_size=1, verbose=2)

# 预测并绘制结果
train_predict = model.predict(X)
train_predict_plot = np.empty_like(data)
train_predict_plot[:] = np.nan
train_predict_plot[look_back:len(train_predict) + look_back] = train_predict.flatten()

# 绘制原始数据与预测数据对比图
plt.figure(figsize=(14, 6))
plt.plot(data, label='Original Data')
plt.plot(train_predict_plot, label='LSTM Prediction')
plt.title('LSTM Prediction vs Original Data')
plt.xlabel('Time Step')
plt.ylabel('Value')
plt.legend()
plt.show()

# 绘制损失函数变化图
history = model.history
loss = history.history['loss']

plt.figure(figsize=(14, 6))
plt.plot(loss, label='Training Loss')
plt.title('Model Training Loss Over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()

🚀 获取更多详细资料可点击链接进群领取,谢谢支持👇

点击免费领取更多资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值