使numpy矩阵更稀疏 [英] Make numpy matrix more sparse

查看:126
本文介绍了使numpy矩阵更稀疏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个numpy数组

Suppose I have a numpy array

np.array([
    [3, 0, 5, 3, 0, 1],
    [0, 1, 2, 1, 5, 2],
    [4, 3, 5, 3, 1, 4],
    [2, 5, 2, 5, 3, 1],
    [0, 1, 2, 1, 5, 2],
])

现在,我想将一些元素随机替换为0.这样我就得到了这样的输出

Now, I want to randomly replace some elements with 0. So that I have an output like this

np.array([
    [3, 0, 0, 3, 0, 1],
    [0, 1, 2, 0, 5, 2],
    [0, 3, 0, 3, 1, 0],
    [2, 0, 2, 5, 0, 1],
    [0, 0, 2, 0, 5, 0],
])

推荐答案

我们可以使用

We can use np.random.choice(..., replace=False) to randomly select a number of unique non-zero flattened indices and then simply index and reset those in the input array.

因此,一种解决方案是-

Thus, one solution would be -

def make_more_sparsey(a, n):
    # a is input array
    # n is number of non-zero elements to be reset to zero
    idx = np.flatnonzero(a) # for performance, use np.flatnonzero(a!=0)
    np.put(a, np.random.choice(idx, n, replace=False),0)
    return a

样品运行-

In [204]: R = np.array([
     ...:     [3, 0, 5, 3, 0, 1],
     ...:     [0, 1, 2, 1, 5, 2],
     ...:     [4, 3, 5, 3, 1, 4],
     ...:     [2, 5, 2, 5, 3, 1],
     ...:     [0, 1, 2, 1, 5, 2],
     ...: ])

In [205]: make_more_sparsey(R, n=5)
Out[205]: 
array([[3, 0, 5, 3, 0, 1],
       [0, 1, 0, 0, 5, 2],
       [4, 3, 5, 3, 1, 4],
       [2, 5, 0, 5, 3, 1],
       [0, 1, 0, 1, 0, 2]])

这篇关于使numpy矩阵更稀疏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