【问题标题】:Operation from each vector in a 2D tensor on each 2D matrix in a 3D tensor从 2D 张量中的每个向量对 3D 张量中的每个 2D 矩阵进行操作
【发布时间】:2019-12-03 04:27:39
【问题描述】:

我有一个二维张量。我想将该 2D 张量中的每个向量和 tf.tensordot(vector, matrix, axes=1) 带到 3D 张量中的矩阵,该矩阵在 3D 张量中与向量在 2D 张量中具有相同的索引。

本质上,我希望得到与使用此 for 循环相同的结果,但通过执行 tensorflow 矩阵运算而不是 numpy 和循环:

tensor2d = np.array([[1.,1.,1.,0.,0.],
                 [1.,1.,0.,0.,0.]],
                np.float32)

tensor3d = np.array([
    [
        [1., 2., 3.],
        [2., 2., 3.],
        [3., 2., 3.],
        [4., 2., 3.],
        [5., 2., 3.],
    ],
    [
        [1., 2., 3.],
        [2., 2., 3.],
        [3., 2., 3.],
        [4., 2., 3.],
        [5., 2., 3.],
    ]
], np.float32)

results = []

for i in range(len(tensor2d)):
    results.append(np.tensordot(tensor2d[i], tensor3d[i], axes=1))

它的输出应该是一个看起来像这样的矩阵(尽管类型会不同):

[array([6., 6., 9.], dtype=float32), array([3., 4., 6.], dtype=float32)]

【问题讨论】:

    标签: tensorflow tensordot


    【解决方案1】:

    好的,自行找到的答案归结为使用tf.math.multiply 并在转置上乱七八糟,直到结果是所需的形状。如果有人能在某个时候提出一个更有原则的答案,那就太好了,但就目前而言,这是可行的:

    result = tf.transpose(tf.math.multiply(tensor2d, tensor3d.transpose([2,0,1])), [1,2,0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-02
      • 2018-05-02
      • 2018-05-15
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 2020-12-04
      • 2018-05-04
      相关资源
      最近更新 更多