Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
127 views

Code For Segmentation Into 277x277 Matrix

The code segments provided define the layers and architecture for convolutional neural networks (CNNs) to perform image classification tasks on medical image datasets. Specifically: 1) The code loads training image data, defines CNN layers including convolution, pooling and fully connected layers, and training options to train the networks from scratch or perform transfer learning using pretrained networks like AlexNet. 2) Segments show loading test data and evaluating trained networks on test images by computing classification predictions and confusion matrices. 3) The architectures defined include LeNet-style CNNs as well as using pretrained models like AlexNet for transfer learning on medical image classification problems.

Uploaded by

Avinash Baldi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

Code For Segmentation Into 277x277 Matrix

The code segments provided define the layers and architecture for convolutional neural networks (CNNs) to perform image classification tasks on medical image datasets. Specifically: 1) The code loads training image data, defines CNN layers including convolution, pooling and fully connected layers, and training options to train the networks from scratch or perform transfer learning using pretrained networks like AlexNet. 2) Segments show loading test data and evaluating trained networks on test images by computing classification predictions and confusion matrices. 3) The architectures defined include LeNet-style CNNs as well as using pretrained models like AlexNet for transfer learning on medical image classification problems.

Uploaded by

Avinash Baldi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Code for segmentation into 277x277 matrix

clc
clear all
[y,Fs] = audioread('heart_sound_1.wav');
%'morse', 'amor', and 'bump', which specify the Morse, Morlet (Gabor), and bump
wavelet, respectively
[wt,f] = cwt(y ,'mor',Fs);
cwt(y ,'mor',Fs)
savefig('PeaksFile.fig')
axObjs = openfig('PeaksFile.fig');
% axObjs = fig.Children
% x = dataObjs(1).XData
% y = dataObjs(1).YData
% z = dataObjs(1).ZData
sh = findall(axObjs , 'type', 'surface');
data_array = get(sh, 'CData');
delete(axObjs);
[m,n] = size(data_array)
%% processing of array %%
syms l p
l = rem(m,277);
p = rem(n,277);

ar = data_array((1:m ),(1:n));
ar_2= data_array((1:277-(2*m)),(1:n));
data_array = [data_array ;ar ;ar_2];

ar = data_array((1:277 ),(1:277-p));
IND = [data_array ar];

%% ************ segmentation (after preprocessing) ************ %%


syms o
o =1;
y = zeros(o, 277 ,277);
j=1:277:m;
i=1:277:n
ni = length(i);
nj = length(j);

[m,n] = size(IND);
for kj = 1:nj
for ki = 1:ni
v = i(ki)+276
Y{o, : , :} = IND((j(kj) : j(kj)+276), (i(ki) : i(ki)+276));
o = o+1;
end
o =o+1;
end
Code for spherical segmentation
clc
close all
[y,Fs] = audioread('heart_sound_1.wav');
%'morse', 'amor', and 'bump', which specify the Morse, Morlet (Gabor), and bump
wavelet, respectively
[wt,f] = cwt(y ,'mor',Fs);
cwt(y ,'mor',Fs)
savefig('PeaksFile.fig')
axObjs = openfig('PeaksFile.fig');
% axObjs = fig.Children
% x = dataObjs(1).XData
% y = dataObjs(1).YData
% z = dataObjs(1).ZData
sh = findall(axObjs , 'type', 'surface');
data_array = get(sh, 'CData');
delete(axObjs);

%% segmentation into one second audio %%


nos = 0.8 *Fs;
[a c] = size(data_array);
padding= rem(c,nos);
padding = nos - padding;
data_array = [data_array data_array(1:a,1:padding)];
[len_r len_c] = size(data_array);

