티스토리 뷰

https://wikidocs.net/184983

 

07-04 자연어 처리를 위한 1D CNN(1D Convolutional Neural Networks)

합성곱 신경망을 자연어 처리에서 사용하기 위한 1D CNN을 이해해보겠습니다. ## 1. 2D 합성곱(2D Convolutions) 앞서 합성곱 신경망을 설명하며 합성곱 연산…

wikidocs.net

PyTorch로 시작하는 딥 러닝 입문이라는 위키독스에 있는 자연어 처리를 위한 1D CNN 연습문제를 풀어보겠습니다. (Pytorch conv1D 예제)

먼저 필요한 라이브러리를 임포트합니다. 

import torch
import torch.nn.init

device = 'cuda' if torch.cuda.is_available() else 'cpu'

신경망 설계하기

- 샘플 데이터의 문장 길이는 9, 임베딩 벡터 차원은 6

- 크기가 4인 커널 2개, 크기가 3인 커널 2개, 크기가 2인 커널 2개 사용

- 각각 6차원 벡터 2개, 7차원 벡터 2개, 8차원 벡터 2개를 얻음.

- 맥스 풀링 후엔 스칼라 값을 6개 얻음.

- 6개의 스칼라 값을 concat 해서 하나의 벡터로 만듦.

- 이진 분류 수행

 

class 로 모델 설계

class NLP_CNN(torch.nn.Module):  # torch.nn.Module 클래스를 상속(기능을 물려) 받음.
  def __init__(self):  # 생성자. 객체가 생성될 때 자동으로 생성되는 메소드. 초기값 설정.
    super(NLP_CNN, self).__init__()  # 부모 클래스의 생성자. 초기값 설정.
    
    self.layer1 = torch.nn.Sequential(
        torch.nn.Conv1d(in_channels=6, out_channels=1, kernel_size=4, stride=1),  # 여기서 in_channels=6은 임베딩 차원.
        torch.nn.ReLU(),
        torch.nn.MaxPool1d(kernel_size=6)  # Conv1d 후 6차원의 벡터가 나옴. 
    )

    self.layer2 = torch.nn.Sequential(
        torch.nn.Conv1d(in_channels=6, out_channels=1, kernel_size=3, stride=1),
        torch.nn.ReLU(),
        torch.nn.MaxPool1d(kernel_size=7) # Conv1d 후 7차원의 벡터가 나옴. 
    )

    self.layer3 = torch.nn.Sequential(
        torch.nn.Conv1d(in_channels=6, out_channels=1, kernel_size=2, stride=1),
        torch.nn.ReLU(),
        torch.nn.MaxPool1d(kernel_size=8) # Conv1d 후 8차원의 벡터가 나옴. 
    )

    self.fc = torch.nn.Linear(in_features=6, out_features=2, bias=True)
    torch.nn.init.xavier_uniform_(self.fc.weight)  # self.fc 한정으로 가중치 초기화

  def forward(self, x):
    out1 = self.layer1(x)  # 크기가 4인 커널에서 나온 벡터. 형태는 tensor([1])와 같은 형태.
    out2 = self.layer1(x)  
    out3 = self.layer2(x)  # 크기가 3인 커널에서 나온 벡터.
    out4 = self.layer2(x)  
    out5 = self.layer3(x)  # 크기가 2인 커널에서 나온 벡터. 
    out6 = self.layer3(x)  
    out = torch.cat((out1, out2, out3, out4, out5, out6), dim=1)  # ex. tensor([1, 2, 3, 4, 5, 6])
    out = self.fc(out)
    return out

 

 

NLP_CNN 모델 정의

model = NLP_CNN().to(device)

 

비용함수와 optimizer 정의

# 비용함수 정의
criterion = torch.nn.CrossEntropyLoss().to(device)  # 비용함수에 소프트맥스가 포함이 되어져있음.
# optimizer 정의
optimizer = torch.optim.Adam(params=model.parameters(), lr=0.1)

 

sample data 딱 하나 만들어서 동작되는지 확인함. 

X = torch.tensor([[11, 12, 13, 14, 15, 16, 17, 18, 19],
                  [21, 22, 23, 24, 25, 26, 27, 28, 29],
                  [31, 32, 33, 34, 35, 36, 37, 38, 39],
                  [41, 42, 43, 44, 45, 46, 47, 48, 49],
                  [51, 52, 53, 54, 55, 56, 57, 58, 59],
                  [61, 62, 63, 64, 65, 66, 67, 68, 69]])  # 문장의 길이가 9이고 임베딩차원이 6인 문장. 
X = X.type(torch.FloatTensor)
Y = torch.tensor([1])

X = X.to(device)
Y = Y.to(device)

optimizer.zero_grad()  # optimizer zero 로 초기화
hypothesis = model(X)
cost = criterion(hypothesis, Y) # cost 구함
cost.backward() # cost에 대한 backward 구함
optimizer.step()  # optimizer 업데이트.

print ("hypothesis:", hypothesis)
print ("Y:", Y)
print ("cost:", cost)
hypothesis: tensor([[-1475.2156,  -277.8548]], grad_fn=<AddmmBackward0>)
Y: tensor([1])
cost: tensor(0., grad_fn=<NllLossBackward0>)

 

'torch' 카테고리의 다른 글

다층 퍼셉트론으로 MNIST 분류하기 (실습 코드 최신 버전)  (0) 2023.01.15
XOR gate  (0) 2023.01.15
댓글
Total
Today
Yesterday
공지사항
최근에 올라온 글
글 보관함