%% 清空环境变量
warning off % 关闭报警信息
close all % 关闭开启的图窗
clear % 清空变量
clc % 清空命令行
%% 读取数据
res = xlsread('数据集.xlsx');
%% 分析数据
num_class = length(unique(res(:, end))); % 类别数(Excel最后一列放类别)
num_dim = size(res, 2) - 1; % 特征维度
num_res = size(res, 1); % 样本数(每一行,是一个样本)
num_size = 0.7; % 训练集占数据集的比例
res = res(randperm(num_res), :); % 打乱数据集(不打乱数据时,注释该行)
flag_conusion = 1; % 标志位为1,打开混淆矩阵(要求2018版本及以上)
%% 设置变量存储数据
P_train = []; P_test = [];
T_train = []; T_test = [];
%% 划分数据集
for i = 1 : num_class
mid_res = res((res(:, end) == i), :); % 循环取出不同类别的样本
mid_size = size(mid_res, 1); % 得到不同类别样本个数
mid_tiran = round(num_size * mid_size); % 得到该类别的训练样本个数
P_train = [P_train; mid_res(1: mid_tiran, 1: end - 1)]; % 训练集输入
T_train = [T_train; mid_res(1: mid_tiran, end)]; % 训练集输出
P_test = [P_test; mid_res(mid_tiran + 1: end, 1: end - 1)]; % 测试集输入
T_test = [T_test; mid_res(mid_tiran + 1: end, end)]; % 测试集输出
end
%% 数据转置
P_train = P_train'; P_test = P_test';
T_train = T_train'; T_test = T_test';
%% 得到训练集和测试样本个数
M = size(P_train, 2);
N = size(P_test , 2);
%% 数据归一化
[P_train, ps_input] = mapminmax(P_train, 0, 1);
P_test = mapminmax('apply', P_test, ps_input);
t_train = categorical(T_train)';
t_test = categorical(T_test )';
%% 数据平铺
% 将数据平铺成1维数据只是一种处理方式
% 也可以平铺成2维数据,以及3维数据,需要修改对应模型结构
% 但是应该始终和输入层数据结构保持一致
P_train = double(reshape(P_train, num_dim, 1, 1, M));
P_test = double(reshape(P_test , num_dim, 1, 1, N));
%% 数据格式转换
for i = 1 : M
Lp_train{i, 1} = P_train(:, :, 1, i);
end
for i = 1 : N
Lp_test{i, 1} = P_test( :, :, 1, i);
end
%% 建立模型
lgraph = layerGraph(); % 建立空白网络结构
tempLayers = [
sequenceInputLayer([num_dim, 1, 1], "Name", "sequence") % 建立输入层,输入数据结构为[num_dim, 1, 1]
sequenceFoldingLayer("Name", "seqfold")]; % 建立序列折叠层
lgraph = addLayers(lgraph, tempLayers); % 将上述网络结构加入空白结构中
tempLayers = convolution2dLayer([3, 1], 32, "Name", "conv_1"); % 卷积层 卷积核[3, 1] 步长[1, 1] 通道数 32
lgraph = addLayers(lgraph,tempLayers); % 将上述网络结构加入空白结构中
tempLayers = [
reluLayer("Name", "relu_1") % 激活层
convolution2dLayer([3, 1], 64, "Name", "conv_2") % 卷积层 卷积核[3, 1] 步长[1, 1] 通道数 64
reluLayer("Name", "relu_2")]; % 激活层
lgraph = addLayers(lgraph, tempLayers); % 将上述网络结构加入空白结构中
tempLayers = [
globalAveragePooling2dLayer("Name", "gapool") % 全局平均池化层
fullyConnectedLayer(16, "Name", "fc_2") % SE注意力机制,通道数的1 / 4
reluLayer("Name", "relu_3") % 激活层
fullyConnectedLayer(64, "Name", "fc_3") % SE注意力机制,数目和通道数相同
sigmoidLayer("Name", "sigmoid")]; % 激活层
lgraph = addLayers(lgraph, tempLayers); % 将上述网络结构加入空白结构中
tempLayers = multiplicationLayer(2, "Name", "multiplication"); % 点乘的注意力
lgraph = addLayers(lgraph, tempLayers); % 将上述网络结构加入空白结构中
tempLayers = [
sequenceUnfoldingLayer("Name", "sequnfold") % 建立序列反折叠层
flattenLayer("Name", "flatten") % 网络铺平层
lstmLayer(6, "Name", "lstm", "OutputMode", "last") % LSTM层
fullyConnectedLayer(num_class) % 全连接层
softmaxLayer % 损失函数层
classificationLayer]; % 分类层
lgraph = addLayers(lgraph, tempLayers); % 将上述网络结构加入空白结构中
lgraph = connectLayers(lgraph, "seqfold/out", "conv_1"); % 折叠层输出 连接 卷积层输入;
lgraph = connectLayers(lgraph, "seqfold/miniBatchSize", "sequnfold/miniBatchSize");
% 折叠层输出 连接 反折叠层输入
lgraph = connectLayers(lgraph, "conv_1", "relu_1"); % 卷积层输出 链接 激活层
lgraph = connectLayers(lgraph, "conv_1", "gapool"); % 卷积层输出 链接 全局平均池化
lgraph = connectLayers(lgraph, "relu_2", "multiplication/in2"); % 激活层输出 链接 相乘层
lgraph = connectLayers(lgraph, "sigmoid", "multiplication/in1"); % 全连接输出 链接 相乘层
lgraph = connectLayers(lgraph, "multiplication", "sequnfold/in"); % 点乘输出
%% 参数设置
options = trainingOptions('adam', ... % Adam 梯度下降算法
'MaxEpochs', 1000, ... % 最大迭代次数
'InitialLearnRate', 1e-2, ... % 初始学习率为0.01
'LearnRateSchedule', 'piecewise', ... % 学习率下降
'LearnRateDropFactor', 0.1, ... % 学习率下降因子 0.5
'LearnRateDropPeriod', 700, ... % 经过700次训练后 学习率为 0.01 * 0.1
'Shuffle', 'every-epoch', ... % 每次训练打乱数据集
'Plots', 'training-progress', ... % 画出曲线
'Verbose', false);
%% 训练模型
net = trainNetwork(Lp_train, t_train, lgraph, options);
%% 模型预测
t_sim1 = predict(net, Lp_train);
t_sim2 = predict(net, Lp_test );
%% 反归一化
T_sim1 = vec2ind(t_sim1');
T_sim2 = vec2ind(t_sim2');
%% 显示网络结构
analyzeNetwork(net)
%% 性能评价
error1 = sum((T_sim1 == T_train))/M * 100 ;
error2 = sum((T_sim2 == T_test)) /N * 100 ;
%% 绘图
figure
plot(1: M, T_train, 'r-*', 1: M, T_sim1, 'b-o', 'LineWidth', 1)
legend('真实值', '预测值')
xlabel('预测样本')
ylabel('预测结果')
string = {'训练集预测结果对比'; ['准确率=' 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 = {'测试集预测结果对比'; ['准确率=' num2str(error2) '%']};
title(string)
xlim([1, N])
grid
%% 混淆矩阵
if flag_conusion == 1
figure
cm = confusionchart(T_train, T_sim1);
cm.Title = 'Confusion Matrix for Train Data';
cm.ColumnSummary = 'column-normalized';
cm.RowSummary = 'row-normalized';
figure
cm = confusionchart(T_test, T_sim2);
cm.Title = 'Confusion Matrix for Test Data';
cm.ColumnSummary = 'column-normalized';
cm.RowSummary = 'row-normalized';
end