【问题标题】:Why is NumPy's `repmat` faster than `kron` to repeat blocks of arrays?为什么 NumPy `repmat` 比 `krona` 更快地重复数组块?
【发布时间】:2022-01-24 16:22:55
【问题描述】:

为什么 numpy.matlib 中的 repmat 函数比 numpy.kron(即 Kronecker 积)重复矩阵块要快得多?

MWE 将是:

test_N = 1000
test_vec = np.random.rand(test_N, 2)
rep_vec = np.matlib.repmat(test_vec, 100, 1)
kron_vec = kron(ones((100,1)), test_vec)

%%timeit
rep_vec = np.matlib.repmat(test_vec, 10, 1)
53.5 µs ± 2.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%%timeit
kron_vec = kron(test_vec, ones((10,1)))
1.65 ms ± 228 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

【问题讨论】:

  • 两者都是可以检查的python代码。快速浏览一下,repmat 使用了reshaperepeatkron 使用 outer(乘法)和 concatenate
  • 我不明白为什么reshaperepeat 会比outerconcatenate 更有效。我认为这就是重点......此外,即使两者都是我可以检查的 Python 代码,我相信这个问题的答案与 NumPy 如何构建在 C 上有关。
  • np.tile(test_vec,(100,1)) 更快。
  • test_vec[None,:,:].repeat(100,0).reshape(-1,2)tile 做同样的事情。

标签: python numpy matrix kronecker-product


【解决方案1】:

我自己的一些时间安排:

In [361]: timeit kron_vec = np.kron(np.ones((10,1)), test_vec)
131 µs ± 871 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

你的

kron_vec = kron(test_vec, ones((10,1)))
1.65 ms

看起来更像是 ones((100,1)) 时间测试。

我的比其他人长,但没有那么大。

类似的乘法方法(如kronouter,但不需要concatenate 步骤):

In [362]: timeit (test_vec*np.ones((10,1,1))).reshape(-1,2)
61.2 µs ± 38.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

repmat:

In [363]: timeit rep_vec = matlib.repmat(test_vec,10,1)
94.2 µs ± 32.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

改用tile

In [364]: timeit np.tile(test_vec,(10,1))
20.4 µs ± 17.8 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

repeat直接:

In [365]: timeit x = test_vec[None,:,:].repeat(10,0).reshape(-1,2)
12.2 µs ± 371 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

【讨论】:

  • 我做了%%timeit kron_vec_2 = np.kron(np.ones((10,1)), test_vec) 并得到了61.6 µs ± 3.29 µs per loop。但是,请注意np.kron(np.ones((10,1)), test_vec)np.kron( test_vec, np.ones((10,1))) 不同。
  • 另外,我认为您的最后两个解决方案确实显着提高了效率,因为这些操作将在大型矩阵上重复执行(然后性能的绝对差异开始变得更加重要)。
猜你喜欢
  • 2022-11-22
  • 1970-01-01
  • 2016-05-15
  • 2012-01-13
  • 1970-01-01
  • 2014-05-28
  • 2021-04-28
相关资源
最近更新 更多