Main Content

이 번역 페이지는 최신 내용을 담고 있지 않습니다. 최신 내용을 영문으로 보려면 여기를 클릭하십시오.

분류 신경망을 회귀 신경망으로 변환하기

이 예제에서는 훈련된 분류 신경망을 회귀 신경망으로 변환하는 방법을 보여줍니다.

사전 훈련된 영상 분류 신경망은 1백만 개가 넘는 영상에 대해 훈련되었으며 영상을 키보드, 커피 머그잔, 연필, 각종 동물 등 1,000가지 사물 범주로 분류할 수 있습니다. 분류 신경망은 다양한 영상을 대표하는 다양한 특징을 학습했습니다. 이 신경망은 영상을 입력값으로 받아서 영상에 있는 사물에 대한 레이블과 각 사물 범주의 확률을 출력합니다.

전이 학습은 딥러닝 응용 분야에서 널리 사용됩니다. 사전 훈련된 신경망을 새로운 작업을 학습하기 위한 출발점으로 사용할 수 있습니다. 이 예제에서는 사전 훈련된 분류 신경망을 회귀 작업을 위해 다시 훈련시키는 방법을 보여줍니다.

이 예제에서는 분류를 위해 사전 훈련된 컨벌루션 신경망 아키텍처를 불러오고 분류를 위한 계층을 대체한 다음 회전된 손글씨 숫자의 각도를 예측하도록 신경망을 다시 훈련시킵니다. 선택적으로 imrotate(Image Processing Toolbox™)를 사용하면 예측값을 사용하여 영상 회전을 정정할 수 있습니다.

사전 훈련된 신경망 불러오기

지원 파일 digitsNet.mat에서 사전 훈련된 신경망을 불러옵니다. 이 파일에는 손으로 쓴 숫자를 분류하는 분류 신경망이 들어 있습니다.

load digitsNet
layers = net.Layers
layers = 
  15x1 Layer array with layers:

     1   'imageinput'    Image Input             28x28x1 images with 'zerocenter' normalization
     2   'conv_1'        2-D Convolution         8 3x3x1 convolutions with stride [1  1] and padding 'same'
     3   'batchnorm_1'   Batch Normalization     Batch normalization with 8 channels
     4   'relu_1'        ReLU                    ReLU
     5   'maxpool_1'     2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
     6   'conv_2'        2-D Convolution         16 3x3x8 convolutions with stride [1  1] and padding 'same'
     7   'batchnorm_2'   Batch Normalization     Batch normalization with 16 channels
     8   'relu_2'        ReLU                    ReLU
     9   'maxpool_2'     2-D Max Pooling         2x2 max pooling with stride [2  2] and padding [0  0  0  0]
    10   'conv_3'        2-D Convolution         32 3x3x16 convolutions with stride [1  1] and padding 'same'
    11   'batchnorm_3'   Batch Normalization     Batch normalization with 32 channels
    12   'relu_3'        ReLU                    ReLU
    13   'fc'            Fully Connected         10 fully connected layer
    14   'softmax'       Softmax                 softmax
    15   'classoutput'   Classification Output   crossentropyex with '0' and 9 other classes

데이터 불러오기

데이터 세트에는 손으로 쓴 숫자의 합성 영상과 영상 각각의 회전 각도(단위: 도)가 포함되어 있습니다.

digitTrain4DArrayDatadigitTest4DArrayData를 사용하여 훈련 및 검증 영상을 4차원 배열로 불러옵니다. 출력값 YTrainYValidation은 회전 각도(단위: 도)입니다. 훈련 및 검증 데이터 세트는 각각 5,000개의 영상을 포함합니다.

[XTrain,~,YTrain] = digitTrain4DArrayData;
[XValidation,~,YValidation] = digitTest4DArrayData;

imshow를 사용하여 임의의 훈련 영상 20개를 표시합니다.

numTrainImages = numel(YTrain);
figure
idx = randperm(numTrainImages,20);
for i = 1:numel(idx)
    subplot(4,5,i)    
    imshow(XTrain(:,:,:,idx(i)))
end

Figure contains 20 axes objects. Axes object 1 contains an object of type image. Axes object 2 contains an object of type image. Axes object 3 contains an object of type image. Axes object 4 contains an object of type image. Axes object 5 contains an object of type image. Axes object 6 contains an object of type image. Axes object 7 contains an object of type image. Axes object 8 contains an object of type image. Axes object 9 contains an object of type image. Axes object 10 contains an object of type image. Axes object 11 contains an object of type image. Axes object 12 contains an object of type image. Axes object 13 contains an object of type image. Axes object 14 contains an object of type image. Axes object 15 contains an object of type image. Axes object 16 contains an object of type image. Axes object 17 contains an object of type image. Axes object 18 contains an object of type image. Axes object 19 contains an object of type image. Axes object 20 contains an object of type image.

마지막 계층 바꾸기

신경망의 컨벌루션 계층은 마지막 학습 가능한 계층과 마지막 분류 계층이 입력 영상을 분류하는 데 사용하는 영상 특징을 추출합니다. digitsNet의 이 두 개의 계층 'fc''classoutput'은 신경망이 추출하는 특징을 클래스 확률, 손실 값 및 예측된 레이블로 조합하는 방법에 대한 정보를 포함합니다. 사전 훈련된 신경망을 회귀용으로 다시 훈련시키려면 이 두 계층을 이 작업에 맞게 조정한 새로운 계층으로 바꾸십시오.

