[PyTorch] Lab09.3 - Dropout

Yun Geonil·2021년 2월 27일
1

📌 학습 목표


  • Dropout
  • Code: mnist_nn_dropout

Dropout

이전 포스트 중 overfitting에 대해 설명했었다. overfitting을 해결하기 위한 방법들은 여러가지 있었다.

  • More training data
  • Reduce features
  • Regularization
  • Dropout

이 중 Dropout에 대해 알아보자.

Dropout은 학습 시 무작위로 몇개의 노드(뉴런)를 학습시키지 않는 것이다.

Code: mnist_nn_dropout

dropout을 이용하여 mnist 데이터를 학습시켜본다.

  • hyper parameter를 정해준다.
# hyper parameter
training_epochs = 15
batch_size = 100
learning_rate = 0.001
drop_prob = 0.3 # dropout percentage
  • nn.Dropout() 을 사용해 Dropout 계층을 정의한다. 이때, p 매개변수에는 dropout 비율이 들어간다.
class SoftmaxClassifierModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(28*28, 256, bias=True).to(device)
        self.linear2 = nn.Linear(256, 256, bias=True).to(device)
        self.linear3 = nn.Linear(256, 10, bias=True).to(device)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(p=drop_prob)
        
        nn.init.xavier_uniform_(self.linear1.weight)
        nn.init.xavier_uniform_(self.linear2.weight)
        nn.init.xavier_uniform_(self.linear3.weight)
        
        self.model = nn.Sequential(self.linear1, self.relu, self.dropout,
                                   self.linear2, self.relu, self.dropout,
                                   self.linear3).to(device)
    
    def forward(self, x):
        return self.model(x)
  • 모델을 정의하고, Lossoptimizer를 설정한다.
model = SoftmaxClassifierModel()
criterion = torch.nn.CrossEntropyLoss().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
  • model.train() 을 이용해 model을 훈련 모드로 set한다. 훈련 모드에서는 dropout이 활성화 된다.
total_batch = len(data_loader)
model.train()    # set the model to train mode (dropout=True)
for epoch in range(training_epochs):
    avg_cost = 0

    for X, Y in data_loader:
        X = X.view(-1, 28 * 28).to(device)
        Y = Y.to(device)

        optimizer.zero_grad()
        hypothesis = model(X)
        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')
'''
Epoch: 0001 cost = 0.326735049
Epoch: 0002 cost = 0.140616640
Epoch: 0003 cost = 0.109323323
Epoch: 0004 cost = 0.089051023
Epoch: 0005 cost = 0.076372094
Epoch: 0006 cost = 0.066639036
Epoch: 0007 cost = 0.061388444
Epoch: 0008 cost = 0.055603977
Epoch: 0009 cost = 0.052779272
Epoch: 0010 cost = 0.047599990
Epoch: 0011 cost = 0.043720163
Epoch: 0012 cost = 0.042121254
Epoch: 0013 cost = 0.040746879
Epoch: 0014 cost = 0.037326634
Epoch: 0015 cost = 0.035204429
Learning finished
'''
  • model.eval()을 통해 평가 모드로 바꿔준다. 이때는 dropout이 비활성화 된다.
with torch.no_grad():
    model.eval()    # set the model to evaluation mode (dropout=False)

    X_test = mnist_test.test_data.view(-1, 28 * 28).float().to(device)
    Y_test = mnist_test.test_labels.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.9836999773979187
'''

이전보다 더욱 성능이 증가했다.

0개의 댓글