syms r
r= 1;
mat_1 = zeros(len_r, nos,r);
j=1:nos:len_c;
i=length(j);
for k = 1:i
mat_1(:,:,r) = data_array(1:len_r,(j(k):j(k)+nos-1));
r=r+1;
end
t= length(r);
for i = 1:r-1
img = squeeze(mat_1(:,:,i));
FileName = sprintf('myclown%d.png', i);
imwrite(im2uint8(img),FileName,'BitDepth', 16);
% figure
% imshow(rgbImage)
% savefig('wav_.fig');
% saveas(k,sprintf('FIG%d.png',i));
end
Spherical Segmentation (short images)

clc
close all
[y,Fs] = audioread('heart sound_patient.wav');
%'morse', 'amor', and 'bump', which specify the Morse, Morlet (Gabor), and bump
wavelet, respectively
[a,b] = size(y)
y_linear= zeros(a*b,1);
y_linear = [y(:,1);y(:,2)];
[wt,f] = cwt(y_linear,'mor',Fs);
cwt(y_linear ,'mor',Fs)
savefig('PeaksFile.fig')
axObjs = openfig('PeaksFile.fig');
% axObjs = fig.Children
% x = dataObjs(1).XData
% y = dataObjs(1).YData
% z = dataObjs(1).ZData
sh = findall(axObjs , 'type', 'surface');
data_array = get(sh, 'CData');
delete(axObjs);

%% segmentation into one second audio %%


nos = 0.8 *Fs;
[a c] = size(data_array);
padding= rem(c,nos);
padding = nos - padding;
data_array = [data_array data_array(1:a,1:padding)];
[len_r len_c] = size(data_array);

syms r
r= 1;
mat_1 = zeros(len_r, nos,r);
j=1:nos:len_c;
i=length(j);
for k = 1:i
mat_1(:,:,r) = data_array(1:len_r,(j(k):j(k)+nos-1));
r=r+1;
end
t= length(r);
for i = 1:r-1
img = squeeze(mat_1(:,:,i));
FileName = sprintf('myclown%d.png', i);
imwrite(im2uint8(img),FileName,'BitDepth', 16);
% figure

% savefig('wav_.fig');
% saveas(k,sprintf('FIG%d.png',i));
end
figure ()
imshow('myclown1.png')
Testing Alex net
clc
close all
nnet = alexnet %load neural network
% Read myclown1.png through myclown41.png.
% Files are in the "yourFolder" directory.
for k = 1:48
jpgFilename = sprintf('myclown%d.jpg', k);
%fullFileName = fullfile(yourFolder, jpgFilename);
fullFileName = fullfile( jpgFilename);
if exist(fullFileName, 'file')
imageData = imread(fullFileName );
imagedata =imresize(imagedata, [277,277]);
label = classify(nnet , imagedata);
image(imagedata);
title(char(label));
drawnow;
else
warningMessage = sprintf('Warning: image file does not exist:\n%s',
fullFileName);
uiwait(warndlg(warningMessage));
end
imshow(imageData);
end

Invoking Alex net


%% Load Pre-trained Network (AlexNet)
alex = alexnet;
%% Review Network Architecture
layers = alex.Layers

% In order for imageDataStore to parse the folder names as category labels,


% you would have to store image categories in corresponding sub-folders.
allImages = imageDatastore('TrainingData', 'IncludeSubfolders', true,...
'LabelSource', 'foldernames');

%% Split data into training and test sets


[trainingImages, testImages] = splitEachLabel(allImages, 0.8, 'randomize');

%% Modify Pre-trained Network


% AlexNet was trained to recognize 1000 classes, we need to modify it to
% recognize just 2 classes.
layers(23) = fullyConnectedLayer(2); % change this based on # of classes
layers(25) = classificationLayer

%% Perform Transfer Learning


opts = trainingOptions('sgdm', 'InitialLearnRate', 0.001,...
'MaxEpochs', 20, 'MiniBatchSize', 64);
%% Train the Network
This process usually takes about 5-20 minutes on a desktop GPU.
myNet = trainNetwork(trainingImages, layers, opts);
Main Code
close all;
clear all;
clc;
%--------------------Load training data-------------------------------------
% Please note: these are 4 of the 10 categories available
% Feel free to choose which ever you like best!

