[SciPy-user] math operations on sparse matrices

Nathan Bell wnbell@gmail....
Sat Feb 21 19:20:21 CST 2009


On Sat, Feb 21, 2009 at 2:28 PM,  <josef.pktd@gmail.com> wrote:
> I have a (dok) sparse distance matrix and I would like to take the
> exponential of the distances
>
> The direct method doesn't work
>>>> Mexp = np.exp(-M)
> Traceback (most recent call last):
>  File "<pyshell#31>", line 1, in <module>
>    Mexp = np.exp(-M)
> AttributeError: exp
>
> The following seems to work. What is the recommended way for doing
> these transformations?
> I didn't see anything in the docs.
>
>>>> T1 = ssp.KDTree(xs3[::k,:],leafsize=2)
>>>> M = T1.sparse_distance_matrix(T1, r)
>>>> Mexp = M.copy()
>>>> for k,v in M.items():
>        Mexp[k]=np.exp(-v)
>

Does the following solve your problem?
>>> M = M.tocsr()
>>> M.data = np.exp(M.data)


I suppose we could add a transform(A, fn) function to scipy.sparse to
codify this sort of thing.  Any suggestions?  The difference here is
that fn() would only be applied to the nonzero entries of A (and to
the explicit zeros, if they are also present).

I'd rather not encourage people to manipulate the underlying CSR/CSC
representations directly, so tranform() would be a nice way to expose
this.

-- 
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/


More information about the SciPy-user mailing list