-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcustomResnet.m
117 lines (89 loc) · 3.45 KB
/
customResnet.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
imds = imageDatastore('C:\Users\Jonathan\Documents\GitHub\RiceDisease\Rice_All_Resize',...
'IncludeSubfolders',true,'LabelSource','foldernames');
% imds = imageDatastore('dataset1',...
% 'IncludeSubfolders',true,'LabelSource','foldernames');
[imdsTrain,imdsValidation] = splitEachLabel(imds,0.7,'randomized');
% Load pretrained Network
net = resnet50;
%Extract the layer graph from the trained network and plot the layer graph.
lgraph = layerGraph(net);
% figure('Units','normalized','Position',[0.1 0.1 0.8 0.8]);
%plot(lgraph)
% Check first layer input images dimensions
net.Layers(1)
inputSize = net.Layers(1).InputSize;
% Replacing last three layers for transfer learning / retraining
lgraph = removeLayers(lgraph, {'ClassificationLayer_fc1000','fc1000_softmax','fc1000'});
numClasses = numel(categories(imdsTrain.Labels));
newLayers = [
fullyConnectedLayer(numClasses,'Name','fc','WeightLearnRateFactor',10,'BiasLearnRateFactor',10)
softmaxLayer('Name','softmax')
classificationLayer('Name','classoutput')];
lgraph = addLayers(lgraph,newLayers);
% Connect last transfer layer to new layers and check
lgraph = connectLayers(lgraph,'avg_pool','fc');
% figure('Units','normalized','Position',[0.3 0.3 0.4 0.4]);
% %plot(lgraph)
% ylim([0,10])
% Set layers to 0 for speed and prevent over fitting
layers = lgraph.Layers;
connections = lgraph.Connections;
layers(1:110) = freezeWeights(layers(1:110));
lgraph = createLgraphUsingConnections(layers,connections);
%% Train the network
pixelRange = [-30 30];
imageAugmenter = imageDataAugmenter( ...
'RandXReflection',true, ...
'RandXTranslation',pixelRange, ...
'RandYTranslation',pixelRange);
augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain, ...
'DataAugmentation',imageAugmenter,'ColorPreprocessing','gray2rgb');
augimdsValidation = augmentedImageDatastore(inputSize(1:2),imdsValidation,'ColorPreprocessing','gray2rgb');
options = trainingOptions('sgdm', ...
'MiniBatchSize',2, ...
'MaxEpochs',1, ... % was 6
'InitialLearnRate',1e-4, ...
'Verbose',false, ...
'Plots','training-progress');
[trainedNet, traininfo] = trainNetwork(augimdsTrain,lgraph,options);
save 'transfer' trainedNet
%load 'transfer' trainedNet
%% Classify Validation Images
[YPred,probs] = classify(trainedNet,augimdsValidation);
accuracy = mean(YPred == imdsValidation.Labels)
%Calculate Confusion Matrix
cm=confusionmat(imdsValidation.Labels,YPred)
%Display confusion matrix
figure;
imagesc(cm)
colorbar
figure;
plotconfusion(imdsValidation.Labels,YPred)
function layers = freezeWeights(layers)
for i = 1:numel(layers)
if isprop(layers(i),'WeightLearnRateFactor')
layers(i).WeightLearnRateFactor = 0;
end
if isprop(layers(i),'WeightL2Factor')
layers(i).WeightL2Factor = 0;
end
if isprop(layers(i),'BiasLearnRateFactor')
layers(i).BiasLearnRateFactor = 0;
end
if isprop(layers(i),'BiasL2Factor')
layers(i).BiasL2Factor = 0;
end
end
end
function lgraph = createLgraphUsingConnections(layers,connections)
% lgraph = createLgraphUsingConnections(layers,connections) creates a layer
% graph with the layers in the layer array |layers| connected by the
% connections in |connections|.
lgraph = layerGraph();
for i = 1:numel(layers)
lgraph = addLayers(lgraph,layers(i));
end
for c = 1:size(connections,1)
lgraph = connectLayers(lgraph,connections.Source{c},connections.Destination{c});
end
end