파이썬/파이썬 기초

파이썬과 R에서 같은 난수 발생 패키지 SyncRNG

Ninestar 2022. 12. 14. 01:37
반응형
SyncRNG함수를 쓰면 난수를 동일하게 발생시킬 수 있다.
 

같은 시퀀스 난수 발생시키는 패키지

GitHub - GjjvdBurg/SyncRNG: Reliably generate the same random numbers in R and Python

arrays - Creating same random number sequence in Python, NumPy and R - Stack Overflow

 

Creating same random number sequence in Python, NumPy and R

Python, NumPy and R all use the same algorithm (Mersenne Twister) for generating random number sequences. Thus, theoretically speaking, setting the same seed should result in same random number seq...

stackoverflow.com

 

Python

# 데이터 셋  7:3 으로 분할
v=list(range(1,len(raw_data)+1))
s=SyncRNG(seed=42)
ord=s.shuffle(v)
idx=ord[:round(len(raw_data)*0.7)]

# R에서는 데이터프레임이 1부터 시작하기 때문에 -1
for i in range(0,len(idx)):
    idx[i]=idx[i]-1

# 학습데이터, 테스트데이터 생성
train=raw_data.loc[idx] # 70%
#train=train.sort_index(ascending=True)
test=raw_data.drop(idx) # 30%

 

R

#모델 생성
library(SyncRNG)
v <- 1:nrow(df)
s <- SyncRNG(seed=42)
idx <- s$shuffle(v)[1:round(nrow(df)*0.7)]

idx[1:length(idx)]
train <- df[idx,]
test <- df[-idx,]