部分代码:
%% 清空环境变量
warning off % 关闭报警信息
close all % 关闭开启的图窗
clear % 清空变量
clc % 清空命令行
%% 重构数据
data_Trend = xlsread("dataguOne.xlsx")
dT = data_Trend(:,1:1)';%选取第1列
step=5
Delays = [1:step]; % 滑动窗口
[input, output] = CreateTimeSeriesData(dT, Delays);% 构造时间序列数据函数
%% 重构数据
res=[input',output'];
%% 导入数据
% res = xlsread('dataguM.xlsx');
%% 数据分析
train_size = 0.8; % 训练集占数据集比例
outdim = 1; % 最后一列为输出
all_samples = size(res, 1); % 样本个数
num_trains = round(train_size * all_samples); % 训练集样本个数
in_ = size(res, 2) - outdim; % 输入特征维度
%% 划分训练集和测试集
P_train = res(1: num_trains, 1: in_)';
T_train = res(1: num_trains, end)';
M = size(P_train, 2);
P_test = res(num_trains+1: end, 1: in_)';
T_test = res(num_trains+1: end, end)';
N = size(P_test, 2);
%% 数据reshape
p_train = double(reshape(P_train, in_, 1, 1, M));
p_test = double(reshape(P_test , in_, 1, 1, N));
t_train = double(T_train)';
t_test = double(T_test )';
%% 构造网络layers
layers = [
imageInputLayer([in_, 1, 1]) % 输入层 输入数据规模[in_, 1, 1]
convolution2dLayer([3, 1], 16) % 卷积核大小
batchNormalizationLayer % 批归一化层
reluLayer % Relu激活层
convolution2dLayer([3, 1], 32) % 卷积核大小
batchNormalizationLayer % 批归一化层
reluLayer % Relu激活层
dropoutLayer(0.1) % Dropout层
fullyConnectedLayer(1) % 全连接层
regressionLayer]; % 回归层
%% 模型预测
T_sim1 = predict(net, p_train);
T_sim2 = predict(net, p_test );
%% 均方根误差
error1 = sqrt(sum((T_sim1' - T_train).^2) ./ M);
error2 = sqrt(sum((T_sim2' - T_test ).^2) ./ N);
%% 绘制网络图
analyzeNetwork(layers)
%% 绘图
figure
plot(1: M, T_train, 'r-*', 1: M, T_sim1, 'b-o', 'LineWidth', 1)
legend('真实值', '预测值')
xlabel('预测样本')
ylabel('预测结果')
string = {'训练集预测结果对比'; ['RMSE=' num2str(error1)]};
title(string)
xlim([1, M])
grid
figure
plot(1: N, T_test, 'r-*', 1: N, T_sim2, 'b-o', 'LineWidth', 1)
legend('真实值', '预测值')
xlabel('预测样本')
ylabel('预测结果')
string = {'测试集预测结果对比'; ['RMSE=' num2str(error2)]};
title(string)
xlim([1, N])
grid
%% 评价指标计算
% R2
R1 = 1 - norm(T_train - T_sim1')^2 / norm(T_train - mean(T_train))^2;
R2 = 1 - norm(T_test - T_sim2')^2 / norm(T_test - mean(T_test ))^2;
disp(['训练集数据的R2为:', num2str(R1)])
disp(['测试集数据的R2为:', num2str(R2)])
% MAE
mae1 = sum(abs(T_sim1' - T_train)) ./ M ;
mae2 = sum(abs(T_sim2' - T_test )) ./ N ;
disp(['训练集数据的MAE为:', num2str(mae1)])
disp(['测试集数据的MAE为:', num2str(mae2)])
评价指标:
训练集数据的R2为:0.97795
测试集数据的R2为:0.22651
训练集数据的MAE为:1.2622
测试集数据的MAE为:6.2496