오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-14 05:39
관리 메뉴

우노

[Python] Custom Sparse Matrix 생성 본문

Language/Python

[Python] Custom Sparse Matrix 생성

운호(Noah) 2020. 11. 17. 16:06

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 형식)

Comments