Pytorch/함수들
[PyTorch] torch.randint(...) / Tensor.item() / Tensor.tolist()
대두코기
2023. 1. 16. 18:25
반응형
torch.randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
low(포함, optional)와 high(제외, 필수) 사이에서 uniformly 하게 생성된 랜덤 정수로 채워진 텐서 반환
텐서는 shape를 가지는데, size(튜플형, 필수) 변수의 크기로 정의됨
- low (int, optional) – Lowest integer to be drawn from the distribution. Default: 0.
- high (int) – One above the highest integer to be drawn from the distribution.
- size (tuple) – a tuple defining the shape of the output tensor.
>>> torch.randint(3, 5, (3,))
tensor([4, 3, 4])
>>> torch.randint(10, (2, 2))
tensor([[0, 2],
[5, 5]])
>>> torch.randint(3, 10, (2, 2))
tensor([[4, 5],
[6, 7]])
Tensor.item() → number
- 텐서를 표준 python 숫자형으로 반환
- 크기가 (1, )인 텐서에만 작동됨. 다른 경우는 Tensor.tolist() 사용
- 미분 불가
>>> x = torch.tensor([1.0])
>>> x.item()
1.0
Tensor.tolist() → list or number
- 텐서를 중첩된(nested) 리스트로 반환
- 스칼라의 경우 Tensor.item()과 마찬가지로 standard Python number로 반환됨.
- 텐서는 필요한 경우 자동으로 먼저 CPU로 이동됨
- 미분 불가
>>> a = torch.randn(2, 2)
>>> a.tolist()
[[0.012766935862600803, 0.5415473580360413],
[-0.08909505605697632, 0.7729271650314331]]
>>> a[0,0].tolist()
0.012766935862600803
반응형