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

基于Keras的GRU(含随机选择数据)多变量时间序列预测咨询

Hey there! Let's build out your GRU-based multivariate time series predictor for 90-length sequences using Keras. First, let's address a key gap in your current data splitting code: it doesn't account for the sequence length (90 time steps) that GRUs require for sequential input. Let's walk through the full implementation step by step.

Step 1: Fix Data Preparation (Create Sequences)

Time series models need input data shaped as [number of samples, sequence length, number of features]. Your current code just splits the data into train/test without creating these sequential windows. Here's a function to fix that:

import numpy as np

def create_sequences(data, seq_length):
    """
    Convert time series data into input sequences and target values
    Args:
        data: Raw multivariate time series array (shape: [total_timesteps, n_features + 1])
        seq_length: Length of input sequences (90 in your case)
    Returns:
        X: Input sequences (shape: [n_samples, seq_length, n_features])
        y: Target values (shape: [n_samples])
    """
    X, y = [], []
    # Loop through data to create sliding windows
    for i in range(len(data) - seq_length):
        # Grab seq_length time steps of features as input
        X.append(data[i:i+seq_length, :-1])
        # Grab the target value at the end of the window
        y.append(data[i+seq_length, -1])
    return np.array(X), np.array(y)

# First split raw data into train/test (keep your original split logic)
n_train_quarter = int(len(values) * 0.75)
train = values[:n_train_quarter, :]
test = values[n_train_quarter:, :]

# Create sequences with your desired length (90)
seq_length = 90
X_train, y_train = create_sequences(train, seq_length)
X_test, y_test = create_sequences(test, seq_length)

Step 2: Build the GRU Model

Now let's construct a flexible GRU model. You can tweak all parameters (units, activation, dropout, etc.) based on your data:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GRU, Dense, Dropout

# Get number of input features (from X_train shape)
n_features = X_train.shape[2]

model = Sequential([
    # First GRU layer: return sequences to stack another GRU layer
    GRU(units=64, return_sequences=True, input_shape=(seq_length, n_features), activation='tanh'),
    Dropout(0.2),  # Add dropout to prevent overfitting
    # Second GRU layer: no need to return sequences for final dense layer
    GRU(units=32, return_sequences=False, activation='tanh'),
    Dropout(0.2),
    # Output layer: linear activation for regression task
    Dense(units=1, activation='linear')
])

# Compile the model: use MSE for regression, Adam optimizer (adjust learning rate if needed)
model.compile(optimizer='adam', loss='mean_squared_error')

# Print model structure to verify
model.summary()

Step 3: Train the Model

Train the model with your prepared sequences. Note: don't shuffle time series data—order matters!

# Train the model (adjust epochs, batch_size based on your data size)
history = model.fit(
    X_train, y_train,
    batch_size=32,
    epochs=50,
    validation_data=(X_test, y_test),
    shuffle=False
)

Step 4: Evaluate and Predict

After training, evaluate performance on the test set and generate predictions:

# Generate predictions
y_pred = model.predict(X_test)

# Calculate evaluation metrics (MAE, RMSE for regression)
from sklearn.metrics import mean_absolute_error, mean_squared_error

mae = mean_absolute_error(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))

print(f"Test Set MAE: {mae:.4f}")
print(f"Test Set RMSE: {rmse:.4f}")

Pro Tips for Tuning

  • Normalize/Standardize Data: Time series data almost always benefits from scaling (e.g., MinMaxScaler or StandardScaler). Fit the scaler on the training data only to avoid data leakage.
  • Adjust GRU Units: Try increasing/decreasing units (e.g., 32, 64, 128) to find the sweet spot between capacity and overfitting.
  • Tweak Dropout: If you see overfitting (validation loss increases while training loss decreases), raise the dropout rate to 0.3-0.5.
  • Optimize Learning Rate: Instead of using default Adam, try tf.keras.optimizers.Adam(learning_rate=0.0001) if training is unstable.
  • Add Batch Normalization: Insert BatchNormalization() layers after GRU layers to stabilize training.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:06