翻转张量并在张量流中填充零

Flipping tensor and fill with zeros in tensorflow

我正在尝试为 tensorflow 张量实现这个有效的 numpy 代码,它上下左右翻转内核的一部分,然后添加一些零。

import numpy as np
kernel = np.array([[1,2,3,],[4,5,6],[7,8,9]]).reshape(1,3,3)
K = np.zeros((1,5,5))

K[:, 0:1 + 1, 0:1 + 1] = kernel[:, 1:, 1:]
K[:, -1:, 0:1 + 1] = kernel[:, 0:1, -2:]
K[:, 0:1 + 1, -1:] = kernel[:, -2:, 0:1]
K[:, -1:, -1:] = kernel[:, 0:1, 0:1]

那么结果是:

K = [[[5, 6, 0, 0, 4],
      [8, 9, 0, 0, 7],
      [0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0],
      [2, 3, 0, 0, 1]]]

内核作为张量流张量出现,具有可训练的权重,尺寸为 1x3x3。因此它不是一个 numpy 数组,所以我不能像上面的代码那样对它进行切片。将张量转换为 numpy 数组是不可取的,因为此操作应该发生在神经网络的一层中。 有人能想出用张量完成这个的好方法吗?

您可以使用 tf.Variable 中的分配。 tf.Tensor支持像numpy一样的拼接选择

kernel = tf.constant(np.array([[1,2,3,],[4,5,6],[7,8,9]]).reshape(1,3,3), dtype=tf.float32) # tf.Tensor
k = tf.Variable(np.zeros((1,5,5)), dtype=tf.float32) # tf.Variable

k[:, 0:1 + 1, 0:1 + 1].assign(kernel[:, 1:, 1:])
k[:, -1:, 0:1 + 1].assign(kernel[:, 0:1, -2:])
k[:, 0:1 + 1, -1:].assign(kernel[:, -2:, 0:1])
k[:, -1:, -1:].assign(kernel[:, 0:1, 0:1])

<tf.Variable 'Variable:0' shape=(1, 5, 5) dtype=float32, numpy=
array([[[5., 6., 0., 0., 4.],
        [8., 9., 0., 0., 7.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [2., 3., 0., 0., 1.]]], dtype=float32)>