Skip to content

Commit 7e3f4b7

Browse files
committed
Adding demo files
0 parents  commit 7e3f4b7

12 files changed

+666
-0
lines changed

CIFARTraining/cifar10CNN.m

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
%% Classifying the CIFAR-10 dataset using Convolutional Neural Networks
2+
% This example shows how to train a Convolutional Neural Network (CNN) from
3+
% scratch using the dataset CIFAR10.
4+
%
5+
% Data Credit: Krizhevsky, A., & Hinton, G. (2009). Learning multiple
6+
% layers of features from tiny images.
7+
8+
% Copyright 2016 The MathWorks, Inc.
9+
10+
%% Download the CIFAR-10 dataset
11+
if ~exist('cifar-10-batches-mat','dir')
12+
cifar10Dataset = 'cifar-10-matlab';
13+
disp('Downloading 174MB CIFAR-10 dataset...');
14+
websave([cifar10Dataset,'.tar.gz'],...
15+
['https://www.cs.toronto.edu/~kriz/',cifar10Dataset,'.tar.gz']);
16+
gunzip([cifar10Dataset,'.tar.gz'])
17+
delete([cifar10Dataset,'.tar.gz'])
18+
untar([cifar10Dataset,'.tar'])
19+
delete([cifar10Dataset,'.tar'])
20+
end
21+
22+
%% Prepare the CIFAR-10 dataset
23+
if ~exist('cifar10Train','dir')
24+
disp('Saving the Images in folders. This might take some time...');
25+
saveCIFAR10AsFolderOfImages('cifar-10-batches-mat', pwd, true);
26+
end
27+
28+
%% Load image CIFAR-10 Training dataset (50000 32x32 colour images in 10 classes)
29+
imsetTrain = imageSet('cifar10Train','recursive');
30+
31+
%% Display Sampling of Image Data
32+
numClasses = size(imsetTrain,2);
33+
imagesPerClass = 10;
34+
imagesInMontage = cell(imagesPerClass,numClasses);
35+
for i = 1:size(imagesInMontage,2)
36+
imagesInMontage(:,i) = ...
37+
imsetTrain(i).ImageLocation(randi(imsetTrain(i).Count, 1, ...
38+
imagesPerClass));
39+
end
40+
41+
montage({imagesInMontage{:}},'Size',[numClasses,imagesPerClass]);
42+
title('Sample of Training Data (Credit:Learning Multiple Layers of Features from Tiny Images, Alex Krizhevsky, 2009.)')
43+
44+
%% Prepare the data for Training
45+
% Read all images and store them in a 4D uint8 input array for training,
46+
% with its corresponding class
47+
48+
trainNames = {imsetTrain.Description};
49+
XTrain = zeros(32,32,3,sum([imsetTrain.Count]),'uint8');
50+
TTrain = categorical(discretize((1:sum([imsetTrain.Count]))',...
51+
[0,cumsum([imsetTrain.Count])],'categorical',trainNames));
52+
53+
j = 0;
54+
tic;
55+
for c = 1:length(imsetTrain)
56+
for i = 1:imsetTrain(c).Count
57+
XTrain(:,:,:,i+j) = read(imsetTrain(c),i);
58+
end
59+
j = j + imsetTrain(c).Count;
60+
end
61+
toc;
62+
63+
%% Define a CNN architecture
64+
conv1 = convolution2dLayer(5,32,'Padding',2,...
65+
'BiasLearnRateFactor',2);
66+
conv1.Weights = gpuArray(single(randn([5 5 3 32])*0.0001));
67+
fc1 = fullyConnectedLayer(64,'BiasLearnRateFactor',2);
68+
fc1.Weights = gpuArray(single(randn([64 576])*0.1));
69+
fc2 = fullyConnectedLayer(10,'BiasLearnRateFactor',2);
70+
fc2.Weights = gpuArray(single(randn([10 64])*0.1));
71+
72+
layers = [ ...
73+
imageInputLayer([32 32 3]);
74+
conv1;
75+
maxPooling2dLayer(3,'Stride',2);
76+
reluLayer();
77+
convolution2dLayer(5,32,'Padding',2,'BiasLearnRateFactor',2);
78+
reluLayer();
79+
averagePooling2dLayer(3,'Stride',2);
80+
convolution2dLayer(5,64,'Padding',2,'BiasLearnRateFactor',2);
81+
reluLayer();
82+
averagePooling2dLayer(3,'Stride',2);
83+
fc1;
84+
reluLayer();
85+
fc2;
86+
softmaxLayer()
87+
classificationLayer()];
88+
89+
% Define the training options.
90+
opts = trainingOptions('sgdm', ...
91+
'InitialLearnRate', 0.001, ...
92+
'LearnRateSchedule', 'piecewise', ...
93+
'LearnRateDropFactor', 0.1, ...
94+
'LearnRateDropPeriod', 8, ...
95+
'L2Regularization', 0.004, ...
96+
'MaxEpochs', 10, ...
97+
'MiniBatchSize', 100, ...
98+
'Verbose', true);
99+
100+
%% Training the CNN
101+
[net, info] = trainNetwork(XTrain, TTrain, layers, opts);
102+
103+
% Alternative way using imageDataStore
104+
% imdsTrain = imageDatastore(fullfile(pwd,'cifar10Train'),...
105+
% 'IncludeSubfolders',true,'LabelSource','foldernames');
106+
% [net, info] = trainNetwork(imdsTrain, layers, opts);
107+
108+
%% Visualise the first layer weights.
109+
figure;
110+
montage(mat2gray(gather(net.Layers(2).Weights)));
111+
title('First Layer Weights');
112+
113+
%% Load Test Data
114+
115+
imsetTest = imageSet('cifar10Test','recursive');
116+
117+
testNames = {imsetTest.Description};
118+
XTest = zeros(32,32,3,sum([imsetTest.Count]),'uint8');
119+
TTest = categorical(discretize((1:sum([imsetTest.Count]))',...
120+
[0,cumsum([imsetTest.Count])],'categorical',testNames));
121+
j = 0;
122+
tic;
123+
for c = 1:length(imsetTest)
124+
for i = 1:imsetTest(c).Count
125+
XTest(:,:,:,i+j) = read(imsetTest(c),i);
126+
end
127+
j = j + imsetTest(c).Count;
128+
end
129+
toc;
130+
131+
%% Run the network on the test set
132+
133+
YTest = classify(net, XTest);
134+
135+
% Alternative way using imageDataStore
136+
% imdsTest = imageDatastore(fullfile(pwd, 'cifar10Test'),...
137+
% 'IncludeSubfolders',true,'LabelSource','foldernames');
138+
% YTest = classify(net, imdsTest);
139+
140+
% Calculate the accuracy.
141+
accuracy = sum(YTest == TTest)/numel(TTest)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
% Copyright 2016 The MathWorks, Inc.
2+
3+
function [XTrain, TTrain, XTest, TTest] = loadCIFAR10AsAFourDimensionalArray()
4+
5+
% loadCIFAR10AsAFourDimensionalArray Load the CIFAR-10 data
6+
7+
[XTrain1, TTrain1] = iLoadBatchAsFourDimensionalArray('data_batch_1.mat');
8+
[XTrain2, TTrain2] = iLoadBatchAsFourDimensionalArray('data_batch_2.mat');
9+
[XTrain3, TTrain3] = iLoadBatchAsFourDimensionalArray('data_batch_3.mat');
10+
[XTrain4, TTrain4] = iLoadBatchAsFourDimensionalArray('data_batch_4.mat');
11+
[XTrain5, TTrain5] = iLoadBatchAsFourDimensionalArray('data_batch_5.mat');
12+
13+
XTrain = cat(4, XTrain1, XTrain2, XTrain3, XTrain4, XTrain5);
14+
TTrain = [TTrain1; TTrain2; TTrain3; TTrain4; TTrain5];
15+
16+
[XTest, TTest] = iLoadBatchAsFourDimensionalArray('test_batch.mat');
17+
18+
XTrain = double(XTrain);
19+
XTest = double(XTest);
20+
end
21+
22+
function [XBatch, TBatch] = iLoadBatchAsFourDimensionalArray(batchFileName)
23+
load(batchFileName);
24+
XBatch = data';
25+
XBatch = reshape(XBatch, 32,32,3,[]);
26+
XBatch = permute(XBatch, [2 1 3 4]);
27+
TBatch = iConvertLabelsToCategorical(labels);
28+
end
29+
30+
function categoricalLabels = iConvertLabelsToCategorical(integerLabels)
31+
load('batches.meta.mat');
32+
categoricalLabels = categorical(integerLabels, 0:9, label_names);
33+
end
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
% Copyright 2016 The MathWorks, Inc.
2+
3+
function saveCIFAR10AsFolderOfImages(inputPath, outputPath, varargin)
4+
% saveCIFAR10AsFolderOfImages Save the CIFAR-10 dataset as a folder of images
5+
% saveCIFAR10AsFolderOfImages(inputPath, outputPath) takes the CIFAR-10
6+
% dataset located at inputPath and saves it as a folder of images to the
7+
% directory outputPath. If inputPath or outputPath is an empty string, it
8+
% is assumed that the current folder should be used.
9+
%
10+
% saveCIFAR10AsFolderOfImages(..., labelDirectories) will save the
11+
% CIFAR-10 data so that instances with the same label will be saved to
12+
% sub-directories with the name of that label.
13+
14+
% Check input directories are valid
15+
if(~isempty(inputPath))
16+
assert(exist(inputPath,'dir') == 7);
17+
end
18+
if(~isempty(outputPath))
19+
assert(exist(outputPath,'dir') == 7);
20+
end
21+
22+
% Check if we want to save each set with the same labels to its own
23+
% directory.
24+
if(isempty(varargin))
25+
labelDirectories = false;
26+
else
27+
assert(nargin == 3);
28+
labelDirectories = varargin{1};
29+
end
30+
31+
% Set names for directories
32+
trainDirectoryName = 'cifar10Train';
33+
testDirectoryName = 'cifar10Test';
34+
35+
% Create directories for the output
36+
mkdir(fullfile(outputPath, trainDirectoryName));
37+
mkdir(fullfile(outputPath, testDirectoryName));
38+
39+
if(labelDirectories)
40+
labelNames = {'airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'};
41+
iMakeTheseDirectories(fullfile(outputPath, trainDirectoryName), labelNames);
42+
iMakeTheseDirectories(fullfile(outputPath, testDirectoryName), labelNames);
43+
for i = 1:5
44+
iLoadBatchAndWriteAsImagesToLabelFolders(fullfile(inputPath,['data_batch_' num2str(i) '.mat']), fullfile(outputPath, trainDirectoryName), labelNames, (i-1)*10000);
45+
end
46+
iLoadBatchAndWriteAsImagesToLabelFolders(fullfile(inputPath,'test_batch.mat'), fullfile(outputPath, testDirectoryName), labelNames, 0);
47+
else
48+
for i = 1:5
49+
iLoadBatchAndWriteAsImages(fullfile(inputPath,['data_batch_' num2str(i) '.mat']), fullfile(outputPath, trainDirectoryName), (i-1)*10000);
50+
end
51+
iLoadBatchAndWriteAsImages(fullfile(inputPath,'test_batch.mat'), fullfile(outputPath, testDirectoryName), 0);
52+
end
53+
end
54+
55+
function iLoadBatchAndWriteAsImagesToLabelFolders(fullInputBatchPath, fullOutputDirectoryPath, labelNames, nameIndexOffset)
56+
load(fullInputBatchPath);
57+
data = data'; %#ok<NODEF>
58+
data = reshape(data, 32,32,3,[]);
59+
data = permute(data, [2 1 3 4]);
60+
for i = 1:size(data,4)
61+
imwrite(data(:,:,:,i), fullfile(fullOutputDirectoryPath, labelNames{labels(i)+1}, ['image' num2str(i + nameIndexOffset) '.png']));
62+
end
63+
end
64+
65+
function iLoadBatchAndWriteAsImages(fullInputBatchPath, fullOutputDirectoryPath, nameIndexOffset)
66+
load(fullInputBatchPath);
67+
data = data'; %#ok<NODEF>
68+
data = reshape(data, 32,32,3,[]);
69+
data = permute(data, [2 1 3 4]);
70+
for i = 1:size(data,4)
71+
imwrite(data(:,:,:,i), fullfile(fullOutputDirectoryPath, ['image' num2str(i + nameIndexOffset) '.png']));
72+
end
73+
end
74+
75+
function iMakeTheseDirectories(outputPath, directoryNames)
76+
for i = 1:numel(directoryNames)
77+
mkdir(fullfile(outputPath, directoryNames{i}));
78+
end
79+
end

