# Import necessary libraries
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow import keras
from matplotlib import pyplot as plt
# Load the dataset
# Replace the file path with the one you download from the GitHub repository.
# Step 1: Load the dataset
# Read the data for the parameters from the GitHub URL into a Pandas DataFrame
url = "https://raw.githubusercontent.com/Carterbouley/ElectricityPricePrediction/refs/heads/master/re_fixed_multivariate_timeseires.csv"
# Fetch and load the CSV data
df = pd.read_csv(url, sep=",", low_memory=False)
print(df.columns) #['datetime', 'GBP/mWh', 'temperature', 'coal Price', 'oil Price', 'uranium Price','natural gas Price']
# Drop the 'datetime' column since it's not needed for the forecasting
del df['datetime']
# Convert the dataframe to a NumPy array for easier processing
data = df.values
# Define the number of past time steps used for forecasting
n_steps = 168 # One week's worth of hourly data (7 days * 24 hours)
# Reshape the data to create sequences for time series forecasting
# Each sequence includes `n_steps + 24` steps (past data + future target)
series_reshaped = np.array([
data[i:i + (n_steps + 24)].copy()
for i in range(len(data) - (n_steps + 24))
])
print(series_reshaped.shape) #(61134, 192, 6)
# Split the sequences into training, validation, and test datasets
X_train = series_reshaped[:43800, :n_steps] # First 43800 samples for training
X_valid = series_reshaped[43800:52560, :n_steps] # Next 8760 samples for validation
X_test = series_reshaped[52560:, :n_steps] # Remaining samples for testing
# Create the target variable `Y` for forecasting
# Target consists of 24 future steps for each sequence
Y = np.empty((series_reshaped.shape[0], n_steps, 24)) # Pre-allocate target array
for step_ahead in range(1, 24 + 1): # Loop over each future step
# Shift the target by `step_ahead` to align it with the input sequence
Y[..., step_ahead - 1] = series_reshaped[..., step_ahead:step_ahead + n_steps, 0]
# Split the target variable into training, validation, and test sets
Y_train = Y[:43800] # Training target
Y_valid = Y[43800:52560] # Validation target
Y_test = Y[52560:] # Testing target
# Set random seeds for reproducibility
np.random.seed(42)
tf.random.set_seed(42)
# Define the model architecture
model6 = keras.models.Sequential([
keras.layers.SimpleRNN(20, return_sequences=True, input_shape=[None, 6]), # First RNN layer
keras.layers.SimpleRNN(20, return_sequences=True), # Second RNN layer
keras.layers.TimeDistributed(keras.layers.Dense(24)) # Dense layer applied at each time step
])
# Compile the model with appropriate loss function and optimizer
model6.compile(
loss="mean_squared_error", # Mean squared error loss for regression tasks
optimizer="adam", # Adam optimizer for efficient training
metrics=['mean_absolute_percentage_error'] # Evaluation metric
)
# Train the model on the training data
history = model6.fit(
X_train, Y_train, # Training input and target
epochs=10, # Number of epochs
batch_size=64, # Batch size
validation_data=(X_valid, Y_valid) # Validation data
)
print(model6.summary())
#Model: "sequential"
#┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
#┃ Layer (type) ┃ Output Shape ┃ Param # ┃
#┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
#│ simple_rnn (SimpleRNN) │ (None, None, 20) │ 540 │
#├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
#│ simple_rnn_1 (SimpleRNN) │ (None, None, 20) │ 820 │
#├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
#│ time_distributed (TimeDistributed) │ (None, None, 24) │ 504 │
#└──────────────────────────────────────┴─────────────────────────────┴─────────────────┘
# Total params: 5,594 (21.86 KB)
# Trainable params: 1,864 (7.28 KB)
# Non-trainable params: 0 (0.00 B)
# Optimizer params: 3,730 (14.57 KB)