如何在python中使用两个不同格式的向量进行操作
其中一个向量的格式是scipy.sparse.csr.csr_矩阵,另一个是numpy.ndarray。我有一个实验代码如下:如何在python中使用两个不同格式的向量进行操作,python,numpy,scipy,sparse-matrix,Python,Numpy,Scipy,Sparse Matrix,其中一个向量的格式是scipy.sparse.csr.csr_矩阵,另一个是numpy.ndarray。我有一个实验代码如下: import numpy as np from scipy.sparse import csr_matrix x = np.arange(5)+1 y = [1, 0, 0, 1, 2] y = csr_matrix(y) print type(x) print type(y) z = np.true_divide(y,x) print z.shape 我得到了z
import numpy as np
from scipy.sparse import csr_matrix
x = np.arange(5)+1
y = [1, 0, 0, 1, 2]
y = csr_matrix(y)
print type(x)
print type(y)
z = np.true_divide(y,x)
print z.shape
我得到了z.shape=(5L,),但我不知道它是什么意思。如果我打印z,它告诉我它是一个包含3个元素的行向量。
如何打印数值结果,例如z的1*5矢量?我是Python和这些数学软件包的新手,只是想了解一些关于稀疏矩阵运算的知识。我的问题是如何正确有效地执行这样的操作,因为我想有一种方法可以避免每次都将稀疏表示恢复为密集表示
谢谢 您可以这样做:
import numpy as np
from scipy.sparse import csr_matrix
x = np.arange(5)+1
y = [1, 0, 0, 1, 2]
y = csr_matrix(y)
x2 = 1.0 / np.matrix(x)
z = y.multiply(x2)
结果:
>>> z
matrix([[ 1. , 0. , 0. , 0.25, 0.4 ]])
您可以这样做:
import numpy as np
from scipy.sparse import csr_matrix
x = np.arange(5)+1
y = [1, 0, 0, 1, 2]
y = csr_matrix(y)
x2 = 1.0 / np.matrix(x)
z = y.multiply(x2)
结果:
>>> z
matrix([[ 1. , 0. , 0. , 0.25, 0.4 ]])