[PyTorch] Tensor 기본

이승수·2024년 10월 20일

Tensor : 배열(array)이나 행렬(matrix)과 매우 유사한 특수한 자료구조. PyTorch에서는 텐서를 사용하여 모델의 입력과 출력뿐만 아니라 모델의 매개변수를 부호화(encode) 한다. → Numpy의 ndarray와 비슷함

1. tensor 생성

import torch
from torch import tensor

 # Numpy 배열로 생성
np_array = np.array(data)
x_np = torch.from_numpy(np_array)


 # random 또는 상수(constant) 값을 사용
shape = (2, 3,)
torch.rand(shape)  →  tensor([[0.3904, 0.6009, 0.2566],
                              [0.7936, 0.9408, 0.1332]])
torch.ones(shape)  →  tensor([[1., 1., 1.],
                              [1., 1., 1.]])
torch.zeros(shape)  →  tensor([[0., 0., 0.],
                               [0., 0., 0.]])


 # tensor의 속성
tensor.shape  →  torch.Size([2, 3])
tensor.dtype  →  torch.float32
tensor.device →  cpu

2. tensor 연산

 # tensor 인덱싱, 슬라이싱
tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor) → tensor([[1., 0., 1., 1.],
               			[1., 0., 1., 1.],
        				[1., 0., 1., 1.],
       					[1., 0., 1., 1.]])


 # tensor 합치기
torch.cat([tensor, tensor, tensor], dim=1)
→ tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
          [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
          [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
          [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])


 # 행렬 곱(matrix multiplication) 계산
A @ B
A.matmul(B)
torch.matmul(A, B, out=torch.rand_like(A))

[[1,1],     [[1,1],     [[2,2],
 [1,1]]  x   [1,1]]   =  [2,2]]


 # 요소별 곱(element-wise product) 계산
A * B
A.mul(B)
torch.mul(A, B, out=torch.rand_like(A))

[[1,1],     [[1,1],     [[1,1],
 [1,1]]  x   [1,1]]   =  [1,1]]

3. tensor 차원 변경

t = torch.tensor([[1,2,3], [4,5,6]])
t.unsqueeze(0)
→ tensor([[1,2,3],
		  [4,5,6]]])
t.squeeze()
→ tensor([[1,2,3],
		  [4,5,6]])
t.unsqueeze(1)
→ tensor([[
profile
AI/Data Science

0개의 댓글