본문 바로가기

Study/FastCampus

[Numpy] random

728x90
반응형

-. seed : 랜덤값을 설정값

-. rand : 균등분포로 난수를 발생

-. randn : 정규분포로 난수를 발생

-. randint : 균등분포로 정수값을 발생

-. suffle : 행렬 데이터를 섞어 줌.

-. choice : 특정 확률로 데이터를 선택


1. seed

np.random.seed(1)
result1 = np.random.randint(10, 100, 10)

np.random.seed(1)
result2 = np.random.randint(10, 100, 10)

np.random.seed(2)
result3 = np.random.randint(10, 100, 10)

print(result1)
print(result2)
print(result3)

########################################

[47 22 82 19 85 15 89 74 26 11]
[47 22 82 19 85 15 89 74 26 11]
[50 25 82 32 53 92 85 17 44 59]

 

2. rand : 0과 1 사이에서의 숫자를 균등한 분포 하에 랜덤 값 발생

    randn : 0 기준 값이 높은 확률로 뽑힌다. ( 정규 분포 )

print(np.random.rand(10))
print()
print(np.random.randn(10))

##########################
[0.42094097 0.34215631 0.97853527 0.53864195 0.96827539 0.00962755
 0.32514619 0.21539666 0.19125334 0.92888843]

[-0.18505656 -1.53684423 -0.06228859 -1.52343123 -3.11801139  0.56419238 
 -1.64710631 -1.31837332  0.92825872  0.83245858]

 

3. randint

# random.randint(low, high=None, size=None, dtype=int)
datas = np.random.randint(100, 130, size=(8,8))
print(datas)

[[108 125 103 100 102 103 108 110]
 [118 110 105 106 109 121 112 106]
 [101 123 127 127 123 129 107 118]
 [114 113 129 108 127 107 103 117]
 [127 111 103 108 118 115 116 120]
 [109 107 104 106 109 103 126 115]
 [123 121 101 121 113 100 129 117]
 [122 121 102 106 102 110 110 115]]

 

4. shuffle : 행렬의 값을 섞어 줌.

np.random.seed(1)
r = np.random.randint(1,10,(3,4))

[[6 9 6 1]
 [1 2 8 7]
 [3 5 6 3]]
 
np.random.shuffle(r)
print(r)

[[3 5 6 3]
 [1 2 8 7]
 [6 9 6 1]]

첫번째 행에 대해서만 shuffle이 된다.. 전체 행과 열에 대해 shuffle을 하기 위해서는 reshape로 1개의 행으로 만들어 준 뒤, 다시금 행렬로 만들어 주면 된다.

x = np.reshape(r,(1,12))

[[6 9 6 1 1 2 8 7 3 5 6 3]]


np.random.shuffle(x)
result = np.reshape(x,(3,4))
print(result)

[[6 9 6 1]
 [1 2 8 7]
 [3 5 6 3]]

 

5. Choice

print(np.random.choice(5,10, p=[0.1, 0, 0.4, 0.2, 0.3]))

[2 4 2 2 2 3 2 3 4 4]

첫번째 파라미터 5의 의미 ==> 0 ~ 4 까지의 숫자를

두번째 파라미터 10의 의미 ==> 10개 추출 하겠다.

세번째 파라미터 p의 의미 ==> 0 ~ 4 까지의 추출될 확률을 지정

(실제 1은 확률이 0이기 때문에 결과에서 없는 것을 알 수 있음)

 

6. 기타

np.unique()

np.random.seed(1)
r = np.random.randint(1,10,(3,4))
print(r)


[[6 9 6 1]
 [1 2 8 7]
 [3 5 6 3]]

numbers, counts = np.unique(r, return_counts=True)
print(numbers)
print(counts)

[1 2 3 5 6 7 8 9]
[2 1 2 1 3 1 1 1]
728x90
반응형