categories = {'health5064','unhealth5064'}; %loading images

rootFolder = '/MATLAB Drive/ANN Project/classes';


imds = imageDatastore(fullfile(rootFolder, categories), ...
'LabelSource', 'foldernames');

%--------------------Define Layers-------------------------------------------
%Training from scratch gives you a lot of freedom to explore the architecture.
%Take a look at this architecture and see how you might want to alter it:
%for example, how would you add another convolutional layer?
numoffilters=20; % first convoltuion layer
conv1 = convolution2dLayer(5,numoffilters,'Padding',1,'BiasLearnRateFactor',2); %
5*5 filter 20 filters
conv1.Weights = single(randn([5 5 1 numoffilters])*0.0001); % assigning filter
values
fc1 = fullyConnectedLayer(500,'BiasLearnRateFactor',2);
fc1.Weights = single(randn([500 7700])*0.1);
fc2 = fullyConnectedLayer(2,'BiasLearnRateFactor',2);
fc2.Weights = single(randn([2 500])*0.1);

layers = [
imageInputLayer([50 64 1]); %input image
% layer 1
conv1;
maxPooling2dLayer(2,'Stride',2);
%reluLayer();
% layer 2
convolution2dLayer(5,50,'Padding',1,'BiasLearnRateFactor',2);
%reluLayer();
maxPooling2dLayer(2,'Stride',2);
%convolution2dLayer(5,64,'Padding',2,'BiasLearnRateFactor',2);
%reluLayer();
%averagePooling2dLayer(3,'Stride',2);
fc1;
reluLayer();
fc2;
softmaxLayer()
classificationLayer();
]
%------------------------------Define training options---------------------------
--------------------------------
%The training options is another parameter that can significantly increase or
decrease the accuracy of the network.
%Try altering some of these values and see what happens to the overall accuracy
of the network.

opts = trainingOptions('sgdm', ...


'InitialLearnRate', 0.001, ...
'LearnRateSchedule', 'piecewise', ...
'LearnRateDropFactor', 0.1, ...
'LearnRateDropPeriod', 8, ...
'L2Regularization', 0.004, ...
'MaxEpochs', 10, ...
'MiniBatchSize', 100, ...
'Verbose', true);
%------------------------------Train!--------------------------------------------
--------------------------------
%This is where the training happens. This can take a few minutes or longer
depending on your hardware.
%Training on a GPU is recommended.
[net, info] = trainNetwork(imds, layers,opts);

%################################################################################
################################
%################################################################################
################################
%----------------------------Load test data--------------------------------------
--------------------------------
%
rootFolder = '/MATLAB Drive/ANN Project/classes/test_h_health_5064';
imds_test = imageDatastore(fullfile(rootFolder, categories), ...
'LabelSource', 'foldernames');

% %---------------------------Test one at a time---------------------------------


----------------------------------
% %Run this section multiple times to get a feel for the random images and how
they are being classified.
% %If the title of the image is green, this is a correct prediction.
% %If the title is red, the prediction is incorrect.

labels = classify(net, imds_test);

ii = randi(9);
im = imread(imds_test.Files{ii});
imshow(im);
if labels(ii) == imds_test.Labels(ii)
colorText = 'g';
else
colorText = 'r';
end
title(char(labels(ii)),'Color',colorText);

%------------------------Do it all at once---------------------------------------


---------------------------------
%This section of code will run through all the test data and compare the
predicted labels with the actual labels.
%This will give a feel for how the network is doing overall with one average
prediction value.

% This could take a while if you are not using a GPU


confMat = confusionmat(imds_test.Labels, labels);
confMat = confMat./sum(confMat,2);
mean(diag(confMat))

Le-net(training and testing)


close all;

clear all;
clc;
%--------------------Load training data-------------------------------------
% Please note: these are 4 of the 10 categories available
% Feel free to choose which ever you like best!
categories = {'healthy_rgb','unhealthy_rgb'};
rootFolder = '/MATLAB Drive/ANN Project/classes';
imds = imageDatastore(fullfile(rootFolder, categories), ...
'LabelSource', 'foldernames');
%--------------------Define Layers-------------------------------------------
%Training from scratch gives you a lot of freedom to explore the architecture.
%Take a look at this architecture and see how you might want to alter it:
%for example, how would you add another convolutional layer?

