gpt4 book ai didi

python - 用于两个 3dim 矩阵的 numpy einsum 的 Theano 版本

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:19 25 4
gpt4 key购买 nike

我有两个 3dim numpy 矩阵,我想根据一个轴做一个点积,而不用在 theano 中使用循环。带有示例数据的 numpy 解决方案如下:

a=[ [[ 0, 0, 1, 1, 0,  0,  0,  0,  0,  0,  1,  0,  0,  1,  0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]],
[[ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]],
[ [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]],
[ [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]],
[[ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[ 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 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0.],
[ 0, 1, 0, 0, 0.]]]
dt = np.dtype(np.float32)
a=np.asarray(a,dtype=dt)
b=np.asarray(b,dtype=dt)
print(a.shape)
print(b.shape)

其中“a”的形状为 (7, 4, 15),“b”的形状为 (7, 4, 5)。 “c”,定义为“a”和“b”的点积:

c = np.einsum('ijk,ijl->ilk',a,b)

我正在寻找这个例子的 theano 实现来计算“c”。

有什么想法吗?

最佳答案

完成本题:

import theano as th
import then.Tensor as T

ta = T.tensor3('a')
tb = T.tensor3('b')

tc = T.batched_tensordot(ta, tb, axes=[[1],[1]])

……

关于python - 用于两个 3dim 矩阵的 numpy einsum 的 Theano 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34005271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com