import torch
a = torch.arange(12).reshape(3, 4)
row = a[1] # VIEW into a (no copy)
row[:] = 99 # writes into a too!
print(a)
# tensor([[ 0, 1, 2, 3],
# [99, 99, 99, 99],
# [ 8, 9, 10, 11]])
# To get an independent copy:
row_copy = a[1].clone()
row_copy[:] = -1
print(a[1]) # untouched: tensor([99, 99, 99, 99])
torch.gather: 어텐션과 손실 계산의 일꾼·python
import torch
# Pick the predicted-class probability for each sample
logits = torch.randn(4, 5).softmax(-1) # (batch=4, classes=5)
labels = torch.tensor([2, 0, 4, 1])
# We want logits[i, labels[i]] for each i
chosen = logits.gather(1, labels.unsqueeze(1)).squeeze(1)
print(chosen.shape) # torch.Size([4])
# Equivalent (less efficient) loop:
# chosen = torch.tensor([logits[i, labels[i]] for i in range(4)])
torch.randn으로 (4, 5) 로짓 텐서를 만들어. 레이블 텐서 [2, 0, 4, 1]이 주어졌을 때 각 샘플의 정답 클래스 로짓을 Python 반복문과 torch.gather 두 방식으로 추출해. 값이 같은지 확인하고, timeit으로 (1024, 1000) 텐서에서 속도를 비교해. torch.gather가 훨씬 빨라야 해.
Progress
Progress is local-only — sign in to sync across devices.