[PyTorch] 기초 사용법

Load Packages

1
2
import numpy as np
import torch

Basic

PyTorch 기초 사용법

1
2
3
4
nums = torch.arange(9)
nums.shape
nums.numpy()
nums.reshape(3, 3)
1
2
3
4
randoms = torch.rand((3, 3))
zeros = torch.zeros((3, 3))
ones = torch.ones((3, 3))
torch.zeros_like(ones)

Operations

PyTorch로 수학연산 하기

1
2
3
4
5
6
7
8
9
10
11
nums * 3
nums = nums.reshape((3, 3))
nums + nums

result = torch.add(nums, 10)
result.numpy()

# Out
array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]], dtype=int64)

View

reshape와 같다.

1
2
3
4
5
6
range_nums = torch.arange(9).reshape(3, 3)
range_nums.view(-1)
range_nums.view(1, 9)

# Out
tensor([[0, 1, 2, 3, 4, 5, 6, 7, 8]])

Compile

numpy를 torch tensor로 불러오기

1
2
3
4
5
arr = np.array([1, 1, 1])
arr_torch = torch.from_numpy(arr)
arr_torch.float()

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

Device 설정

1
2
3
4
5
device = 'cuda' if torch.cuda.is_available() else 'cpu'
arr_torch.to(device)

# Out - GPU 사용 가능
tensor([1, 1, 1], device='cuda:0', dtype=torch.int32)

AutoGrad

기울기 구하기

1
2
3
4
5
6
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
print(x.grad_fn)

# Out
<AddBackward0 object at 0x000001FFE2A04148>
1
2
3
4
5
6
7
z = y * y * 3
out = z.mean()
print(z, out)

# Out
tensor([[27., 27.],
[27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward0>)
1
2
3
4
5
6
out.backward()
print(x.grad)

# Out
tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])
Share