如何在 for 循环中使用 vstack 将 csr_matrix 矩阵附加在一起

Han*_*Goc 2 python numpy scipy

我正在使用以下代码段将不同类型的矩阵连接csr_matrix 在一起。它基于如何展平 csr_matrix 并将其附加到另一个 csr_matrix?

#! /usr/bin/python
# -*- coding: utf-8 -*-
import re, sys
import os
import numpy

from scipy.sparse import csr_matrix
from scipy.sparse import vstack


if __name__ == "__main__": 

  centroids = []
  for i in range(0,3):
    a = csr_matrix([[i,i,i]])
    centroids = vstack((centroids, a), format='csr')

  print "centroids : " + str(centroids.shape[0]) +"  "+ str(centroids.shape[1])
Run Code Online (Sandbox Code Playgroud)

作为输出我得到

centroids : 4  3
Run Code Online (Sandbox Code Playgroud)

质心的大小应该是 3 而不是 4。我是否正确连接它们?


我尝试了以下操作,看看是否可以忽略第一行:

from sklearn.metrics.pairwise import euclidean_distances
matrix = euclidean_distances(centroids[1:][:], centroids[1:][:])
print matrix
[[ 0.          1.73205081  3.46410162]
 [ 1.73205081  0.          1.73205081]
 [ 3.46410162  1.73205081  0.        ]]
Run Code Online (Sandbox Code Playgroud)

对我来说听起来不错。

小智 5

不要vstack在循环中使用,因为在每次迭代中更改矩阵的大小和稀疏性的成本很高。相反,做:

centroids = []
for i in range(3):
  a = csr_matrix([[i, i, i]])
  centroids.append(a)
centroids = vstack(centroids, format="csr")
Run Code Online (Sandbox Code Playgroud)