본문 바로가기
목차
Python

random 모듈 사용법

by ds31x 2025. 10. 2.
728x90
반응형

https://www.scaler.com/topics/python-random-module/

 

random 내장 모듈(built-in)은 난수(무작위 숫자)를 생성하거나, 리스트에서 무작위로 선택하는 기능을 제공.

 

tensor 객체를 random하게 만드는 방법은 다음을 참고:

2024.03.29 - [Python] - [DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

 

[DL] Tensor: Random Tensor 만들기 (NumPy, PyTorch)

Tensor: Random Tensor 만들기 (NumPy, PyTorch)Random value를 얻는데 이용되는 Probability Distribution에 따라 크게 2가지로 나눌 수 있음.Uniform DistributionNormal Distribution 0. Uniform DistributionRandom Variable이 가질 수

ds31x.tistory.com


주요 메서드

  • random.random() : [0,1) 사이 실수
  • random.randint(a, b) : [a,b] 범위 정수
  • random.uniform(a, b) : [a,b] 범위 실수
  • random.choice(seq) : 시퀀스에서 하나 추출
  • random.sample(seq, k) : 중복 없이 k개 추출
  • random.choices(seq, k=n) : 중복 허용 n개 추출
  • random.shuffle(seq) : 리스트 순서 섞기
  • random.seed(n) : 난수 결과 고정

1. 모듈 불러오기

import random

2. 기본적인 난수 생성

2-1. 0 이상 1 미만 [0.0, 1.0) 의 난수

print(random.random())  # 예: 0.37444887175646646

2-2. 특정 범위의 정수

print(random.randint(1, 10))  # 1 ~ 10 사이의 정수 중 하나

2-3. 특정 범위의 실수

print(random.uniform(1.0, 5.0))  # 1.0 ~ 5.0 사이의 실수

3. 리스트에서 무작위 추출

3-1. 리스트 중 하나 선택

fruits = ["apple", "banana", "cherry"]
print(random.choice(fruits))  
# "banana" 같은 값이 무작위로 선택됨

3-2. 여러 개 선택 (중복 없음)

print(random.sample(fruits, 2))  
# ['apple', 'cherry'] 와 같이 2개 뽑음

3-3. 여러 개 선택 (중복 허용)

print(random.choices(fruits, k=5))  
# ['banana', 'banana', 'cherry', 'apple', 'apple'] 처럼 나올 수 있음

4. 순서 섞기 (Shuffle)

cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)  
# 예: [3, 1, 5, 4, 2]

5. 재현 가능한 난수 (Seed 고정)

실험이나 테스트에서 항상 같은 난수 결과를 얻고 싶을 때 seed()를 사용하여 seed 값을 고정한다.

random.seed(42)
print(random.randint(1, 100))  # 항상 같은 값 출력

6. 다른 확률분포 기반한 메서드들.

위의 함수들은 Uniform distribution에 기반한 것들이며, 다른 Probability distribution에 기반한 함수들은 다음과 같음.

import random

# 1. Uniform (균등 분포)
random.random()          # [0.0, 1.0)
random.uniform(1, 10)    # [1, 10]

# 2. Normal/Gaussian (정규 분포)
random.gauss(mu=0, sigma=1)
random.normalvariate(mu=0, sigma=1)

# 3. Exponential (지수 분포)
random.expovariate(lambd=1.5)

# 4. Gamma (감마 분포)
random.gammavariate(alpha=2, beta=1)

# 5. Beta (베타 분포)
random.betavariate(alpha=2, beta=5)

# 6. Lognormal (로그정규 분포)
random.lognormvariate(mu=0, sigma=1)

# 7. Triangular (삼각 분포)
random.triangular(low=0, high=10, mode=5)

# 8. Pareto (파레토 분포)
random.paretovariate(alpha=1)

# 9. Weibull (와이블 분포)
random.weibullvariate(alpha=1, beta=1.5)

# 10. Von Mises (폰 미제스 분포) - 원형 데이터용
random.vonmisesvariate(mu=0, kappa=1)

위의 코드의 활용방법은 다음의 gist를 참고할 것.

https://gist.github.com/dsaint31x/c6af1a05d58f636ec65ed378b0bbfa73

 

py_random_probability_distribution.ipynb

py_random_probability_distribution.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

 

보다 다양한 probability distribution이 필요하다면, NumPy의 random모듈을 사용하면 됨.

  • 사실 Poissson과 Binomial 등이 Python의 random모듈엔 없다보니 대부분은 NumPy의 random 모듈을 사용하게 된다.
  • Discrete Probability Distribution이 지원이 안되는게 아쉬움.

같이 보면 좋은 자료

https://dsaint31.tistory.com/707

 

[Math] Probability Distribution

Probability Distribution : Probability Distribution은 특정 random variable(확률 변수)이 취할 수 있는 각각의 값에 대한 확률을 나타내는 분포임.Probability Distribution Function (PDF)으로 기술되며,random variable이 어떤

dsaint31.tistory.com


 

728x90