read the noisy matrix mat by line as a resnet18 input and the clean matrix mat by line as its output to train the cnn-resnet18 to denoise in matlab

To train a denoising CNN based on Resnet18 architecture in Matlab, the first step is to prepare the noisy matrix and clean matrix as inputs and outputs, respectively, and then load them as datasets to be used in the training process.

Assuming noisy_matrix.mat and clean_matrix.mat have M rows and N columns, the following code reads the input and output matrices line by line:

main.m
noisy_data = load('noisy_matrix.mat'); % load noisy matrix
clean_data = load('clean_matrix.mat'); % load clean matrix

data = zeros(M,N,2);

for i = 1:M
    data(i,:,1) = noisy_data(i,:); % noisy matrix is the input
    data(i,:,2) = clean_data(i,:); % clean matrix is the output
end
284 chars
10 lines

The output data is an M x N x 2 3D matrix, where the first two dimensions represent the size of the matrices, and the third dimension represents the input and output channels of the dataset.

Next, you need to create an image datastore from this dataset by using the matfile function in Matlab:

main.m
imds = imageDatastore(matfile('data.mat'),'FileExtensions','.mat',...
    'ReadFcn',@(x)matfile(x,'Writable',false).data);
123 chars
3 lines

This creates an image datastore imds from the data variable, with .mat file extension.

Now that the data is prepared, you can create a data augmentation pipeline to perform random flips, rotations, and translations on the noisy input data:

main.m
augmenter = imageDataAugmenter('RandXReflection',true,...
    'RandRotation',[-10 10],'RandXTranslation',[-3 3],'RandYTranslation',[-3 3]);

inputSize = [M,N,1];
auimds = augmentedImageDatastore(inputSize,imds,'DataAugmentation',augmenter);
241 chars
6 lines

Finally, you can define the Resnet18 architecture, specify the training options, and start training the network:

main.m
resnet18 = resnet18;

layers = [
    imageInputLayer([M,N,1])
    convolution2dLayer(3,64,'Padding',1,'Stride',1)
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2,'Padding',0,'Stride',2)
    resnet18(2:end-5)
    fullyConnectedLayer(512)
    reluLayer
    dropoutLayer(0.5)
    fullyConnectedLayer(2)
    regressionLayer
];

options = trainingOptions('adam', ...
    'MiniBatchSize',32, ...
    'MaxEpochs',50, ...
    'Shuffle','every-epoch', ...
    'InitialLearnRate',1e-3, ...
    'Verbose',false);

net = trainNetwork(augimds,layers,options);
565 chars
25 lines

This will train a Resnet18-based CNN on the input and output matrices to denoise the noisy input data.

Note: Make sure your matrices are properly normalized and scaled between range [0,1]

related categories

gistlibby LogSnag