You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于LSTM模型绘制含历史与2023年后预测数据的图表

LSTM模型预测2023年后数据问题

我已构建一个LSTM预测模型,目前该模型可绘制并展示2012年至2023年的实际值与预测值。现在我希望在图表中预测并展示2023年及以后的预测值,但在此环节遇到了问题。以下是我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# Step 1: Prepare the data
data = pd.read_csv('bank_data.csv')  # Replace 'bank_data.csv' with your file name or data source
# Preprocess the data if necessary (e.g., handle missing values, scale the data)

# Convert the 'Date End' column to datetime with the correct format
data['Date'] = pd.to_datetime(data['Date End'], format='%m/%d/%Y')
data = data[['Date', 'Assets']]  # Keep only the necessary columns

# Sort the data by the 'Date' column in ascending order
data.sort_values('Date', inplace=True)
data.reset_index(drop=True, inplace=True)

# Set the 'Date' column as the index
data.set_index('Date', inplace=True)

# Split the data into train and test sets
train_data = data.loc['2012-01-01':'2022-12-31']
test_data = data.loc['2012-01-01':'2024-12-31']

# Prepare the input features and target variable
def create_sequences(data, seq_length):
    X = []
    y = []
    for i in range(len(data) - seq_length):
        X.append(data[i:i+seq_length])
        y.append(data[i+seq_length])
    return np.array(X), np.array(y)

# Scale the data using MinMaxScaler
scaler = MinMaxScaler()
train_scaled = scaler.fit_transform(train_data)
test_scaled = scaler.transform(test_data)

seq_length = 4  # Adjust the sequence length as per your requirements
X_train, y_train = create_sequences(train_scaled, seq_length)
X_test, y_test = create_sequences(test_scaled, seq_length)

# Step 2: Build the LSTM model
model = Sequential()
model.add(LSTM(units=64, activation='relu', input_shape=(seq_length, 1)))
model.add(Dense(units=1))

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Step 3: Train the LSTM model
model.fit(X_train, y_train, epochs=50, batch_size=32)

# Step 4: Generate predictions
predicted_train = model.predict(X_train)
predicted_test = model.predict(X_test)

# Inverse transform the scaled predictions
predicted_train = scaler.inverse_transform(predicted_train)
predicted_test = scaler.inverse_transform(predicted_test)

# Pad the predicted values to match the length of the test data
padding = np.zeros((seq_length, 1))
predicted_test = np.concatenate((padding, predicted_test))

# Extend the test data to include the period from 2024 to 2030
extended_test_data = data.loc['2012-01-01':'2030-12-31']

# Prepare the input features and target variable for the extended test data
X_extended_test, y_extended_test = create_sequences(scaler.transform(extended_test_data), seq_length)

# Generate predictions for the extended test data
predicted_extended_test = model.predict(X_extended_test)

# Inverse transform the scaled predictions for the extended test data
predicted_extended_test = scaler.inverse_transform(predicted_extended_test)

# Pad the predicted values to match the length of the extended test data
padding = np.zeros((len(extended_test_data) - len(test_data) + seq_length, 1))
predicted_extended_test = np.concatenate((padding, predicted_extended_test))

#Evaluating model
# Inverse transform the scaled predictions for the test data
predicted_test = scaler.inverse_transform(predicted_test)

# Calculate Mean Squared Error (MSE) and Root Mean Squared Error (RMSE) for the test data
mse = np.mean((test_data['Assets'].values - predicted_test.flatten())**2)
rmse = np.sqrt(mse)

print("Mean Squared Error (MSE):", mse)
print("Root Mean Squared Error (RMSE):", rmse)


# Step 5: Plot the graph
plt.figure(figsize=(10, 6))
plt.plot(train_data.index, train_data['Assets'], color='blue', label='Historical Data (2012-2023)')
plt.plot(extended_test_data.index, predicted_extended_test, color='red', label='Predicted Data (2012-2023)')
plt.xlabel('Year')
plt.ylabel('Assets')
plt.title('Growing Assets of Commercial Bank')
plt.legend()
plt.show()

当前输出图表

实际值与预测值


期望的图表样式

样例图表

内容的提问来源于stack exchange,提问作者Asmat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 03:03:11