๋ฐ์ดํฐ ๋ถ์ ๋ฐ ๋จธ์ ๋ฌ๋์์๋ ๋์(random number) ์์ฑ๊ณผ ์ํ๋ง(sampling)์ด ์์ฃผ ์ฌ์ฉ๋๋ค. Numpy์ np.random ๋ชจ๋์ ํ์ฉํ๋ฉด ๋ค์ํ ํ๋ฅ ๋ถํฌ์์ ๋์๋ฅผ ์์ฑํ๊ณ ๋ฐ์ดํฐ๋ฅผ ์ํ๋งํ ์ ์๋ค.
1. ๋์ ์์ฑ์ ๊ธฐ๋ณธ
1.1 ๊ท ๋ฑ ๋ถํฌ ๋์ ์์ฑ
๊ท ๋ฑ ๋ถํฌ์์ ๋์๋ฅผ ์์ฑํ๋ ค๋ฉด np.random.rand() ๋๋ np.random.uniform()์ ์ฌ์ฉํ๋ฉด ๋จ
import numpy as np
# 0๊ณผ 1 ์ฌ์ด์ ๋์ 5๊ฐ ์์ฑ
random_numbers = np.random.rand(5)
print(random_numbers)
# [0.68210576 0.42857438 0.15101299 0.54555321 0.02568058]
# ํน์ ๋ฒ์(์: 10~20)์์ ๊ท ๋ฑ ๋ถํฌ ๋์ 5๊ฐ ์์ฑ
random_uniform = np.random.uniform(10, 20, 5)
print(random_uniform)
# [13.02513486 13.01353072 17.41235939 16.13056435 19.33079594]
1.2 ์ ๊ท ๋ถํฌ ๋์ ์์ฑ
์ ๊ท ๋ถํฌ(๊ฐ์ฐ์์ ๋ถํฌ)์์ ๋์๋ฅผ ์์ฑํ๋ ค๋ฉด np.random.randn() ๋๋ np.random.normal()์ ์ฌ์ฉํ๋ฉด ๋จ.
# ํ๊ท 0, ํ์คํธ์ฐจ 1์ธ ์ ๊ท๋ถํฌ์์ ๋์ 5๊ฐ ์์ฑ
normal_random = np.random.randn(5)
print(normal_random)
# [1.69753115 0.42420459 0.81921845 0.75193326 1.25570611]
# ํ๊ท 10, ํ์คํธ์ฐจ 2์ธ ์ ๊ท๋ถํฌ์์ ๋์ 5๊ฐ ์์ฑ
normal_custom = np.random.normal(10, 2, 5)
print(normal_custom)
# [ 8.63078874 11.81641683 7.50887906 8.87855625 11.51443264]
2. ์ ์ ๋์ ์์ฑ
์ ์ ๋ฒ์์์ ๋์๋ฅผ ์์ฑํ๋ ค๋ฉด np.random.randint()๋ฅผ ์ฌ์ฉํ๋ฉด ๋จ.
# 0๋ถํฐ 9๊น์ง์ ์ ์ ๋์ 5๊ฐ ์์ฑ
random_integers = np.random.randint(0, 10, 5)
print(random_integers)
# [4 8 4 2 4]
3. ๋ฐ์ดํฐ ์ํ๋ง
Numpy๋ ๊ธฐ์กด ๋ฐ์ดํฐ์์ ์ํ๋ง์ ์ํํ๋ ๋ค์ํ ๋ฐฉ๋ฒ์ ์ ๊ณตํจ
3.1 ๋ฐฐ์ด์์ ๋ฌด์์ ์ํ ์ ํ (choice)
np.random.choice()๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐฐ์ด์์ ๋ฌด์์๋ก ์ํ์ ์ ํํ ์ ์์
arr = np.array([1, 2, 3, 4, 5])
# ๋ฐฐ์ด์์ 3๊ฐ ์ํ ์ ํ (์ค๋ณต ํ์ฉ)
sampled = np.random.choice(arr, 3)
print(sampled)
# [5 2 4]
# ๋ฐฐ์ด์์ 3๊ฐ ์ํ ์ ํ (์ค๋ณต ์์)
sampled_unique = np.random.choice(arr, 3, replace=False)
print(sampled_unique)
# [4 5 1]
3.2 ์ํ๋ง์ ์ํ ํ๋ฅ ๊ฐ์ค์น ์ ์ฉ
์ ํ ํ๋ฅ ์ ์กฐ์ ํ๋ ค๋ฉด p ๋งค๊ฐ๋ณ์๋ฅผ ์ฌ์ฉํ๋ฉด ๋จ
# ์ ํ ํ๋ฅ ์ ์ ์ฉํ ์ํ๋ง
weighted_sample = np.random.choice(arr, 3, p=[0.1, 0.2, 0.3, 0.2, 0.2])
print(weighted_sample)
# [2 5 3]
4. ๋์ ์์ฑ ์๋ ์ค์
๊ฐ์ ๋์๋ฅผ ์ฌํํ๋ ค๋ฉด np.random.seed()๋ฅผ ์ฌ์ฉํ์ฌ ์๋๋ฅผ ์ค์ ํด์ผ ํจ
np.random.seed(42)
print(np.random.rand(3))
# [0.37454012 0.95071431 0.73199394]
์ ์ฝ๋๋ฅผ ์คํํ๋ฉด ๊ฐ์ ๊ฒฐ๊ณผ๊ฐ ์ถ๋ ฅ๋จ. ์ด๋ฅผ ํตํด ์ฌํ ๊ฐ๋ฅ์ฑ์ ๋ณด์ฅํ ์ ์์
5. ๋ง๋ฌด๋ฆฌ
Numpy์ np.random ๋ชจ๋์ ์ฌ์ฉํ๋ฉด ๋ค์ํ ํ๋ฅ ๋ถํฌ์์ ๋์๋ฅผ ์์ฑํ๊ณ ๋ฐ์ดํฐ๋ฅผ ์ํ๋งํ ์ ์๋ค. ํนํ, ์๋๋ฅผ ์ค์ ํ๋ฉด ๋์ผํ ๋์๋ฅผ ์์ฑํ ์ ์์ด ์คํ์ ์ผ๊ด์ฑ์ ์ ์งํ ์ ์๋ค. ์ด๋ฌํ ๊ธฐ๋ฒ์ ๋ฐ์ดํฐ ๋ถ์, ๋จธ์ ๋ฌ๋, ์๋ฎฌ๋ ์ด์ ๋ฑ ๋ค์ํ ๋ถ์ผ์์ ํ์ฉ๋ ์ ์๋ค.
'๊ฐ๋ฐ Code > ํ์ด์ฌ Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python][pandas] Loading Data - CSV (0) | 2025.02.11 |
---|---|
[Python][pandas] Exploring pandas in Depth (0) | 2025.02.11 |
[Python][numpy] Numpy ๋ฐฐ์ด ์ ์ฅ ๋ฐ ๋ถ๋ฌ์ค๊ธฐ (0) | 2025.02.09 |
[Python][numpy] Numpy ๊ธฐ์ด๋ถํฐ ํ์ฉ๊น์ง (0) | 2025.02.08 |
[Python][pandas] ๋ฐ์ดํฐ ์ ๋ ฌํ๊ธฐ - Sort (0) | 2025.01.30 |