Torch Practice

BERT·2023년 5월 27일
0

Perception

목록 보기
2/20

Tensor practice

생성

정수형 tensor 생성

a = torch.tensor([1], dtype=torch.int16)

tensor size

a.shape

tensor 타입

a.dtype

tensor 디바이스

a.device

연산

tensor 덧셈

 a = torch.tensor([3, 2])
 b = torch.tensor([5, 3])
 
 a+b

tensor 각 원소 합

a.sum()

tensor 행렬 곱

torch.matmul(a, b)

tensor element-wise 곱

torch.mul(a, b)

크기 변형

tensor view
(1,) \rarr (2,3)

a = torch.tensor([2, 4, 5, 6, 7, 8])
b = a.view(2, 3)

tensor transpose

bt = b.t()

슬라이싱

1열

a = torch.arange(1, 13).view(4, 3)
print(a[:, 0])

1행

print(a[0, :])

넘파이로 변형

tensor \rarr numpy

a = torch.arange(1, 13).view(4, 3)
a_np = a.numpy()

numpy \rarr tensor

b = np.array([1, 2, 3])
bt = torch.from_numpy(b)

결합

a = torch.arange(1, 10).view(3, 3)
b = torch.arange(10, 19).view(3, 3)
c = torch.arange(19, 28).view(3, 3)

abc = torch.cat([a, b, c], dim=0)
a = torch.arange(1, 10).view(3, 3)
b = torch.arange(10, 19).view(3, 3)
c = torch.arange(19, 28).view(3, 3)

abc = torch.cat([a, b, c], dim=1)

스택

a = torch.arange(1, 10).view(3, 3)
b = torch.arange(10, 19).view(3, 3)
c = torch.arange(19, 28).view(3, 3)

abc = torch.stack([a, b, c], dim=0)

전치

특정 2개 차원 변경

a = torch.arange(1, 10).view(3, 3)
at = torch.transpose(a, 0, 1)

Permute

전체 차원 교체

b = torch.arange(1, 25).view(4, 3, 2)
bt = torch.transpose(b, 0, 2)
bp = b.permute(2, 0, 1)

0개의 댓글