우노
[Python] Custom Sparse Matrix 생성 본문
COO형식의 Custom Sparse Matrix 생성 코드
코드
import random import os # 생성하고자하는 Sparse matrix의 행,렬,density 입력 row = 10000 col = 10000 density = 0.05 nnz = int(row * col * density) # 결과 파일명 (M_행_열_density_nnz) file = "M_" + str(row) + "_" + str(col) + "_" + str(density) + "_" + str(nnz) # 행,열 중복 확인용 dic dic = {} with open(file,"w") as w: for i in range(nnz): # 행,열,값 난수 생성 row_idx = random.randrange(0,row) col_idx = random.randrange(0,col) value = random.random() # COO 형식의 line 생성 line = str(row_idx) + " " + str(col_idx) + " " + str(value) + "\n" # 행,열 중복 확인용 idx 생성 r_c_idx = str(row_idx) + " " + str(col_idx) # 중복 되지 않는 행,렬만 write if r_c_idx not in dic: dic[r_c_idx] = 1 w.write(line) # 중복 제거 된 nnz, density 업데이트 new_nnz = len(dic) new_density = new_nnz / (row * col) # 파일명 수정 (M_행_열_newdensity_newnnz) newfile = "M_" + str(row) + "_" + str(col) + "_" + str(format(new_density,".8f")) + "_" + str(new_nnz) os.rename(file, newfile)
결과 파일명 (M_행_열_density_nnz)
- M_10000_10000_0.04876852_4876852
결과 파일내부 (COO 형식)
'Language > Python' 카테고리의 다른 글
[Python] Numpy 2차원 배열 생성 방법 (0) | 2020.11.26 |
---|---|
[Python] Pandas DataFrame index 정렬 및 초기화 (0) | 2020.11.20 |
[Python] random 모듈 정리 (0) | 2020.11.17 |
[Python] os 모듈 정리 (0) | 2020.11.15 |
[Python] 코드 실행시간 측정 (0) | 2020.11.15 |
Comments