【问题标题】:Flipping tensor and fill with zeros in tensorflow在张量流中翻转张量并用零填充
【发布时间】:2023-03-29 16:46:02
【问题描述】:

我正在尝试为 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]]]

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

【问题讨论】:

    标签: python numpy tensorflow tensor


    【解决方案1】:

    您可以使用来自 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)>
    

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      相关资源
      最近更新 更多