0

i would like to change this Pytorch code to Tensorflow, but after many attempts, I did not manage. Could you help me please?

class MeanShift(nn.Conv2D):
    def __init__(self, rgb_range, rgb_mean, rgb_std, sign=-1):
        super(MeanShift, self).__init__(3, 3, kernel_size=1)
        std = paddle.to_tensor(rgb_std)
        self.weight.set_value(paddle.eye(3).reshape([3, 3, 1, 1]))
        self.weight.set_value(self.weight / (std.reshape([3, 1, 1, 1])))

        mean = paddle.to_tensor(rgb_mean)
        self.bias.set_value(sign * rgb_range * mean / std)

        self.weight.trainable = False
        self.bias.trainable = False

I tried the following code: (where x is the output of the previous layer)

def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights
        weight_initer = tf.constant(shape=[1, 1, 3, 3], value=np.eye(3).reshape(1,  1, 3, 3), dtype=tf.float32)
        W = tf.Variable(weight_initer, name="Weight", dtype=tf.float32, shape=[1, 1, 3, 3])

        # Initilize bias
        bias_initer = tf.constant(shape=[3], value=[rgb_mean * rgb_range * sign], dtype=tf.float32)
        b = tf.Variable(bias_initer, name="Bias", dtype=tf.float32)

        x = Conv2D(3, 1, padding="same", kernel_initializer=keras.initializers.Constant(weight_initer), bias_initializer=keras.initializers.Constant(bias_initer))(x)
        return x

    return _func

And I get the error:

TypeError: Eager execution of tf.constant with unsupported shape. > Tensor [[[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]]] (converted from [[[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]]]) has 9 elements, but got shape (1, 1, 1, 3) with > 3 elements).

salomepx
  • 23
  • 1
  • 5
  • You would need to provide the code you have tried and specify the error if you want help debugging. – jodag Dec 06 '22 at 15:16

0 Answers0