繁体   English   中英

Numpy:改变所有矩阵元素的 10% 的最快方法

[英]Numpy: Fastest way to change 10% of all matrix elements

我有一个大小为mxn的矩阵M 目前,如果我想更改流程中所有矩阵元素的 10%,我会执行以下操作:

M = np.ones((m, n))
for _ in range(999999999):
    M = M + (np.random.random(M.shape) < 0.1) * np.random.random(M.shape)
    # do stuff with M

然而,这种方法在多次迭代和大型矩阵时真的很慢,并且当我真的只需要0.1*m*n时需要m*n随机数。

如何更快地执行上述操作?

如果您的用例可以容忍大约 10% 的值,您可以使用随机索引更改这些值:

import numpy as np
a = np.ones((10,10))
a[np.random.rand(*a.shape)>=0.9] = 0.
a
array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [0., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 0., 1., 1., 1., 1., 1.],
       [1., 1., 1., 0., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 0., 0., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 0., 1., 1., 0., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 0., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 0., 1.]])

如您所见,您将更改大约 10 个值。

我给了这个破解,并想出了一种在我的笔记本电脑上执行速度更快的方法。 不过我没有去 1B 迭代!

最佳表演者:

%timeit advancedSlice()
9.56 s ± 12.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def advancedSlice():
    M = np.arange(12000000.0).reshape(1200,10000)
    rows = M.shape[0]
    cols = M.shape[1]
    sampleSize = M.size//10
    for _ in range(100):
        M[np.random.randint(rows, size=sampleSize), np.random.randint(cols, size=sampleSize),] += np.random.random(sampleSize)
    return M

最佳表演者第二名:使用迈克尔的方法

%timeit advancedSlice2()
22.8 s ± 11.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def advancedSlice2():
    M = np.arange(12000000.0).reshape(1200,10000)

    for _ in range(100):
        randIndecies =np.random.rand(*M.shape)>=0.9
        M[randIndecies] += np.random.random(randIndecies[randIndecies==True].size)
    return M

原始代码:

%timeit randMask()
33.2 s ± 211 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def randMask():
    M = np.arange(12000000.0).reshape(1200,10000)
    for _ in range(100):
        M = M + (np.random.random(M.shape)  < 0.1) * np.random.random(M.shape)
    return M

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM