假定从标量到固定尺寸的矩阵的映射。 如何有效地创建此地图的矢量化版本?
更具体地说,假设存在一个带有n个条目的恒定向量lamb。 给定标量t,我对
给出的对角矩阵感兴趣np.diag(np.exp(lamb*t))
使用numpy。
这将是一个n×n的矩阵。
现在给定一个大小为m_1乘以m_2的矩阵T,我想计算形状张量D(m_1,m_2,n,n),其中0 <= i 一个人如何有效地获得这个张量?D[i,j,:,:] = np.diag(np.exp(lamb*T[i,j]))
答案 0 :(得分:1)
一种相对简单的方法是使用einsum
。
示例:
>>> T = np.array([[1,2,3], [4,6,7]])
>>> lam = np.array([1,2,5])
>>> D = np.zeros((*T.shape, n, n))
>>> np.einsum('ijkk->ijk', D)[...] = np.exp(np.multiply.outer(T, lam))
>>> D
array([[[[2.71828183e+00, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 7.38905610e+00, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 1.48413159e+02]],
[[7.38905610e+00, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 5.45981500e+01, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 2.20264658e+04]],
[[2.00855369e+01, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 4.03428793e+02, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 3.26901737e+06]]],
[[[5.45981500e+01, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 2.98095799e+03, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 4.85165195e+08]],
[[4.03428793e+02, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 1.62754791e+05, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 1.06864746e+13]],
[[1.09663316e+03, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 1.20260428e+06, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 1.58601345e+15]]]])
您可以使用out
关键字来加快速度,以避免重复:
np.exp(np.multiply.outer(T, lam), out=np.einsum('ijkk->ijk', D))