[Pytorch] 01. Tutorial 01

Hyun·2022년 5월 12일
0

Pytorch tutorial

목록 보기
1/1

Tensor

Tensor(텐서) : array(배열)이나 matrix(행렬)과 매우 유사한 자료구조

  • Numpy의 ndarray와 유사
    • Tensor는 GPU나 다른 HW 가속기에서 실행할 수 있다.
  • Automatic differentiation ( 자동 미분 )에 최적화 되어있음
  • 기본적으로 CPU에 생성되지만, .to 메소드를 통해 GPU에서도 연산을 실행할 수 있다.
    • device간에 큰 tensor를 copy하는 것은 시간과 memory 측면에서 비용이 많이들 수 있다.
    	# GPU가 존재하면 tensor를 이동
    	if torch.cuda.is_available():
      	tensor = tensor.to("cuda")

Tensor Initialize

List -> Tensor

import torch
import numpy as np
    
# list -> tensor
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

numpy array <-> tensor


# numpy array -> tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
    
# tensor -> numpy array
new_np_array = x_np.numpy()

tensor -> another tensor

# tensor -> another tensor
x_ones = torch.ones_like(x_data)	# x_data의 shape, type은 유지. value는 1
# print :  tensor([[1, 1], [1, 1]])
    
x_rand  = torch.rand_like(x_data, dtype=torch.float)	# x_data의 shape, type은 유지. value는 float type 중에서 random으로
# print :   tensor([[0.0965, 0.2738], [0.9675, 0.2934]])
    

shape으로 tensor

shape = (2,3,)
rand_tensor = torch.rand(shape)
# print : tensor([[0.8398, 0.8787, 0.4099], [0.6517, 0.2316, 0.1294]])
ones_tensor = torch.ones(shape)
# print : tensor([[1., 1., 1.], [1., 1., 1.]])
zeros_tensor = torch.zeros(shape)
# print : tensor([[0., 0., 0.], [0., 0., 0.]])

Tensor Attribute

tensor = torch.rand(3,4)
tensor.dim()		# 2 ( rank, 차원 )
tensor.shape		# torch.Size([3, 4])
tensor.size()		# torch.Size([3, 4])
tensor.dtype		# ex. torch.float32
tensor.device		# cpu or cuda(gpu)

Tensor Operation

slice

tensor = torch.ones(4, 4)
# print : tensor([[1., 1., 1., 1.],
#				  [1., 1., 1., 1.],
#				  [1., 1., 1., 1.],
#			      [1., 1., 1., 1.]])
  
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
# print : 3가지 모두 tensor([1., 1., 1., 1.])
  
tensor[:,1] = 0
# print : tensor([[1., 0., 1., 1.],
# 		          [1., 0., 1., 1.],
# 		          [1., 0., 1., 1.],
#			      [1., 0., 1., 1.]])

concat

t1 = torch.cat([tensor, tensor, tensor], dim=1)
# print : 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.]])

stack

torch.stack

Arithmetic operations ( 산술 연산 )

추가 연산

# 두 텐서 간의 행렬 곱(matrix multiplication)을 계산합니다. y1, y2, y3은 모두 같은 값을 갖습니다.
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)


# 요소별 곱(element-wise product)을 계산합니다. z1, z2, z3는 모두 같은 값을 갖습니다.
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
agg = tensor.sum()	# 요소가 1개인 tensor ( scalar)
agg_item = agg.item()	# tensor ( scalar ) -> python number value
print(agg_item, type(agg_item))
# 12.0 <class 'float'>

in-place 연산 (ex. tensor.add_(5))

  • in-place ( 바꿔치기 ) 연산은 연산 결과를 피연산자 ( operand )에 저장하는 연산이며 _접미사를 갖는다.
  • 메모리를 절약할 수 있지만, history(기록)이 즉시 삭제되기 때문에 도함수(derivative) 계산에 문제가 발생할 수 있다. -> 사용 x
    ex. x.copy(y), x.t() : x를 변경
print(f"{tensor} \n")
# tensor([[1., 0., 1., 1.],
#         [1., 0., 1., 1.],
#         [1., 0., 1., 1.],
#         [1., 0., 1., 1.]])

tensor.add_(5)

print(tensor)
# tensor([[6., 5., 6., 6.],
#         [6., 5., 6., 6.],
#         [6., 5., 6., 6.],
#         [6., 5., 6., 6.]])

bridge ( 변환 )

  • tensor -> numpy
t = torch.ones(5)
# t: tensor([1., 1., 1., 1., 1.])

n = t.numpy()
# n: [1. 1. 1. 1. 1.]

bridge

t.add_(1)
# t: tensor([2., 2., 2., 2., 2.])
n = t.numpy()
# n: [2. 2. 2. 2. 2.]
  • numpy -> tensor
n = np.ones(5)
t = torch.from_numpy(n)

bridge

np.add(n, 1, out=n)
# t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
# n: [2. 2. 2. 2. 2.]

참조

pytorch tutorial korea
wikidocs, Pytorch로 시작하는 딥러닝

0개의 댓글