change to cnn model:
%% UK Electricity consumption prediction - Time series
%MUHAMMAD NAIM BIN NORDIN
%EC20012
%--------------------------------------------------------------------------------------------------------------------------%
%% LSTM
%%clear all
close all;
clear;
clc;
%--------------------------------------------------------------------------------------------------------------------------%
%% Load the train dataset
% Load the dataset
data = readtable('train data (2009-2022).csv');
settlement_date = datetime(data.settlement_date, 'InputFormat', 'd/MM/yyyy HH:mm');
data.settlement_date = settlement_date;
% Extract features and target
FEATURES = ["is_holiday","settlement_period","day_of_month","day_of_week","day_of_year","quarter","month","year","week_of_year",];
TARGET = "tsd";
X = table2array(data(:, FEATURES));
y = table2array(data(:, TARGET));
% Normalize the entire dataset
[X, mu, sigma] = zscore(X);
y_normalized = (y - mean(y)) / std(y); % If y is univariate, normalize separately
% Use the entire dataset for training
X_train = X;
y_train = y_normalized;
%% LSTM
% Create LSTM model
num_features = size(X, 2);
% Update LSTM layer with more hidden units
num_hidden_units = 215;
layers = [
sequenceInputLayer(num_features)
bilstmLayer(num_hidden_units, 'OutputMode', 'sequence')
fullyConnectedLayer(1)
regressionLayer
];
options = trainingOptions('adam', ...
'MaxEpochs', 100, ...
'GradientThreshold', 1, ...
'InitialLearnRate', 0.001, ... % Adjust the learning rate
'LearnRateSchedule', 'piecewise', ...
'LearnRateDropFactor', 0.9, ...
'LearnRateDropPeriod', 15, ...
'Plots', 'training-progress', ...
'Verbose', 1, ...
'MiniBatchSize', 64);
% Transpose the data for LSTM input
X_train = X_train';
y_train = y_train';
%% Train the GRU model
[net, info] = trainNetwork(X_train, y_train, layers, options);
%% Extract and plot mini-batch RMSE and mini-batch loss
% Ensure that the training info contains the mini-batch RMSE and loss
if isfield(info, 'MiniBatchRMSE') && isfield(info, 'MiniBatchLoss')
miniBatchRMSE = info.MiniBatchRMSE;
miniBatchLoss = info.MiniBatchLoss;
% Plot mini-batch RMSE
figure;
plot(miniBatchRMSE);
xlabel('Mini-batch');
ylabel('RMSE');
title('Mini-batch RMSE during Training');
grid on;
% Plot mini-batch loss
figure;
plot(miniBatchLoss);
xlabel('Mini-batch');
ylabel('Loss');
title('Mini-batch Loss during Training');
grid on;
else
disp('Training info does not contain MiniBatchRMSE or MiniBatchLoss');
end
%% Extract and plot mini-batch RMSE and mini-batch loss
miniBatchRMSE = info.TrainingRMSE;
miniBatchLoss = info.TrainingLoss;
% Plot mini-batch RMSE
figure;
plot(miniBatchRMSE);
xlabel('Mini-batch');
ylabel('RMSE');
title('Mini-batch RMSE during Training');
set(gcf,'color','w');
grid on;
% Plot mini-batch loss
figure;
plot(miniBatchLoss);
xlabel('Mini-batch');
ylabel('Loss');
title('Mini-batch Loss during Training');
set(gcf,'color','w');
grid on;
%% Load the test dataset
test_data = readtable('test.csv');
settlement_date_test = datetime(test_data.settlement_date, 'InputFormat', 'd/MM/yyyy HH:mm');
test_data.settlement_date = settlement_date_test;
% Extract features and target for the test set
X_test = table2array(test_data(:, FEATURES));
y_test = table2array(test_data(:, TARGET));
% Normalize the test set using mean and standard deviation from the training set
X_test = (X_test - mu) ./ sigma;
% Normalize the target variable for the test set using mean and standard deviation from the training set
y_test_normalized = (y_test - mean(y)) / std(y);
%% Transpose the test data for LSTM input
X_test = X_test';
y_test_normalized = y_test_normalized';
%% Make predictions on the test set
y_pred_normalized = predict(net, X_test);
% Denormalize the predicted values
y_pred = y_pred_normalized * std(y) + mean(y);
%% Visualize the predictions
% Visualize the predictions against the actual values
figure;
plot(settlement_date_test, y_test, 'b-', 'DisplayName', 'Actual');
hold on;
plot(settlement_date_test, y_pred, 'r-', 'DisplayName', 'Predicted');
xlabel('Settlement Date');
ylabel('Electricity Consumption');
title('Actual vs. Predicted Electricity Consumption on Test Set');
legend('Actual', 'Predicted');
set(gcf,'color','w');
grid on;
%% Evaluate the performance on the test set (you may use appropriate metrics)
% Calculate rmse
rmse = sqrt(mean((y_test_normalized - y_pred_normalized).^2));
disp(['Root Mean Squared Error (RMSE) on the test set: ', num2str(rmse)]);
% Calculate MAE
mae = mean(abs(y_test_normalized - y_pred_normalized));
disp(['Mean Absolute Error (MAE) on the test set: ', num2str(mae)]);
% Calculate R^2
ss_residual = sum((y_test_normalized - y_pred_normalized).^2);
ss_total = sum((y_test_normalized - mean(y_test_normalized)).^2);
r2 = 1 - ss_residual / ss_total;
fprintf('R-squared (R2) Score: %.4f\n', r2);