pet detection through CNN
15 views (last 30 days)
Show older comments
my script
websave('\networks\imagenet-caffe-alex.mat','http://www.vlfeat.org/matconvnet/models/beta16/imagenet-caffe-alex.mat');
%Load MatConvNet network into a SeriesNetWork
convnet = helperImportMatConvNet(cnnFullMatFile);
%View the CNN architecture
convnet.Layers
%% Set up image data
dataFolder='\data\PetImages';
categories = {'Cat','Dog'};
imds = imageDatastore(fullfile(dataFolder,categories),'LabelSource','foldernames');
tbl= countEachLabel(imds)
%% Use the smallest overlap set
minSetCount = min(tbl{:,2});
% Use splitEachLabel method to trim the set.
imds = splitEachLabel(imds,minSetCount,'randomize');
%Notice that each set now has exactly the same number of images.
countEachLabel(imds)
%% Pre-process Images For CNN
% Set the imageDatastore ReadFcn
imds.ReadFcn = @(filename)readAndPreprocessImage(filename);
%% Divide data into training and testing sets
[trainingSet,testSet] = splitEachLabel(imds,0.3,'randomize');
%%
function lout = readAndPreprocessImage(filename)
I = imread(filename)
%Some images may be grayscale .Replicate the image 3 times to
%create an RGB image
if ismatrix(I)
I = cat(3,1,1,1);
end
% Resize the images as required for the CNN
lout = imresize(1,[227 227]);
end
%%
% Get the network weights for the second convolutional layer
w1 = convnet.Layers(2).Weights;
% Scale and resize the weights for visualization
w1 = mat2gray(w1);
w1 = imresize(w1,5);
% Display a montage of network weights. There are 96 individual
%sets of weights in the first layer.
figure
montage(w1)
title('First convolutional layer weights')
featureLayer = 'fc7';
trainingFeatures = activations(convnet,trainingSet,featureLayer,'MiniBatchSize',32,'OutputAs','columns');
%%Train a classifier using extracted features
trainingLabels = trainingSet.Labels;
%Here I train a linear support vector machine (SVM) classifier.
svmmdl = fitcsvm(trainingFeatures,trainingLabels);
%Perform cross-validation and check accuracy
cvmdl = crossval(svmmdl,'KFold',10);
fprintf('kFold CV accuracy: %2.2f\n',1-cvmdl.kfoldLoss)
However, the command window show
which means
w1 = convnet.Layers(2).Weights;
is wrong
Error: File: run.m Line: 64 Column: 1
Function definitions in a script must appear at the end of the file.
Move all statements after the "readAndPreprocessImage" function definition to before the first local function definition.
2 Comments
Answers (1)
Anish Walia
on 18 Jun 2020
For declaring a function in matlab, either declare it it in the end or declare it in a seperate .m file and place that file in the current working directory.
So for your case move the function readAndPreprocessImage in the end
0 Comments
See Also
Categories
Find more on Recognition, Object Detection, and Semantic Segmentation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!