[부스트코스] 코칭스터디 9기 : AI Basic 2023 5주차 미션(Q1, Q2, Q3) 변형 문제 풀이

2023. 2. 20. 23:37BOOTCAMP/boostcourse AI BASIC 2023

Q1. MNIST 데이터셋을 직접 Load 해 봅시다. 데이터셋을 로드하고 DataLoader를 구현해 보세요.

 

Input

import torch
import torch.nn as nn
import torchvision.datasets as dset
import torchvision.transforms as transforms 
from torch.utils.data import DataLoader

training_epochs = 18 # training 반복 횟수
batch_size = 150

root = './data'
mnist_train = dset.MNIST (root=root, train=True, transform=transforms, download=True)
mnist_test = dset.MNIST (root=root, train=False, transform=transforms, download=True)

# Create the data loaders
train_loader =

test_loader =

Output

# Create the data loaders
train_loader = DataLoader(dataset=mnist_train,
                          batch_size=batch_size,
                          shuffle=True,
                          num_workers=2)

test_loader = DataLoader(dataset=mnist_test,
                         batch_size=batch_size,
                         shuffle=False,
                         num_workers=2)

Q2. 모델 안의 가중치를 초기화시켜 보세요. 입력 데이터 형태에 맞도록 linear 한 모델을 구성해 보세요.

 

Input

deviec = torch.device('cuda' if torch.cuda.is_available() els 'cpu')
linear = #

# weight init

Output

deviec = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
linear = nn.Linear(784, 10)
nn.init.xavier_uniform_(linear.weight)

Parameter containing:
tensor([[-0.0849, -0.0160,  0.0080,  ..., -0.0018,  0.0273,  0.0192],
        [ 0.0386, -0.0225, -0.0026,  ...,  0.0046, -0.0407,  0.0519],
        [-0.0514,  0.0652,  0.0241,  ...,  0.0142, -0.0524, -0.0423],
        ...,
        [ 0.0509, -0.0055,  0.0080,  ..., -0.0013,  0.0832, -0.0474],
        [ 0.0628,  0.0348,  0.0316,  ..., -0.0253,  0.0556,  0.0490],
        [-0.0090, -0.0812, -0.0138,  ..., -0.0150,  0.0751, -0.0146]],
       requires_grad=True)

 

Q3. 위에서 구현한 모델을 학습시키기 위해서는 loss 함수와 opitmizer가 필요합니다. 제시된 loss 함수와 optimizer를 구현해 보세요.

 

Input

# Loss fn - Cross Entropy Loss
criterion = # 구현

# optimizer - SGD
optimizer = # 구현

 

Output

# Loss function - Cross Entropy Loss
criterion = nn.CrossEntropyLoss()

# Optimizer - SGD
learning_rate = 0.1
optimizer = torch.optim.SGD(linear.parameters(), lr=learning_rate)