Home > Mobile >  how to apply numpy function on a tensor with unknown shape
how to apply numpy function on a tensor with unknown shape

Time:10-14

I'm trying to construct a Keras layer which mimics NumPy prebuilt tile function like ([np.tile][1]). I've tried the following code but it didn't work

import tensorflow as tf
from tensorflow import keras
from keras import Input

class Tile(Layer):
    def __init__(self,repeat, **kwargs):
        self.repeat = repeat
        super(Tile,self).__init__(**kwargs)

    def call(self, x):
        return np.tile(x,self.repeat)

input= Input(shape= (3,))
repeat = (1,2)
x = Tile(repeat)(input)
model = keras.Model(input,x)
print(model(tf.ones(3,)))

error output:

---> x = Tile(repeat)(input)
NotImplementedError: Cannot convert a symbolic Tensor (Placeholder:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported

I think the issue relates to the unkown dimension of the batch size but I don't know how to handle it. Can anyone help please ?

CodePudding user response:

There are several problems here.

  1. Keras symbolic tensors can't be manipulated with NumPy. Either run eagerly or use Tensorflow operations
  2. You need to give 2d input to your model

Try this:

import tensorflow as tf
import numpy as np


class Tile(tf.keras.layers.Layer):
    def __init__(self, repeat, **kwargs):
        self.repeat = repeat
        super(Tile, self).__init__(**kwargs)

    def call(self, x):
        return tf.tile(x, self.repeat)


input = tf.keras.Input(shape=(3,))
repeat = (1, 2)
x = Tile(repeat)(input)
model = tf.keras.Model(input, x)
print(model(tf.ones((1, 3))))
tf.Tensor([[1. 1. 1. 1. 1. 1.]], shape=(1, 6), dtype=float32)
  • Related