简体   繁体   English

如何在python中使用两个不同格式的向量进行运算

[英]How to do operations with two vectors of different format in python

One of my vector is in format scipy.sparse.csr.csr_matrix, the other is numpy.ndarray. 我的向量之一是scipy.sparse.csr.csr_matrix格式,另一个是numpy.ndarray。 I have an experimental code below: 我在下面有一个实验代码:

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

I get z.shape = (5L,) and don't know what it means. 我得到z.shape =(5L,),不知道这意味着什么。 If I print z it tells me its a row vector with 3 elements in it. 如果我打印z,它会告诉我其包含3个元素的行向量。 How can I print the numerical result, eg the 1*5 vector from z? 如何打印数值结果,例如z的1 * 5向量? I'm new to Python and these math packages, just want to learn something about the sparse matrix operations. 我是Python和这些数学软件包的新手,只是想学习有关稀疏矩阵运算的知识。 My problem is how to do operations like this right and efficiently, since I guess there is a way without getting sparse representations back to dense every time. 我的问题是如何正确,有效地执行这样的操作,因为我猜想有一种方法不会使稀疏表示每次都回到密集状态。

Thanks! 谢谢!

You could do this: 您可以这样做:

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)

Result: 结果:

>>> z
matrix([[ 1.  ,  0.  ,  0.  ,  0.25,  0.4 ]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM