matlab使用自己的数据集做图像数据的回归问题1
最近需要做相同的任务,matlab官网给出的针对数字旋转训练神经网络的例子
针对回归训练卷积神经网络 - MATLAB & Simulink - MathWorks 中国
链接: link.
其中,构建数据集直接调用了digitTrain4DArrayData,但没有详细给出这个数据集的构造过程。
通过查阅trainNetwork函数,发现针对图像的回归任务需要将数据构造成4D-array的类型,于是根据digitTrain4DArrayData中的imds2array函数自己写了一份构建4D数据集的代码。
%% 加载自己的数据
%由于使用图片回归模型需要将数据集构造成4D-array的类型,即[W,H,C,N],W,H为图像长宽,C为图像深度,N为图像数目
sourcePath = 'D:\my_experiment\1550_crop';
imds = imageDatastore(sourcePath, 'IncludeSubfolders', true, 'LabelSource', 'foldernames'); %先使用imageDatastore将文件中的数据读取成datastore格式
[dsTrain, dsVal, dsTest] = splitEachLabel(imds, 0.8, 0.1, 0.1, 'randomized');
[XTrain, YTrain] = my_imds2array(dsTrain);
[XValidation, YValidation] = my_imds2array(dsVal);
function [X, T] = my_imds2array(imds)
% imds2array Convert an image datastore into a 4-D array
%
% X - Input data as an H-by-W-by-C-by-N array, where H is the
% height and W is the width of the images, C is the number of
% channels, and N is the number of images.
% T - Categorical vector containing the labels for each
% observation.
% Copyright 2016 The MathWorks, Inc.
imagesCellArray = imds.readall();
numImages = numel( imagesCellArray );
[h, w, c] = size( imagesCellArray{1} );
X = zeros( h, w, c, numImages );
for i=1:numImages
X(:,:,:,i) = im2double( imagesCellArray{i} );
end
T = double(imds.Labels); %imds.Lables读出的是categorical型,需要转换为double型
end
构建的XTrain,YTrain,XValidiion,YValidation可以直接用于trainNetwork。
但是现在我的数据集是分类数据集,我只是把label改为了regression的response,所以response值是一些整数型,而且单一response对应单一sample还没做,过几天写了贴上来。