티스토리 뷰
랜덤으로 ndarray 생성하기
ndarray를 생성할 때 랜덤값 기반으로 생성할 수 있다.
총 5가지 방법으로 ndarray를 생성할 수 있다.
np.random.normal()
np.random.rand(d0, d1, d2.. )
np.random.randn()
np.random.ranadint(low, high, shape)
np.random.random(shape)
1. np.random.normal()
정규분포(평균, 표준편차 이용) 확률밀도함수에서 실수 표본을 추출해서 ndarray 생성
mean = 50 # 평균
std = 2 # 표준편차
arr = np.random.normal(mean, std, (10000, )) # 난수 10000개 추출
print(arr)
# [44.50727651 48.99284656 49.07309962 ... 49.88544463 52.43436293
# 52.36112056]
# 특정 영역 안에 몇개 있는지 히스토그램으로 나타낸다.
plt.hist(arr, bins=100)
plt.show()
2. np.random.rand(d0, d1, d2.. )
[0, 1) (0<= 실수x <=1) 범위에서 균등분포로 실수 추출
- 인자 하나 => 1차원, 두개 => 2차원
arr = np.random.rand(100000)
print(arr)
# [0.08386971 0.84501991 0.09875647 ... 0.22411621 0.7281503 0.23096898]
plt.hist(arr, bins=100)
plt.show()
3. np.random.randn()
실수 추출, 표준정규분포에서 난수 추출
- 표준정규분포 - 평균 0, 표준편차 1
arr = np.random.randn(100000)
print(arr)
# [-0.55739177 2.53737014 0.36589348 ... -0.2681497 -0.51712975
# 0.53599655]
plt.hist(arr, bins=100)
plt.show()
4. np.random.ranadint(low, high, shape)
균등분포 확률밀도함수에서 난수 추출
- 정수값을 난수로 추출
arr = np.random.randint(-100, 100, (100000, ))
print(arr)
# [-86 36 13 ... 71 4 90]
plt.hist(arr, bins=100)
plt.show()
5. np.random.random(shape)
[0, 1) 균등분포에서 실수 난수를 추출!
arr = np.random.random((100000, ))
print(arr)
plt.hist(arr, bins=100)
plt.show()
랜덤 관련 함수
seed
shuffle
choice
1. seed()
난수의 재현
# Numpy가 제공하는 랜덤 관련 함수
## 1. 난수의 재현
# 랜덤값도 실제로는 특정 알고리즘의 결과물이다.
# => 초기에 시작값을 설정해주면, 항상 같은 랜덤값이 도출된다.
np.random.seed(10)
arr = np.random.randint(0, 100, (10, ))
print(arr)
# [ 9 15 64 28 89 93 29 8 73 0]
2. shuffle()
ndarray의 순서를 랜덤하게
## 2. ndarray의 순서를 랜덤하게 바꾸려면?
arr = np.arange(10)
print(arr)
# [0 1 2 3 4 5 6 7 8 9]
np.random.shuffle(arr) # ndrray 자체가 변형된다.
print(arr)
# [0 7 5 2 3 9 6 4 8 1] => 실행될 때 마다 바뀜
3. choice()
Sampling 기능
ndarray 안에서 일부를 무작위로 선택하는 기능 => Sampling
np.random.choice(arr, size, replace, p)
1) arr : numpy array 혹은 정수가 나온다.
정수면, arange(정수)
2) size : 정수값. 샘플의 숫자
3) replace : Boolean(True, False)
- True => 한번 선택한 데이터를 다시 샘플링 할 수 있다.
4) p : ndrray.
- 각 데이터가 샘플링될 수 있는 확률
## 3. ndarray 안에서 일부를 무작위로 선택하는 기능 => Sampling -> choice()
arr = np.random.choice(5, 3, replace=True)
print(arr) # [0 0 4]
arr = np.random.choice([1, 2, 3, 4, 5], 3, replace=False)
print(arr) # [2 3 1]
arr = np.random.choice(5, 5, replace=False) # Shuffle과 동일 기능
print(arr) # [1 3 0 4 2]
# [0 1 2 3 4 5 ]
arr = np.random.choice(5, 10, replace=True, p=[0.2, 0, 0.3, 0.4, 0.1])
print(arr) # [3 2 3 4 3 4 3 2 0 2]
'멀티캠퍼스 AI과정 > 03 Numpy' 카테고리의 다른 글
Numpy 06 - ndarray의 사칙연산, 행렬곱, Broadcasting (0) | 2020.09.08 |
---|---|
Numpy 05 - ndarray의 Indexing & Slicing (0) | 2020.09.08 |
Numpy 04 - ndarray의 shape 조절 함수 (0) | 2020.09.08 |
Numpy 02 - ndarray 생성과 차원 관련 속성 (0) | 2020.09.08 |
Numpy 01 - Introduction (0) | 2020.09.08 |
댓글