varSize = 32;
conv1 = convolution2dLayer(5,varSize,'Padding',2,'BiasLearnRateFactor',2);
conv1.Weights = single(randn([5 5 3 varSize])*0.0001);
fc1 = fullyConnectedLayer(64,'BiasLearnRateFactor',2);
fc1.Weights = single(randn([64 576])*0.1);
fc2 = fullyConnectedLayer(2,'BiasLearnRateFactor',2);
fc2.Weights = single(randn([2 64])*0.1);
layers = [
% layer 1
imageInputLayer([varSize varSize 3]);
conv1;
maxPooling2dLayer(2,'Stride',2); %maxpool
reluLayer();
% layer2
convolution2dLayer(5,32,'Padding',2,'BiasLearnRateFactor',2);
reluLayer();
averagePooling2dLayer(2,'Stride',2); %avgpool
% layer 3
convolution2dLayer(5,64,'Padding',2,'BiasLearnRateFactor',2);
reluLayer();
averagePooling2dLayer(3,'Stride',2); %avgpool
fc1;
reluLayer();
fc2;
softmaxLayer()
classificationLayer()];

%------------------------------Define training options-----------------------------------


------------------------
%The training options is another parameter that can significantly increase or decrease
the accuracy of the network.
%Try altering some of these values and see what happens to the overall accuracy of the
network.
opts = trainingOptions('sgdm', ...
'InitialLearnRate', 0.001, ...
'LearnRateSchedule', 'piecewise', ...
'LearnRateDropFactor', 0.1, ...
'LearnRateDropPeriod', 8, ...
'L2Regularization', 0.004, ...
'MaxEpochs', 10, ...
'MiniBatchSize', 100, ...
'Verbose', true);
%------------------------------Train!----------------------------------------------------
------------------------
%This is where the training happens. This can take a few minutes or longer depending on
your hardware.
%Training on a GPU is recommended.
[net, info] = trainNetwork(imds, layers, opts);
%########################################################################################
########################
%########################################################################################
########################
%----------------------------Load test data----------------------------------------------
------------------------
%
rootFolder = '/MATLAB Drive/ANN Project/Test_h_healthy';
imds_test = imageDatastore(fullfile(rootFolder, categories), ...
'LabelSource', 'foldernames');

% %---------------------------Test one at a time-----------------------------------------


--------------------------
% %Run this section multiple times to get a feel for the random images and how they are
being classified.
% %If the title of the image is green, this is a correct prediction.
% %If the title is red, the prediction is incorrect.
labels = classify(net, imds_test);
ii = randi(10);
im = imread(imds_test.Files{ii});
imshow(im);
if labels(ii) == imds_test.Labels(ii)
colorText = 'g';
else
colorText = 'r';
end
title(char(labels(ii)),'Color',colorText);
%------------------------Do it all at once-----------------------------------------------
-------------------------
%This section of code will run through all the test data and compare the predicted labels
with the actual labels.
%This will give a feel for how the network is doing overall with one average prediction
value.
% This could take a while if you are not using a GPU
confMat = confusionmat(imds_test.Labels, labels);
confMat = confMat./sum(confMat,2);
mean(diag(confMat))
************************
Conversion and Resizing
************************
clc
close all
for n=1:40
image_{n}= imread(sprintf('/MATLAB
Drive/Published/healthy/healthy_murmurs/myclown%s.png',num2str(n)));
imag_{n} = imresize(image_{n} ,[277,277]);
rgbImage_{n} = cat(3, imag_{n}, imag_{n}, imag_{n});
%imwrite (imag_{n} , 'pout%s.png');
imwrite(rgbImage_{n},['pout' num2str(n) '.png'],'png');
end

You might also like