LICENSE.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
Copyright (c) 2017, The MathWorks, Inc.
2+
All rights reserved.
3+
4+
Redistribution and use in source and binary forms, with or without
5+
modification, are permitted provided that the following conditions are
6+
met:
7+
8+
* Redistributions of source code must retain the above copyright
9+
notice, this list of conditions and the following disclaimer.
10+
* Redistributions in binary form must reproduce the above copyright
11+
notice, this list of conditions and the following disclaimer in
12+
the documentation and/or other materials provided with the distribution.
13+
* In all cases, the software is, and all modifications and derivatives
14+
of the software shall be, licensed to you solely for use in conjunction
15+
with MathWorks products and service offerings.
16+
17+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27+
POSSIBILITY OF SUCH DAMAGE.

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# DeepLearning-for-ComputerVision-with-MATLAB
2+
[![View Example files for "Deep Learning for Computer Vision with MATLAB" Webinar on File Exchange](https://www.mathworks.com/matlabcentral/images/matlab-file-exchange.svg)](https://www.mathworks.com/matlabcentral/fileexchange/58030-example-files-for-deep-learning-for-computer-vision-with-matlab-webinar)
3+
4+
These are the example files used in the webinar ["Aprendizaje Profundo para Visión Artificial con MATLAB" - Spanish](https://www.mathworks.com/videos/deep-learning-for-computer-vision-with-matlab-1540981496452.html) ("Deep Learning for Computer Vision with MATLAB").
5+
6+
7+
Deep Learning is an area of Machine Learning that uses multiple nonlinear processing layers to learn useful representations of features directly from data. This webinar shows the fundamentals of Deep Learning for Computer Vision and how to use Convolutional Neural Networks (popularly known as CNNs or ConvNets) to solve object classification/recognition problems.
8+
9+
The source code consists of 3 different examples:
10+
1. Running a trained CNN (/WebcamClassification)
11+
2. Training a CNN from scratch (/CIFARTraining)
12+
3. Fine-tuning a pre-trained CNN. Transfer learning (/TransferLearning)
13+
Examples 1) and 3) make use AlexNet [1]. In order to download the trained CNN [2], run the file downloadAndPrepareCNN.m (if using R2016a) or download AlexNet Network support package (if using R2016b or later).
14+
15+
References:
16+
[1] Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2012). Imagenet classification with Deep Convolutional Neural Networks. Advances in Neural Information Processing Systems (pp. 1097-1105).
17+
[2] Vedaldi, A., & Lenc, K. (2015, October). MatConvNet: Convolutional Neural Networks for MATLAB. Proceedings of the 23rd ACM International Conference on Multimedia (pp. 689-692). ACM.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
% Copyright 2016 The MathWorks, Inc.
2+
3+
function DisplayImageMontage(cellArrayOfImages)
4+
% Displays a montage of images. Images are resized to handle different
5+
% image sizes.
6+
7+
thumbnails = [];
8+
for i = 1:numel(cellArrayOfImages)
9+
img = imread(cellArrayOfImages{i});
10+
thumbnails = cat(4, thumbnails, imresize(img, [200 200]));
11+
end
12+
13+
montage(thumbnails)

0 commit comments

Comments
 (0)