Skip to content

Instantly share code, notes, and snippets.

@goddoe
Created July 13, 2023 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goddoe/647320b1f8ab206f2a70749672afcfd1 to your computer and use it in GitHub Desktop.
Save goddoe/647320b1f8ab206f2a70749672afcfd1 to your computer and use it in GitHub Desktop.
파일이 너무 커서 한 번에 메모리에 로드할 수 없는 경우, 간단한 무작위 샘플링은 불가능합니다. 그러나, 이 문제를 해결하기 위해 Reservoir Sampling이라는 알고리즘이 있습니다. 이 알고리즘은 스트림에서 무작위로 샘플을 선택하는 데 사용됩니다.
import random
def reservoir_sampling(file_name, k):
sample = []
with open(file_name, 'r') as f:
f.seek(0, 2) # 파일의 끝으로 이동
filesize = f.tell() # 파일의 크기를 얻음 (바이트)
random_set = sorted(random.sample(range(filesize), k))
for i in range(k):
f.seek(random_set[i])
# 파일의 중간에 끼어있을 수 있는 줄을 건너뜀
f.readline()
# 다음 줄을 샘플로 취함
sample.append(f.readline())
return sample
# 사용 예
samples = reservoir_sampling('large_file.txt', 100) # 100개의 무작위 라인을 샘플링
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment