[PyTorch] 텐서(Tensor)

김희원·2024년 10월 17일
post-thumbnail

Tensor

  • Tensor는 numpy의 ndarray와 유사하며, GPU를 사용한 연산 가속이 가능하다.
  • PyTorch에서는 텐서를 사용하여 모델의 입/출력뿐만 아니라 모델의 매개변수를 부호화하고 GPU를 활용해 연산을 가속화할 수 있다.
  • NumPy와 공통점은 수학 계산, 선형 대수 연산을 비롯해 전치(Transposing), 인덱싱(Indexing), 슬라이싱(slicing), 임의 샘플링(random sampling) 등 다양한 텐서 연산을 진행할 수 있다.
  • NumPy와의 차이점은 CPU에서 사용하는 텐서와 GPU에서 사용하는 텐서의 선언 방식의 차이가 있다.
  • GPU 가속(GPU Acceleration)을 적용할 수 있으므로 CPU 텐서와 GPU 텐서로 나눠지고, 각각의 텐서를 상호 변환하거나 GPU 사용 유/무를 설정한다.

텐서 속성 (Attribute)

텐서의 속성은 텐서의 모양(shape), 자료형(datatype) 그리고 어느 장치(device)에 저장되는지 등을 말한다.

tensor = torch.rand(3, 4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
# OUTPUT
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

텐서 초기화 (Initialization)

데이터로부터 직접 생성하기

data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

NumPy 배열로부터 생성하기

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

다른 텐서로부터 생성하기

명시적으로 재정의하지 않는다면, 인자로 주어진 텐서의 속성(모양(shape), 자료형(datatype))을 유지한다.

x_ones = torch.ones_like(x_data) # x_data 속성 유지
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # x_data 속성 재정의
print(f"Random Tensor: \n {x_rand} \n")

# OUPUT
Ones Tensor:
 tensor([[1, 1],
        [1, 1]])

Random Tensor:
 tensor([[0.8823, 0.9150],
        [0.3829, 0.9593]])

무작위(random) 또는 상수(constant) 값 사용하기

shape은 텐서의 차원(dimension)을 나타내는 튜플(tuple)로, 아래 함수들에서는 출력 텐서의 차원을 결정한다.

shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")

# OUPUT
Random Tensor:
 tensor([[0.3904, 0.6009, 0.2566],
        [0.7936, 0.9408, 0.1332]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

0개의 댓글