企业社会责任矩阵构建缓慢

slow csr matrix construction

我正在使用 csr_matrix((data, indices, indptr), shape=[row, col]) 方法创建一个 csr 矩阵。执行构造方法 csr_matrix() 比自己构建 data, indices, indptr 花费的时间多 4 倍。既然我已经有了 (data, indices, indptr) 元组,那么构造一个 csr 矩阵难道不应该很简单(而且很快)吗?

我的代码和时间统计是这样的:

data = ...  # 2.207s
indices = ...  # 11.065s       
indptr = ...  # 0.047s          
matrix = csr_matrix((data, indices, indptr), shape=(row, col))  # 57.806s

您传递的数组似乎很大,因此它们可能被复制到了某个地方,由此产生的内存问题导致了速度下降。

有几种方法可以复制您的数组。如果这些条件中的任何一个不成立,您将获得副本:

  • indicesindptr 需要具有适当的索引数据类型。
  • 三个都必须是numpy数组(numpy.ndarray)
  • copy kwarg 需要是 False。默认情况下它是错误的,所以这不太可能是问题。