在https://numpy.org/doc/stable/reference/generated/numpy.einsum.html 中提到
廣播和標量乘法: np.einsum('..., ...', 3, c) array([[ 0, 3, 6],[ 9, 12, 15]])
似乎 einsum 可以模仿 DGEMM 中的預因子 alpha/beta http://www.netlib.org/lapack/explore-html/d1/d54/group__double__blas__level3_gaeda3cbd99c8fb834a60a6412878226e1.html
這是否意味著它(包括 einsum 中的標量乘法作為一個步驟)將比兩個步驟更快:(1)A,B->C和(2)C*prefactor?
我嘗試將https://ajcr.net/Basic-guide-to-einsum/擴展為
import numpy as np
A = np.array([0, 1, 2])
B = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
C = np.einsum('i,ij->i', 2., A, B)
print(C)
得到了ValueError: einstein sum subscripts string contains too many subscripts for operand。
所以,我的問題是,有沒有什么方法可以在 einsum 中包含標量因子并加速計算?
uj5u.com熱心網友回復:
我沒有使用過這個scalar功能,但它是這樣作業的:
In [422]: np.einsum('i,ij->i',A,B)
Out[422]: array([ 0, 22, 76])
In [423]: np.einsum(',i,ij->i',2,A,B)
Out[423]: array([ 0, 44, 152])
節省的時間似乎很少
In [424]: timeit np.einsum(',i,ij->i',2,A,B)
11.5 μs ± 271 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
In [425]: timeit 2*np.einsum('i,ij->i',A,B)
12.3 μs ± 274 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
另一個例子:
In [427]: np.einsum(',i,,ij->i',3,A,2,B)
Out[427]: array([ 0, 132, 456])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480773.html
上一篇:檢查陣列是否具有相同的值
