python - 将 numpy.ndarray 输出为 csr 文件
问题描述
我正在尝试将 numpy ndarray 输出为 CSR 文件(这是一个中间阶段,我正在尝试使用需要 CSR 格式作为输入的程序)。
到目前为止,我已经尝试使用scipy.sparse.coo_matrix()
以下代码写入 ijv 文件:
pca_coo = scipy.sparse.coo_matrix(pca_result)
with open(project + '/matrix/for_knn.jiv', 'w') as f:
for row, col, val in zip(pca_coo.row, pca_coo.col, pca_coo.data):
t= f.write("{}\t{}\t{}\n".format(row, col, val))
上述代码产生的文件导致下游程序出现段错误。
我现在假设问题出在输出格式上,但我无法找到问题所在。
编辑:在下面回答。
解决方案
一位朋友帮我解决了以下问题:
def write_csr(C, outputname):
"""
writes out a csr matrix to a file (for use with l2knng).
C = csr matrix
outputName = output file name
"""
with open(outputname, 'a') as OUTFILE:
for i in range(0,C.shape[0]):
sub = C[i,]
outstr = ""
for j in range(0,sub.size):
outstr += " " + str(sub.indices[j]+1) + " " + str(sub.data[j])
outstr += "\n"
_ = OUTFILE.write(outstr)
似乎运作良好。