0. 참고 영상
https://www.youtube.com/watch?v=60cllAUWIvI
1. 데이터 수집
구글에서 흰우유, 초코우유, 바나나우유, 딸기우유 4개의 카테고리에 각각 15장의 jpg사진을 수집함.
우유.zip
6.87MB
2. 데이터 불러오기
editior: MATLAB 라이브 스크립트 이용
imds = imageDatastore('우유', 'IncludeSubfolders',true, 'LabelSource','foldernames'); [imdsTrain, imdsValidation] = splitEachLabel(imds, 0.7, 'randomized'); |
3. 이미지 확인
numTrainImages = numel(imdsTrain.Labels); idx = randperm(numTrainImages, 16); figure for i = 1:16 % 16개의 사진만 뽑아보기 subplot(4,4,i) I = readimage(imdsTrain, idx(i)); imshow(I) end |

4. 사전훈련된 신경망 불러오기
net = alexnet; % 여기서는 alexnet 신경망을 사용할 예정. % 설치가 되어있지 않다면 설치하기 |
5. 신경망 layer 및 input size 확인하기
net.Layers inputSize = net.Layers(1).InputSize % size는 227*227 |

6. 마지막 계층 바꾸기
layersTranfer = net.Layers(1:end-3); numClasses = numel(categories(imdsTrain.Labels)) % 클래스의 수 : 4개 (흰, 초코, 바나나, 딸기우유) % layer를 새로 생성하기 layers = [ layersTranfer fullyConnectedLayer(numClasses, 'WeightLearnRateFactor', 20, 'BiasLearnRateFactor', 20) % 파라미터들은 예제와 동일하게 20으로 둠. softmaxLayer classificationLayer]; |
7. 신경망 훈련시키기
7-1. 훈련 이미지 데이터 증강
pixelRange = [-30, 30]; imageAugmenter = imageDataAugmenter( ... 'RandXReflection',true, ... 'RandXTranslation',pixelRange, ... 'RandYTranslation',pixelRange); augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain, ... 'DataAugmentation',imageAugmenter, ... 'ColorPreprocessing','gray2rgb'); |
7-2. 검증 이미지 데이터 증강
augimdsValidation = augmentedImageDatastore(inputSize(1:2), imdsValidation, ... "ColorPreprocessing","gray2rgb"); |
8. 네트워크 옵션
options = trainingOptions('sgdm', ... 'MiniBatchSize',10, ... 'MaxEpochs',6, ... 'InitialLearnRate', 1e-4, ... 'Shuffle', 'every-epoch', ... 'ValidationData',augimdsValidation, ... 'ValidationFrequency',3,... 'Verbose',false,... 'Plots','training-progress'); |
9. 신경망 훈련
netTransfer = trainNetwork(augimdsTrain, layers, options) |

10. 신경망 저장
save('netTransfer.mat', 'netTransfer') |
11. 검증영상 분류
[YPred, scores] = classify(netTransfer, augimdsValidation); idx = randperm(numel(imdsValidation.Files),4); figure for i = 1:4 % 4개정도만 가져와서 검증해보기 subplot(2,2,i) I = readimage(imdsValidation,idx(i)); imshow(I) label = YPred(idx(i)); title(string(label)); end |

12. 모델의 정확도 확인
YValidation = imdsValidation.Labels; accuracy = mean(YPred == YValidation) % 정확도는 62.5%로 다소 아쉬운 수치를 보였음 |
13. 실제 우유 사진을 촬영하여 정확도를 확인
I = imread("example.jpg"); figure imshow(I) inputSize = net.Layers(1).InputSize I = imresize(I, inputSize(1:2)); figure imshow(I) [label, scores] = classify(netTransfer, I); label classNames = netTransfer.Layers(end).ClassNames; figure imshow(I) title(string(label) + ", " + num2str(100*scores(classNames == label), 3) + "%"); |
