根据条件用随机数替换 numpy 数组值

dc-*_*-ai 6 python arrays random numpy vectorization

我需要根据条件用随机数替换 numpy 数组中的一些值。

我有一个函数可以在 50% 的情况下添加随机值:

def add_noise(noise_factor=0.5):

    chance = random.randint(1,100)
    threshold_prob = noise_factor * 100.

    if chance <= threshold_prob:
        noise = float(np.random.randint(1,100))
    else:
        noise = 0.

    return(noise)
Run Code Online (Sandbox Code Playgroud)

但是当我调用 numpy 函数时,它会用生成的随机数替换所有匹配值:

np.place(X, X==0., add_noise(0.5))
Run Code Online (Sandbox Code Playgroud)

这样做的问题是 add_noise() 仅运行一次,并且它用噪声值替换所有 0. 值。

我想做的是“迭代”numpy 数组中的每个元素,检查条件(是否 ==0。)并且我想每次都通过 add_noise() 生成噪声值。

我可以用 for 循环遍历每一行和每一列来做到这一点,但是有人知道更有效的方式吗?

Div*_*kar 3

这是一种矢量化方法 -

noise_factor = 0.5 # Input param

# Get mask of zero places and the count of it. Also compute threshold
mask = X==0
c = np.count_nonzero(mask)
threshold_prob = noise_factor * 100.

# Generate noise numbers for count number of times. 
# This is where vectorization comes into the play.
nums = np.random.randint(1,100, c)

# Finally piece of the vectorization comes through replacing that IF-ELSE
# with np,where that does the same op of choosing but in a vectorized way
vals = np.where(nums <= threshold_prob, np.random.randint(1,100, c) , 0)

# Assign back into X
X[mask] = vals
Run Code Online (Sandbox Code Playgroud)

额外的好处是我们可以重复使用maskof0s进行add_noise操作,也可以重新分配回X。这取代了 的使用np.place,并被视为效率标准。

进一步提升性能

我们可以在计算步骤numsvals使用随机数生成的两个步骤中进一步优化,只需执行一次并在第二步中重复使用,如下所示 -

nums = np.random.randint(1,100, (2,c))
vals = np.where(nums[0] <= threshold_prob, nums[1] , 0)
Run Code Online (Sandbox Code Playgroud)