본문 바로가기
인공지능 AI

Pytorch MNIST Code 분석

by Managemnet S/W saehyeong.woo 2022. 8. 25.
SMALL

파이 토치의 MNIST 글자 인공신경망 분석 코드입니다.

import torch
-> torch 를 import
import torchvision.datasets as dsets
-> pytorch 라이브러리에 포함된 모든 학습 데이터를 불러옴 (MNIST)
import torchvision.transforms as transforms
-> 다양한 이미지 변환을 위해 ex) PIL 이미지 또는 numpy.ndarray(배열)
from torch.utils.data import DataLoader
-> 학습을 위한 방대한 데이터를 미니배치 단위로 정리 -> 학습효율 상승
import torch.nn as nn
-> 신경망 Neural Network 구성
import matplotlib.pyplot as plt
-> MNIST 파일 그래프화
import random
-> 랜덤숫자
USE_CUDA = torch.cuda.is_available()
device = torch.device("cuda" if USE_CUDA else "cpu")
print("다음 기기로 학습합니다:", device)
->false는 CPU True는 cuda(GPU)로 학습
GPU가 학습 성능이 더좋음
random.seed(777)
-> random number를 seed를 정하여 다른사람이 돌려도 똑같은 형태의 random seed
torch.manual_seed(777)
if device == 'cuda':
    torch.cuda.manual_seed_all(777)

CPU 또는 GPU로 학습할 건지 선택하고, 일정 seed를 사용할 건지 입력해줍니다.

training_epochs=30
-> 6만개의 데이터를 15번 훈련 epochs
batch_size=100
-> 6만개의 데이터를 15번 훈련한것을 100size로 미니 배치 (학습시간이 오래걸림)
mnist_train = dsets.MNIST(root='MNIST_data/', -> MNIST data를 받을 경로
                          train=True, -> true는 훈련데이터, false는 테스트 데이터
                          transform=transforms.ToTensor(), -> 현재 데이터 파이토치 변환
                          download=True) -> MNIST 데이터가 없으면 다운로드
mnist_test = dsets.MNIST(root='MNIST_data/',
                         train=False,
                         transform=transforms.ToTensor(),
                         download=True)

data_loader = DataLoader(dataset=mnist_train, -> loader할 대상이 Mnist_train
                                          batch_size=batch_size, -> 배치 크기는 100
                                          shuffle=True, -> 미니배치로 나눈것을 셔플 True
                                          drop_last=True)-> 마지막 배치 데이터 버림
linear = nn.Linear(784, 10, bias=True).to(device)
-> Y=Wx+b의 형태 2차원 그래프 28*28= 784의 그래프 배치, to(device)는 CPU 수행
criterion = nn.CrossEntropyLoss().to(device)
-> P,Q의 두확률간의 계산 CrossEntropyLoss
optimizer = torch.optim.SGD(linear.parameters(), lr=0.1)
-> Optimizer로 인해 최적화된 예측값 구현

for epoch in range(training_epochs):
    avg_cost = 0 -> 평균값 변수 초기화
    total_batch = len(data_loader) -> 배치를 data_loader의 길이만큼
    for X, Y in data_loader:
        X = X.view(-1, 28 * 28).to(device) -> X의 데이터를 28*28로 변환
        Y = Y.to(device) -> Y는 0~9의 한자리수로
        optimizer.zero_grad() -> 최적화된 값이 계속 학습하면서 누적이 될수있기에 grad값을 
        초기화 ( epoch 사용시)
        hypothesis = linear(X) -> X값을 linear에 넣어 분류결과를 도출
        cost = criterion(hypothesis, Y) -> 분류결과와 Y를 비교하여 Cost 계산
        cost.backward() -> cost 계산값의 기울기
        optimizer.step() -> optimizer를 업데이트
 
        avg_cost += cost / total_batch -> total_batch를 cost로 나누어 avg_cost값
    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))
print('Learning finished')


epoch을 설정하고 글자 데이터를 훈련

epoch 및 cost 결과

with torch.no_grad(): -> autograd를 끄고 메모리사용량을 줄이고 연산속도를 높임.
    X_test = mnist_test.test_data.view(-1, 28 * 28).float().to(device)
    Y_test = mnist_test.test_labels.to(device) -> 테스트 데이터를 불러옴
    prediction = linear(X_test) -> 예측하는값을 X_test를 linear에 넣어줌
    correct_prediction = torch.argmax(prediction, 1) == Y_test
    ->가장 높은 가능성의 클래스를 뽑아줌 (argmax)
    accuracy = correct_prediction.float().mean()
    -> 정확도 계산, mean()은 평균계산
    print('Accuracy:', accuracy.item())
    r = random.randint(0, len(mnist_test) - 1)
    -> 0~Mnist_test의 자료 길이 -1 까지의 범위의 수 random 추출
    X_single_data = mnist_test.test_data[r:r + 1].view(-1, 28 * 28).float().to(device) 
    Y_single_data = mnist_test.test_labels[r:r + 1].to(device)

print('Label: ', Y_single_data.item())
-> 실제 Test 라벨
single_prediction = linear(X_single_data)
print('Prediction: ', torch.argmax(single_prediction, 1).item())
    plt.imshow(mnist_test.test_data[r:r+1].view(28,28),cmap='Greys',interpolation='bilinear') -> Greys 배경-> 흰, 숫자-> 검
plt.show()
-> mataplotlib의 그래프 숫자 show

훈련한 데이터를 그래프에 넣어 결과출력

 

정확도가 0.87%로 높은 수치는 아니다.

LIST

'인공지능 AI' 카테고리의 다른 글

LSTM Kospi Prediction Analysis  (1) 2022.08.26
인공신경망을 이용한 USB 인식 시스템  (0) 2022.08.26
USB Image ResNet Modeling  (0) 2022.08.26