AI Codes/PyTorch

PyTorch Random Number Generating

아르카눔 2025. 4. 20. 17:47

 

파이토치에서 랜덤 넘버를 만들 경우가 있는데 몇가지 자주 쓰던 방법을 정리한다.

 

추가적으로 [1, 2, 3, 4, 5]와 같은 연속된 수의 텐서를 만드는 방법과 순열을 적용하는 방법도 추가한다.

 

다음의 함수들을 다룬다.

 

  • rand
  • rand_like
  • randint
  • randint_like 
  • randn
  • randn_like
  • normal
  • randperm
  • arange
  • linspace

 

 

 

1. torch.rand()와 torch.rand_like()

 

[0, 1) 의 범위의 uniform dist 유니폼 분포에서 뽑는다.

 

rand_like는 zeros_like처럼 목표가 되는 텐서와 똑같은 형태로 random number generating (이하 RNG) 난수 생성을 수행한다.

 

import torch

print(torch.rand(4))

torch.rand(2, 3)

>> 
tensor([0.9250, 0.5086, 0.9940, 0.3761])
tensor([[0.0458, 0.9643, 0.2889],
        [0.0346, 0.3806, 0.2786]])


a = torch.Tensor([1, 2, 3])

b = torch.rand_like(a)
print(a)
print(b)

>> tensor([1., 2., 3.])
tensor([0.2670, 0.9020, 0.4089])

a = torch.Tensor([[1, 2, 3],
                 [4, 5, 6]])

b = torch.rand_like(a)

print(a)
print(b)

>>
tensor([[1., 2., 3.],
        [4., 5., 6.]])
tensor([[0.3318, 0.1814, 0.3899],
        [0.6909, 0.8665, 0.0063]])

 

 

2. torch.randint()와 torch.rand_like()

 

rand와 다르게 정수만 뽑는다. 

 

인자로 가장 작은 값인 low, 가장 큰 값인 high를 받는다.  

 

이때 실제로 나오는 가장 큰 값은 high 보다 하나 작은 값인 (high - 1)이다. 

 

인덱싱처럼 작동한다. 

 

정수기 때문에 당연하게도 음의 정수도 포함한다.  

 

a = torch.randint(10, (2, 3))
print(a)

>> tensor([[2, 1, 9],
        [9, 9, 7]])

b = torch.randint_like(a, 10, 20)
print(b)

>>
tensor([[13, 18, 10],
        [14, 13, 16]])

c = torch.randint(5, 10, (3,))

print(c)

>> tensor([8, 7, 5])

d = torch.randint(-10, 10, (5, ))

print(d)

>> tensor([  2,   9,  -3, -10,   8])

 

 

3. torch.randn()와 torch.normal

 

torch.randn()은 Standard Normal dist N(0, 1)에서 데이터를 뽑는다.

 

torch.normal(mean, std)는 N(mean, std^2)의 분포에서 데이터를 뽑는다.

 

두 방법 모두 정규분포에서 뽑기 때문에 모든 실수 값이 나올 수 있다.

 

a = torch.randn(2, 3)

print(a)
>>
tensor([[-1.4788, -1.8331,  0.3906],
        [-0.9831, -0.1389,  0.6708]])

b = torch.normal(0, 1, (2, 3))
print(b)
>> tensor([[-0.7708, -0.8627,  1.8578],
        [ 0.3269, -0.2307,  0.5221]])

c = torch.normal(3, std=10, size=(2, 3))

print(c)

>> 
tensor([[20.7589, -9.0360, -2.3861],
        [18.9746,  0.4964, -5.3330]])

 

 

4. torch.arange

 

start, end, step에 따라서 연속적인 등차 수열을 생성한다.

 

step은 수열의 등차다.  

 

torch.randint 처럼 end는 포함하지 않는다. 

 

start의 디폴트 값은 0이고 step의 기본 값은 1이다. 

 

step은 실수가 올 수 있다. 

 

a = torch.arange(5)
print(a)

>> tensor([0, 1, 2, 3, 4])

b = torch.arange(5, 10)
print(b)

>> tensor([5, 6, 7, 8, 9])

c = torch.arange(1, 2.5, 0.5) # 실수 step
print(c)

>> tensor([1.0000, 1.5000, 2.0000])

 

 

5. torch.linspace

 

start, end, step에 따라서 연속적인 등차 수열을 생성한다.

 

arange와의 차이점은 arange는 step이 등차를 의미하는데,

 

linspace에서는 지정된 수열의 개수인 steps에 따라서 등차가 되는 간격을 자동으로 계산해서 적용한다.

 

그리고 end 값을 포함해서 생성한다. 

 

a = torch.linspace(0, 1, steps=5)
print(a)

>> tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])

b = torch.linspace(0, 10, steps=5, dtype=torch.int32)

print(b)

>> tensor([ 0,  2,  5,  7, 10], dtype=torch.int32)

c = torch.linspace(0, 10, steps=5, dtype=torch.float32)

print(c)

>> tensor([ 0.0000,  2.5000,  5.0000,  7.5000, 10.0000])

 

 

6. torch.randperm

 

n을 주면 0부터 n - 1 까지의 정수에 대한 n - 1 크기의 순열을 반환한다.

 

a = torch.randperm(5)
print(a)

>> tensor([0, 2, 3, 1, 4])

 

 

 

 

 

 

 

 

References:

https://pytorch.org/docs/stable/torch.html#random-sampling