import torch
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import torch.nn.init
from torch.utils.data import DataLoader
import random
import matplotlib.pyplot as plt
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(device)
# for reproducibility
torch.manual_seed(777)
if device == 'cuda':
torch.cuda.manual_seed_all(777)
# Test model and check accuracy
with torch.no_grad():
X_test = mnist_test.data.view(len(mnist_test), 1, 28, 28).float().to(device)
Y_test = mnist_test.targets.to(device)
prediction = model(X_test)
correct_prediction = torch.argmax(prediction, 1) == Y_test
accuracy = correct_prediction.float().mean()
print('Accuracy:', accuracy.item())
Accuracy: 0.9848999977111816
# Random sample test
with torch.no_grad():
r = random.randint(0, len(mnist_test) - 1)
img_sample = mnist_test.data[r].view(1, 1, 28, 28).float().to(device)
label_sample = mnist_test.targets[r].to(device)
print('Label: ', label_sample.item())
sample_prediction = model(img_sample)
print('Prediction: ', torch.argmax(sample_prediction, axis=1).item())
plt.imshow(mnist_test.data[r].view(28, 28), cmap='Greys', interpolation='nearest')
plt.show()
Label: 9
Prediction: 9
<Figure size 640x480 with 1 Axes>
3 Assignment
다음 미완성 코드를 활용해 새로운 data를 학습해보자
Training data image
Shape: (?, 3, 64, 128)
여러장의, RGB, 64x128 size의 이미지라고 가정하자
Test data image
Shape: (?, 3, ?, ?)
여러장의, RGB, size를 알 수 없는 이미지라고 가정하자
Labels
image의 class는 2가지 이다
data folder의 구성을 참고하자
Data folder 위치
노트북 github의 data folder 2개를 적당한 위치에 카피해 사용한다
import torch
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import torch.nn.init
from torch.utils.data import DataLoader
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(device)
from google.colab import drive
drive.mount('/content/drive')
# for reproducibility
torch.manual_seed(777)
if device == 'cuda':
torch.cuda.manual_seed_all(777)
# Model
##### 지난 assignment에서 작성한 모델을 활용한다
##### 바뀐 image input에 맞게 변형한다
##### 바뀐 image의 size는 64x128이며, 흑백이 아닌 RGB 3개의 채널임에 유의한다
# parameters
##### 적당히 수정한다
learning_rate =
training_epochs =
# contruct model
model = CNN().to(device)
# define cost/loss & optimizer
criterion = torch.nn.CrossEntropyLoss().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# train
##### 직접 dataset을 만들어 학습할 때 자주 사용되는 함수이니 기능을 숙지한다
##### pytorch 공식 홈페이지에서 관련 함수의 정보를 직접 찾아보는 것을 추천한다
trans = transforms.Compose([transforms.ToTensor()])
train_data = dsets.ImageFolder(root='/content/drive/MyDrive/Colab Notebooks/courses/AI_Appl/train_data', transform=trans)
data_loader = DataLoader(dataset = train_data, batch_size = 8, shuffle = True)
total_batch = len(data_loader)
##### 학습이 이루어지는 loop
##### 지난 source code를 그대로 사용해도 되지만, 연습삼아 직접 작성해보자
# test
##### 직접 dataset을 만들어 학습할 때 자주 사용되는 함수이니 기능을 숙지한다
##### pytorch 공식 홈페이지에서 관련 함수의 정보를 직접 찾아보는 것을 추천한다
trans=transforms.Compose([transforms.Resize((64,128)),transforms.ToTensor()])
test_data = dsets.ImageFolder(root='/content/drive/MyDrive/Colab Notebooks/courses/AI_Appl/test_data', transform=trans)
test_set = DataLoader(dataset = test_data, batch_size = len(test_data))
with torch.no_grad():
##### 결과 test가 이루어지는 loop
##### 지난 source code를 그대로 사용해도 되지만, 연습삼아 직접 작성해보자
cuda
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
Learning started. It takes sometime.
[Epoch: 1] cost = 0.158599436
[Epoch: 2] cost = 0.00020430611
[Epoch: 3] cost = 2.68744279e-05
[Epoch: 4] cost = 5.39911434e-06
[Epoch: 5] cost = 1.20812297e-06
Learning Finished!
Accuracy: 1.0