Programming/python-deep learning

torch.view (파이토치 뷰) 함수 설명

방황하는 데이터불도저 2022. 9. 21. 23:52

# Manual
-> https://pytorch.org/docs/stable/generated/torch.Tensor.view.html

 

torch.Tensor.view — PyTorch 1.12 documentation

Shortcuts

pytorch.org

 

파이토치 함수 중 view 함수는 tensor형태의 데이터의 shape을 바꿔주는 함수이다.

 

원본데이터도 같고, 성분의 수도 같지만 이를 구성하는 shape만 다르게 만들어주는 함수이다.

 

예시는 아래와 같다.

 

# make the random tensor
input = torch.randn(1, 28, 28)

 - 랜덤한 값으로 tensor를 만들어준다.

 

# reshape the tensor using torch.view
n = 1
output1 = input.view(n, -1)   
print(output1.size())                 # torch.Size([1, 784])

output2 = input.view(-1, n)
print(output2.size())                 # torch.Size([784, 1])

 - input 변수(tensor)의 본래 1*28*28이었던 shape을 torch.view 함수를 이용하여 1*784로 만들어준다.
 - (n을 입력한 차원은 n만큼의 성분을 남기고, -1이 있는 차원에 나머지 성분의 수로 채워주는 원리)

 

num = 16
output = input.view(num, -1)
output.size()                 # torch.Size([16, 49])

 - 16을 입력한 차원에는 16개의 성분을 남기고, -1이 있는 차원에 784/16 = 49가 남는것을 볼 수 있다.