cnn in matlab

Here is an example of training a Convolutional Neural Network (CNN) for image classification in MATLAB:

main.m
% Load the training and testing data
imdsTrain = imageDatastore('path/to/training/images', 'IncludeSubfolders', true, 'LabelSource', 'foldernames');
imdsTest = imageDatastore('path/to/testing/images', 'IncludeSubfolders', true, 'LabelSource', 'foldernames');

% Define the CNN architecture
layers = [
    imageInputLayer([32 32 3])
    convolution2dLayer(3, 32, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2, 'Stride', 2)
    convolution2dLayer(3, 64, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2, 'Stride', 2)
    convolution2dLayer(3, 128, 'Padding', 'same')
    batchNormalizationLayer
    reluLayer
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer];

% Set the training options
options = trainingOptions('sgdm', ...
    'InitialLearnRate', 0.001, ...
    'MaxEpochs', 15, ...
    'MiniBatchSize', 128,...
    'Shuffle', 'every-epoch', ...
    'ValidationData', imdsTest, ...
    'ValidationFrequency', 300, ...
    'Verbose', false, ...
    'Plots', 'training-progress');

% Train the CNN
net = trainNetwork(imdsTrain, layers, options);

% Classify test images using the trained CNN
YPred = classify(net, imdsTest);

% Calculate the classification accuracy
accuracy = mean(YPred == imdsTest.Labels);
1303 chars
42 lines

In this example, we first load the training and testing data into imageDatastore objects. Then, we define the CNN architecture using the layers array. This CNN consists of three convolutional layers with batch normalization and ReLU activation, followed by two max pooling layers, a fully connected layer, a softmax layer, and a classification layer.

Next, we set the training options using the trainingOptions function. These options include the optimization algorithm (sgdm), the initial learning rate, the maximum number of epochs, the mini-batch size, and the validation data.

We then train the CNN on the training data using the trainNetwork function, passing in the imageDatastore for the training data, the layers array, and the options struct.

After training, we use the classify function to predict the labels of the test images using the trained CNN. Finally, we calculate the classification accuracy by comparing the predicted labels to the true labels in the test data.

gistlibby LogSnag