마지막 완전 연결 계층, 소프트맥스 계층 및 분류 출력 계층을 크기가 1(응답의 개수)인 완전 연결 계층과 회귀 계층으로 바꿉니다.

numResponses = 1;
layers = [
    layers(1:12)
    fullyConnectedLayer(numResponses)
    regressionLayer];

초기 계층 고정하기

새로운 데이터를 사용하여 신경망을 다시 훈련시킬 준비가 되었습니다. 선택적으로 신경망의 앞쪽 계층의 학습률을 설정하여 이전 계층의 가중치를 "고정"할 수 있습니다. 훈련 중에 trainNetwork는 고정된 계층의 파라미터를 업데이트하지 않습니다. 고정된 계층의 기울기를 계산할 필요가 없으므로 전반부에 있는 여러 계층의 가중치를 고정하면 신경망 훈련 속도를 대폭 높일 수 있습니다. 새로운 데이터 세트의 크기가 작다면 이전 신경망 계층을 고정함으로써 해당 계층이 새로운 데이터 세트에 과적합되지 않도록 할 수도 있습니다.

지원 함수 freezeWeights를 사용하여 처음 12개 계층의 학습률을 0으로 설정합니다.

layers(1:12) = freezeWeights(layers(1:12));

신경망 훈련시키기

신경망 훈련 옵션을 만듭니다. 초기 학습률을 0.001로 설정합니다. 검증 데이터를 지정하여 훈련 중에 신경망 정확도를 모니터링합니다. 훈련 진행 상황 플롯을 켜고 명령 창 출력을 끕니다.

options = trainingOptions('sgdm',...
    'InitialLearnRate',0.001, ...
    'ValidationData',{XValidation,YValidation},...
    'Plots','training-progress',...
    'Verbose',false);

trainNetwork를 사용하여 신경망을 만듭니다. 이 명령은 사용 가능한 경우 호환되는 GPU를 사용합니다. GPU를 사용하려면 Parallel Computing Toolbox™와 지원되는 GPU 장치가 필요합니다. 지원되는 장치에 대한 자세한 내용은 GPU 연산 요구 사항 (Parallel Computing Toolbox) 항목을 참조하십시오. 사용 가능하지 않은 경우 trainNetwork는 CPU를 사용합니다.

net = trainNetwork(XTrain,YTrain,layers,options);

Figure Training Progress (30-Jan-2023 13:05:10) contains 2 axes objects and another object of type uigridlayout. Axes object 1 with xlabel Iteration, ylabel Loss contains 10 objects of type patch, text, line. Axes object 2 with xlabel Iteration, ylabel RMSE contains 10 objects of type patch, text, line.

신경망 테스트하기

검증 데이터에 대한 정확도를 평가함으로써 신경망의 성능을 테스트합니다.

predict를 사용하여 검증 영상의 회전 각도를 예측합니다.

YPred = predict(net,XValidation);

다음을 계산하여 모델의 성능을 평가합니다.

  1. 허용 가능한 오차 범위 내에 있는 예측값의 비율

  2. 예측된 회전 각도와 실제 회전 각도 사이의 RMSE(제곱평균제곱근 오차)

예측된 회전 각도와 실제 회전 각도 사이의 예측 오차를 계산합니다.

predictionError = YValidation - YPred;

실제 각도로부터 허용 가능한 오차 범위 내에 있는 예측값의 개수를 계산합니다. 임계값을 10도로 설정합니다. 이 임계값 내에 있는 예측값의 비율을 계산합니다.

thr = 10;
numCorrect = sum(abs(predictionError) < thr);
numImagesValidation = numel(YValidation);

accuracy = numCorrect/numImagesValidation
accuracy = 0.7532

RMSE(제곱평균제곱근 오차)를 사용하여 예측된 회전 각도와 실제 회전 각도 사이의 차이를 측정합니다.

 rmse = sqrt(mean(predictionError.^2))
rmse = single
    9.0270

숫자 회전 정정하기

Image Processing Toolbox의 함수를 사용하여 숫자를 바로 세우고 함께 표시할 수 있습니다. imrotate(Image Processing Toolbox)를 사용하여 49개의 샘플 숫자를 예측한 회전 각도에 따라 회전합니다.

idx = randperm(numImagesValidation,49);
for i = 1:numel(idx)
    I = XValidation(:,:,:,idx(i));
    Y = YPred(idx(i));  
    XValidationCorrected(:,:,:,i) = imrotate(I,Y,'bicubic','crop');
end

원래 숫자와 회전을 정정한 숫자를 함께 표시합니다. montage(Image Processing Toolbox)를 사용하여 숫자들을 영상 하나에 한꺼번에 표시합니다.

figure
subplot(1,2,1)
montage(XValidation(:,:,:,idx))
title('Original')

subplot(1,2,2)
montage(XValidationCorrected)
title('Corrected')

Figure contains 2 axes objects. Axes object 1 with title Original contains an object of type image. Axes object 2 with title Corrected contains an object of type image.

참고 항목

|

관련 항목