简体   繁体   中英

Flipping tensor and fill with zeros in tensorflow

I am trying to implement this working numpy code for tensorflow tensors, which flips a part of the kernel up-down and left-right and then adds some zeros.

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]

The result then is:

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]]]

The kernel comes as a tensorflow tensor with trainable weights with dimensions 1x3x3. Thus it is not a numpy array, so I cannot slice it like in the code above. Converting the tensor into a numpy array is no option since this operation should take place in a layer of a neural network. Can anybody think of a good way to accomplish this with tensors?

you can use assign from tf.Variable. tf.Tensor support splice selection like 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)>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM