곰퓨타의 SW 이야기

Lab 07-2 MNIST Introduction 본문

인공지능/부스트코스_파이토치로 시작하는 딥러닝 기초

Lab 07-2 MNIST Introduction

곰퓨타 2021. 2. 22. 18:17

이 강의를 참고하며 작성하였다!!

www.boostcourse.org/ai214/lecture/42292

 

파이토치로 시작하는 딥러닝 기초

부스트코스 무료 강의

www.boostcourse.org

 

 

What is MNIST ?

MNIST : 손으로 쓰여진 0-9의 숫자 dataset

우체국에서 편지를 받으면 921-13과 같은 숫자가 적혀있다. 이러한 숫자를 자동으로 인식하기 위하여 만든 것이다.

 

<구성>

 

<Example of MNIST>

 

28 x 28 로 이루어진 image이고, 1 channel로 된 gray image(흑백)이다.

이는 0에서 9까지의 digits로 이루어져있다. 

for X,Y in data_loader :
	# reshape input image into [batch_size by 784]
    # Label is not one-hot encoded
    X = X.view(-1,28*28)	# 28*28을 784의 사이즈로 바꾸어준다.

 

Code : MNIST Classifier

 

iteration : batch size를 몇 번 도느냐

 

ex ) 1000개의 training set이 있는데 batch ssize가 500이면 2개의 batch가 있음. -> 2 iteration이 끝나면 1 epoch이 끝났다고 한다.

 

 

import torch
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import random

# parameters
training_epochs = 15
batch_size = 100

# MNIST dataset
# root : 어느 경로에 MNIST 데이터가 있는지
# train : True - trainset을 불러올지 
#         False - testset을 불러올지
# transform : MNIST 이미지를 불러올 때 어떤 transform을 불러올지
#             pytorch : image는 0-1사이의 값을 갖고 Channel, Height, width순으로 값을 가짐
#             image : 0-255의 값으로 가지고 Height, width, channel 순서로 되어있음.
# toTensor는 image를 pytorch 값으로 변경해준다.
#download : MNIST가 root에 없으면 다운을 받겠다는 의미 
mnist_train = dsets.MNIST(root='MNIST_data/',
                          train=True,
                          transform=transforms.ToTensor(),
                          download=True)

mnist_test = dsets.MNIST(root='MNIST_data/',
                         train=False,
                         transform=transforms.ToTensor(),
                         download=True)
                         

# dataset loader
# dataset : 어떤 데이터를 로드할지
# batch_size : 몇개씩 잘라서 불러올지
# shuffle : 60000만장 중 100개씩 순서를 무작위로 가져올지에 대한 여부
# drop_last : batch size로 나누었을때 뒤에 개수가 안맞아떨어지는 경우 사용하지 않으면 True
data_loader = torch.utils.data.DataLoader(dataset=mnist_train,
                                          batch_size=batch_size,
                                          shuffle=True,
                                          drop_last=True)
                                          
                                          


# MNIST data image of shape 28 * 28 = 784
linear = torch.nn.Linear(784, 10, bias=True).to(device)


# define cost/loss & optimizer
criterion = torch.nn.CrossEntropyLoss().to(device)    # Softmax is internally computed.
optimizer = torch.optim.SGD(linear.parameters(), lr=0.1)

for epoch in range(training_epochs):
    avg_cost = 0
    total_batch = len(data_loader)
    # data 불러오기
    # X : mnist image
    # Y : label (0-9)
    for X, Y in data_loader:
        # reshape input image into [batch_size by 784]
        # label is not one-hot encoded
        # x를 784로 바꾸어줌 (view를 활용하여!)
        X = X.view(-1, 28 * 28).to(device)
        Y = Y.to(device)

        
        optimizer.zero_grad()
        # X를 linear에 넣으면 분류 결과가 나옴
        hypothesis = linear(X)
        # 분류 결과와 Y비교하여 cost 계산해냄
        cost = criterion(hypothesis, Y)
        cost.backward()
        optimizer.step()
        
        avg_cost += cost / total_batch

    print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))

print('Learning finished')



# Test
# Test the model using test sets
# 이 범위 안에서느 gradient 계산을 안하겠다는 의미
with torch.no_grad():
    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)
    # 예측된 결과와 실제 test label 간의 맞는 정도
    correct_prediction = torch.argmax(prediction, 1) == Y_test
    accuracy = correct_prediction.float().mean()
    print('Accuracy:', accuracy.item())

    
    # image로 보여주려함
    # Get one and predict , 무작위로 image하나를 뽑아서 예측을 해보기 위함
    r = random.randint(0, len(mnist_test) - 1)
    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())
    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='nearest')
    plt.show()

 

 

 

 

'인공지능 > 부스트코스_파이토치로 시작하는 딥러닝 기초' 카테고리의 다른 글

Lab 08-2 Multi layer Perceptron  (0) 2021.02.22
Lab 08-1 Perceptron  (0) 2021.02.22
Lab 07-1 Tips  (0) 2021.02.17
Lab-06 Softmax Classification  (0) 2021.02.17
Lab-05 Logistic Regression  (0) 2021.02.15
Comments