Scipy的sign()不能保证有效吗?

2024-06-29 00:44:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图A的邻接矩阵。在A = A.sign()之后仍然有一些元素不是1、0或-1。你知道吗

In [35]: A = A.sign()

In [36]: A.getcol(0).data
Out[36]: 
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,    
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
        1.,  1.,  1.,  1.,  2.])

In [37]: A
Out[37]: 
<519403x519403 sparse matrix of type '<type 'numpy.float64'>'
    with 3819116 stored elements in COOrdinate format>

另一方面numpy.sign()工作正常。你知道吗

In [50]: a = A.getcol(0)

In [51]: np.sum(a.todense())
Out[51]: 58.0

In [52]: np.sum(np.sign(a.todense()))
Out[52]: 57.0

Tags: ofinnumpy元素datatypenpout
1条回答
网友
1楼 · 发布于 2024-06-29 00:44:45

经过研究我得到了答案。它完全是关于Scipy使用的内部数据结构。你知道吗

import numpy as np
from scipy.sparse import coo_matrix

xs = np.array([1, 2, 3, 3, 2])
ys = np.array([2, 3, 1, 1, 1])
A = coo_matrix((np.ones((5,)), (xs, ys)))

此时A是一个<4x4 sparse matrix of type '<type numpy.float64'>' with 5 stored elements in COOrdinate format>,尽管我们有两个元素在同一个坐标(3, 1)。和A = A.sign()只在5个元素上执行,它们首先都是1。你知道吗

>>> A.data
array([ 1.,  1.,  1.,  1.,  1.])

>>> A.todense()
matrix([[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.],
        [ 0.,  2.,  0.,  0.]])

>>> A = A.sign()
>>> A.todense()
matrix([[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  1.,  0.],
        [ 0.,  1.,  0.,  1.],
        [ 0.,  2.,  0.,  0.]])

相关问题 更多 >