AlexNet网络对已经打好四个标签某文件夹中的彩色图像数据集进行分类并对卷积操作可视化具体matlab
时间: 2024-06-11 21:06:58 浏览: 142
代码如下:
%% 加载数据
imds = imageDatastore('path/to/folder', 'IncludeSubfolders', true, 'LabelSource', 'foldernames');
% 将数据集分为训练集和测试集
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.8, 'randomized');
% 显示部分图像
figure
perm = randperm(100,20);
for i = 1:20
subplot(4,5,i)
imshow(imds.Files{perm(i)})
end
%% 定义AlexNet网络
net = alexnet;
% 查看网络结构
net.Layers
%% 修改网络结构
% 将最后一层全连接层的输出数目改为对应分类数目
numClasses = numel(categories(imdsTrain.Labels));
layers = net.Layers;
layers(end-2) = fullyConnectedLayer(numClasses);
layers(end) = classificationLayer;
%% 训练网络
% 定义训练选项
opts = trainingOptions('sgdm', ...
'MiniBatchSize', 32, ...
'MaxEpochs', 4, ...
'InitialLearnRate', 1e-4, ...
'Shuffle', 'every-epoch', ...
'ValidationData', imdsTest, ...
'ValidationFrequency', 3, ...
'Verbose', false, ...
'Plots', 'training-progress');
% 训练网络
netTransfer = trainNetwork(imdsTrain, layers, opts);
%% 对测试集进行分类
YPred = classify(netTransfer, imdsTest);
YTest = imdsTest.Labels;
% 计算分类准确率
accuracy = sum(YPred == YTest)/numel(YTest)
%% 可视化卷积操作
% 选择一张测试集中的图像
idx = 19;
I = readimage(imdsTest, idx);
% 显示原始图像
figure
imshow(I)
% 获取第一层卷积层的权重矩阵
w = netTransfer.Layers(2).Weights;
% 将权重矩阵reshape成卷积核形式
w = mat2cell(w, size(w,1), size(w,2), ones(1,size(w,3)), size(w,4));
w = cellfun(@(x) permute(x,[1 2 4 3]), w, 'UniformOutput', false);
w = cell2mat(w);
% 对图像进行卷积操作
convI = vl_nnconv(single(I), w, []);
% 显示卷积结果
figure
imshow(convI(:,:,1), [])
title('第一层卷积结果')
% 获取第二层卷积层的权重矩阵
w = netTransfer.Layers(6).Weights;
% 将权重矩阵reshape成卷积核形式
w = mat2cell(w, size(w,1), size(w,2), size(w,3), ones(1,size(w,4)));
w = cellfun(@(x) permute(x,[1 2 4 3]), w, 'UniformOutput', false);
w = cell2mat(w);
% 对卷积结果进行卷积操作
convI2 = vl_nnconv(convI, w, []);
% 显示卷积结果
figure
subplot(1,2,1)
imshow(convI(:,:,1), [])
title('第一层卷积结果')
subplot(1,2,2)
imshow(convI2(:,:,1), [])
title('第二层卷积结果')
阅读全文