[docs]defto_sparse(X,type='csr'):'''Convert to sparse matrix. Guide for choosing sparsity types: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html '''asserttypein['coo','csr','csc','lil'],"Matrix type not available"iftype=='coo':X=coo_matrix(X)eliftype=='csr':X=csr_matrix(X)eliftype=='csc':X=csc_matrix(X)eliftype=='lil':# LIst of ListsX=lil_matrix(X)returnX
[docs]defto_dense(X,squeeze=False,keep_nan=False):'''Convert to dense array '''ifkeep_nanandissparse(X):rows,cols,values=to_triplet(X)X=np.empty(shape=X.shape)X.fill(np.nan)foriinrange(len(values)):X[rows[i],cols[i]]=values[i]ifissparse(X):X=X.toarray()elifisinstance(X,np.matrix):X=np.asarray(X)returnX.squeeze()ifsqueezeelseX
[docs]defto_triplet(X):'''Convert a dense or sparse matrix to a UIR triplet '''coo=coo_matrix(X)X=(np.asarray(coo.row,dtype='int'),np.asarray(coo.col,dtype='int'),np.asarray(coo.data,dtype='float'))returnX