Python/numpy & Pytorch

[Numpy] 넘파이 난수 생성하기

파송송 2023. 5. 4. 23:30
728x90

Numpy에서는 난수를 생성하는 method들이 있음


random.rand()

0~1 사이의 랜덤 한 실수를 생성한다.(1은 포함되지 않음)

rand() 안에 아무것도 안 나오면 스칼라값이 나오고 나머지는 입력한 크기에 맞게 벡터값이 나온다.

import numpy as np

test = np.random.rand(3,4)
print(test)
[[0.72298894 0.53186953 0.52394924 0.89806408]
 [0.56625083 0.34967767 0.75511065 0.16174391]
 [0.19854568 0.90354496 0.07178789 0.59389605]]

randint(min, max)

min, max 사이의 범위의 정수를 랜덤 하게 반환해 준다.(max는 포함되지 않음)

size를 통해 벡터의 크기를 지정할 수 있다.

import numpy as np

test = np.random.randint(0, 5, size=(10,10))
print(test)
[[3 1 3 3 0 1 2 1 3 0]
 [3 4 0 4 2 2 4 3 3 4]
 [4 1 0 4 4 1 1 0 2 2]
 [4 4 0 4 0 4 3 2 0 2]
 [4 4 2 4 2 4 1 1 2 1]
 [3 0 1 1 1 2 2 1 1 2]
 [3 2 4 4 4 3 4 4 4 3]
 [1 1 0 1 1 4 4 4 1 1]
 [4 0 1 1 1 0 2 0 4 4]
 [1 3 0 2 4 4 4 4 4 2]]

randn(n)

정규분포를 따르는 난수를 반환해준다.

 

import numpy as np

test = np.random.randn(3,4)
print(test)
[[-1.97049195  0.78388403  1.31954062 -0.53624647]
 [-0.93932758 -0.71448687  1.66879837 -0.21069159]
 [ 0.36444801 -0.67027248 -1.16706086 -0.36836897]]

import numpy as np
import matplotlib.pyplot as plt

teat = np.random.randn(100000)

plt.hist(teat, bins=1000)
plt.show()

728x90