PyTorch의 view 함수 소개
PyTorch의 view 함수를 쉽게 이해하고, 더 나은 모델 설계 방법을 찾아보세요. 이 글은 AI 번역 기사입니다. 오역이 있을 수 있으니 댓글로 알려주세요.
Created on September 12|Last edited on September 12
Comment
View 함수 입문
작동 방식을 더 잘 이해하기 위해, 다음 코드를 사용한 예제부터 시작해 보겠습니다 view:
def forward(self, x):x = self.pool(F.relu(self.conv1(x)))x = self.pool(F.relu(self.conv2(x)))x = x.view(-1, 16*5*5)x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return x
우리는 무엇을 살펴볼지 먼저 알아볼 것입니다 view function이 실제로 무엇을 하는지, 음수 값을 주면 무엇이 발생하는지, 그리고 이를 어떻게 활용할 수 있는지 view 더 나은 모델을 설계하기 위해서입니다.
자, 시작해 봅시다:
PyTorch의 view 함수 사용 방법
간단히 말해, view 함수는 텐서를 재구성하는 데 사용됨.
예를 들어 설명해 보겠습니다. PyTorch에서 간단한 텐서를 만들어 봅시다:
import torch# tensorsome_tensor = torch.range(1, 36) # creates a tensor of shape (36,)
~이므로 view 은 텐서의 모양을 재구성하는 데 사용되므로, 간단한 재구성을 통해 다음과 같은 형태의 배열을 만들어 봅시다 (3, 12).
some_tensor_reshaped = some_tensor.view(3, 12) # creates a tensor of shape (3, 12)

다른 형태로의 재구성 방법 some_tensor into are (12, 3), (6, 6), (2, 18) 등
하지만 원하는 텐서로 재구성할 수 있는 이유는, 재구성하려는 텐서의 형태를 알고 있기 때문이라는 점에 주의하세요.
만약 당신이 하지 마세요 그 텐서의 형태를 알고 있나요?
서두에서 음수 값에 대해 이야기했던 것을 기억하나요? 바로 여기에서 그 내용이 등장합니다. -1 매개변수는 놀라울 정도로 유용합니다.
some_tensor_reshaped_1 = some_tensor.view(3, -1) # creates a tensor of shape (3, 12)some_tensor_reshaped_2 = some_tensor.view(-1, 12) # creates a tensor of shape (3, 12)
그 -1 매개변수 출력 텐서의 한 차원을 자동으로 계산합니다! PyTorch에서 모델을 만들 때 각 층의 입력과 출력 형태를 지정해야 하므로, 복잡한 네트워크에서는 문제가 될 수 있는데, 이 기능이 그런 상황에서 유용합니다.
View를 사용해 PyTorch 모델을 쉽게 만드는 방법
다음으로, 똑똑한 사용 사례를 보여드리겠습니다. view 신경망 아키텍처를 구성할 때 유용합니다. 이 모델 아키텍처를 살펴보겠습니다:
class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.conv1 = nn.Conv2d(3, 6, 5)self.pool = nn.MaxPool2d(2,2)self.conv2 = nn.Conv2d(6, 16, 5)self.fc1 = nn.Linear(16*5*5, 120) # <---- you can do so only if you know the expected input shape.self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)def forward(self, x):x = self.pool(F.relu(self.conv1(x)))x = self.pool(F.relu(self.conv2(x)))x = x.view(-1, 16*5*5) # <---- notice passing in one value expected in the output shape.x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return x
에서 온 사람 TensorFlow(Keras) 에코시스템에 따라 층을 정의할 때 기대하는 입력 형태를 직접 지정하는 데 익숙하지 않을 수 있습니다. Keras의 고수준 API는 이를 자동으로 처리해 줍니다. 그렇다면 이를 똑똑하게 처리하는 방법이 있을까요?
사용해 봅시다 view 우리에게 유리하게 활용하고 …을 수정합니다 Net 클래스를 조금 다듬어 보겠습니다.
class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.conv1 = nn.Conv2d(3, 6, 5)self.pool = nn.MaxPool2d(2,2)self.conv2 = nn.Conv2d(6, 16, 5)n_size = self._get_conv_output(input_shape) # <---- input_shape is the shape of the input training data.self.fc1 = nn.Linear(n_size, 120)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)def _get_conv_output(self, shape): # returns the size of the output tensor going into Linear layer from the conv block.batch_size = 1input = torch.autograd.Variable(torch.rand(batch_size, *shape))output_feat = self._forward_features(input)n_size = output_feat.data.view(batch_size, -1).size(1) # <---- notice the first use of viewreturn n_sizedef _forward_features(self, x): # returns the feature tensor from the conv blockx = self.pool(F.relu(self.conv1(x)))x = self.pool(F.relu(self.conv2(x)))return xdef forward(self, x):x = self._forward_features(x)x = x.view(x.size(0), -1) # <---- notice the second use of viewx = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return x
혹시 눈치채셨나요? view각 항목을 하나씩 살펴보겠습니다:"
- 에서 _get_conv_output 메서드, output_feat 는 합성곱 블록의 마지막 합성곱/풀링 연산에서 나온 특성 벡터입니다. 이 특성 벡터의 형태는 다음과 같습니다 (batch_size, n, n, channels). …을 사용하면 view(batch_size, -1) 우리는 …을 계산하고 있습니다 n x n x channels 자동으로 계산되어 다음과 같이 반환됩니다 n_size 에서 init 메서드.
- 그 forward 메서드는 입력 학습 데이터를 받으며, 여기에서 그 형태는 다음과 같습니다 (batch_size, image_shape[0], image_shape[1], 3). 합성곱 블록에서 나온 출력 특성 텐서는 _forward_features 메서드는 다음과 같은 형태를 갖습니다 (batch_size, n, n, channels). 이를 다음을 사용해 형태를 바꿀 수 있습니다(평탄화할 수 있습니다) view(x.size[0], -1)
결론
이 글은 다음 내용을 간단히 보여 주기 위한 짧은 포스트였습니다: 어떻게 하면 view 는 텐서의 형태를 바꾸는 데 쓸 수 있으며, 의 마법을 공유하기 위해 사용됩니다 -1 매개변수.
다른 PyTorch 함수에 대한 도움이 필요하다면 댓글로 남겨 주세요. 그 주제로 글을 써 드릴게요!
Add a comment