numpy 如何计算scipy稀疏矩阵中的矩阵

mznpcxlj  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(123)

有没有办法计算scipy稀疏矩阵的百分位数?
由于内存问题,我不想将稀疏矩阵转换为稠密矩阵。
下面是一个我想要使用密集numpy数组的工作示例。我目前使用的numpy版本< 1.22,但我不介意使用最新的numpy版本的解决方案。

>>> arr = 100 * np.random.rand(3,5)
>>> arr
array([[ 3.24955563, 76.40300826, 95.47390569, 24.19071006, 26.07447378],
       [60.40003646, 38.50289778, 86.50299598, 27.00110588, 34.91898836],
       [51.75939709, 99.00492787, 63.32860788, 23.91364962, 56.34410086]])

>>> col_q3 = np.percentile(arr, 75, interpolation='midpoint', axis=0)
>>> col_q3
array([56.07971677, 87.70396807, 90.98845084, 25.59590797, 45.63154461])

>>> row_q3 = np.percentile(arr, 75, interpolation='midpoint', axis=1)
>>> row_q3
array([76.40300826, 60.40003646, 63.32860788])

对我来说,计算这些值所花费的时间并不太重要。我更关心内存的使用。

rjee0c15

rjee0c151#

实际上,我希望有一个稀疏的例子,例如:

In [45]: M = sparse.random(3, 5, 0.4, "csr")
In [46]: M
Out[46]: 
<3x5 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in Compressed Sparse Row format>
In [47]: M.A
Out[47]: 
array([[0.44828545, 0.84567936, 0.        , 0.23534173, 0.        ],
       [0.14978221, 0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.32428732, 0.        , 0.33813957]])

In [49]: arr = M.A
In [50]: np.percentile(arr, 75, interpolation="midpoint", axis=0)
....
Out[50]: array([0.29903383, 0.42283968, 0.16214366, 0.11767086, 0.16906979])
In [51]: np.percentile(arr, 75, interpolation="midpoint", axis=1)
....
  np.percentile(arr, 75, interpolation="midpoint", axis=1)
Out[51]: array([0.44828545, 0.        , 0.32428732])

1.22有一个关于interpolation参数使用的弃用警告。
我假设您已经搜索了percentilesparse文档。它认为你/我们需要深入研究np.percentile代码,以确定它到底在做什么-就像行/列sum,乘法等事情而言。
Sparse实现了像sum这样的东西:

In [53]: arr.sum(axis=0)
Out[53]: array([0.59806767, 0.84567936, 0.32428732, 0.23534173, 0.33813957])
In [54]: M.sum(axis=0)
Out[54]: matrix([[0.59806767, 0.84567936, 0.32428732, 0.23534173, 0.33813957]])

稀疏求和实际上是用矩阵乘法来完成的。

In [55]: np.ones(3) * M
Out[55]: array([0.59806767, 0.84567936, 0.32428732, 0.23534173, 0.33813957])

非零值为:

In [56]: M.data
Out[56]: 
array([0.44828545, 0.84567936, 0.23534173, 0.14978221, 0.32428732,
       0.33813957])

尽管逐行(或逐列)获得它们需要迭代。

In [58]: Ml = M.tolil()
In [59]: Ml.data
Out[59]: 
array([list([0.44828545291437716, 0.8456793619879996, 0.23534172969892375]),
       list([0.14978221447183726]),
       list([0.32428731688363377, 0.33813957327426203])], dtype=object)
lf3rwulv

lf3rwulv2#

这是你需要的吗
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.QuantileTransformer.html

from sklearn.preprocessing import QuantileTransformer

M = sparse.random(3, 5, 0.4, "csr")
qt = QuantileTransformer(n_quantiles=10, random_state=0)
qt.fit_transform(M)

相关问题