Torch 사용법 (1) tensor 연산

김준오·2021년 9월 2일

numpy와 거의 유사한 문법이다

pytorch란?
기존 수치 연산 라이브러리인 numpy를 딥러닝 연구목적으로 gpu에서도 사용하고자 탄생하게된 딥러닝 플랫폼이다.

tensor?

numpy의 다차원 배열 (ndarray) 같은거라고 보면된다.
하지만 gpu사용이 가능한 더 빠르게 연산할수있는 그런녀석

numpy to tensor

torch.from_numpy(n)

a = np.ones(5000)
b = torch.from_numpy(a)
np.add(a,10, out=a)

print(a)
print(b)
[11. 11. 11. ... 11. 11. 11.]
tensor([11., 11., 11.,  ..., 11., 11., 11.], dtype=torch.float64)

tensor to numpy

tensor.numpy(t)

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

torch.ones()

tensor = torch.ones(4, 4)
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])

Slicing


tensor[:,1] = 0

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor[2:,1] = 0

tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor[:2,1] = 0

tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])

torch.rand(5,3)

x = torch.rand(5,3)
print(x)
tensor([[0.9390, 0.6715, 0.8244],
        [0.6373, 0.9764, 0.4452],
        [0.9505, 0.8122, 0.6476],
        [0.0674, 0.4005, 0.5773],
        [0.1729, 0.0376, 0.2119]])

텐서 곱하기

 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor * tensor = tensor.mun(tensor) 원소별 곱

tensor * tensor
 tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor @ tensor.T = tensor.matmul(tensor.T) 행렬곱

tensor @ tensor.T
 tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
profile
jooooon

0개의 댓글