Python/numpy & Pytorch

[Numpy] random 서브 모듈

파송송 2022. 8. 1. 18:11
728x90

https://codetorial.net/numpy/random.html

Matplotlib와 함께 정리가 잘된 사이트

 

NumPy 난수 생성 (Random 모듈) - Codetorial

예제1 - 기본 사용 import numpy as np a = np.random.randn(5) print(a) b = np.random.randn(2, 3) print(b) sigma, mu = 1.5, 2.0 c = sigma * np.random.randn(5) + mu print(c) [ 0.06704336 -0.48813686 0.4275107 -0.9015714 -1.30597604] [[ 0.87354043 0.03783

codetorial.net

 

Random 서브 모듈

  • Random 모듈에 있는 다양한 함수를 통해 특정 범위, 개수, 형태를 갖는 난수 생성에서 활용 가능

 

rand

  • 0 ~ 1 사이의 랜덤한 ndarray 생성
  • parameter 값은 arange랑 비슷함
np.random.rand(2, 3)

결과 1
결과 2

실행할 때 마다 다른 난수 발생

np.random.rand(5)
np.random.rand(2, 3, 4)

array([0.91658382, 0.85938711, 0.66940341, 0.41594724, 0.88564095])
array([[[0.54109404, 0.74867509, 0.28578402, 0.65362947],
        [0.27309207, 0.46953695, 0.7256572 , 0.77333583],
        [0.77038042, 0.78565092, 0.58114835, 0.50503722]],

       [[0.07122367, 0.24035075, 0.28453746, 0.23287762],
        [0.12952284, 0.48888114, 0.59815744, 0.20300082],
        [0.64202159, 0.68356639, 0.91063599, 0.45614067]]])

 

randn

  • n : normal distribution (정규 분포)
  • 정규분포로 샘플링된 랜덤 ndarray 생성
  • \( N(\mu, \sigma^{2}) \)의 경우 c = sigma * np.random.randn(5) + mu 와 같이 사용 가능
np.random.randn(3, 4)
np.random.randn(2, 3, 4)


array([[-0.49877773, -0.27742098,  0.44084168,  0.05923024],
       [ 0.15038982, -1.6238503 , -0.36258852,  0.90563597],
       [-0.15356809, -0.28665527, -0.48069368, -0.60523583]])
array([[[-0.71432122,  1.59179541,  1.14618268, -0.55785528],
        [-1.01347604, -0.34551177, -0.42667083, -2.11764588],
        [-0.05277305, -0.60144367, -0.05834352, -0.83345114]],

       [[-0.47910755, -0.47784565,  1.09805113, -0.27570596],
        [-1.40212439, -0.84674452,  0.87421835, -0.03943741],
        [ 1.22687616,  0.34270473,  0.45375635,  0.06002358]]])

 

randint

  • 특정 정수 사이에서 랜덤하게 샘플링
  • np.random.randint(low, high, size, dtype=int)
np.random.randint(1, 100, size=(2, 3))

array([[75, 99, 28],
       [95, 34, 51]])

seed

  • 랜덤한 값을 동일하게 생성하고 싶을 때 사용
np.random.seed(100)
np.random.randint(1, 100, size=(2, 3))

array([[ 9, 25, 68],
       [88, 80, 49]])

값이 달라지지 않고 항상 일정하게 나옴

seed값은 자신이 정하는 것, 상징적인 숫자를 사용하는 것이 보편적임

 

choice

  • 1차원 ndarray의 값을 랜덤 샘플링
  • 정수의 경우, np.arange(해당 숫자)로 인식
  • replace = False 중복 숫자는 걸러짐
np.random.choice(100, size=(2, 3))

array([[30, 17, 53],
       [68, 50, 91]])

np.arange(100)으로 생성되는 1차원 ndarray 값에서 추출

 

a = np.array([1.5, 2.5, 3.5, 7, 8, 9])
np.random.choice(a, size=(2, 3))

array([[7. , 8. , 9. ],
       [3.5, 3.5, 8. ]])

확률분포에 따린 ndarray 생성

  • uniform, normal 등

728x90