0

I have a problem since i want to use the Numpy's gradient function in a keras model. I've tried to code a custom Layer with tensorflow operations but I'm still stuck with the numpy gradient function implementation. When i use this code :

@Tensorflow.numpy_function(Tout=Tensorflow.float32)
def tf_gradient(x):
    return Numpy.gradient(x, axis = 1)

class Inflections(Layer):
    def __init__(self, norm_max, axis = 1, **kwargs):
        super(Inflections, self).__init__(**kwargs)
        self.norm_max = norm_max
        self.axis = axis
        
    def call(self, x):
        d1 = tf_gradient(x, self.axis)
        d2 = tf_gradient(d1, self.axis)
        d2.set_shape(x.get_shape())
        infls = Tensorflow.experimental.numpy.diff(Tensorflow.math.sign(d2), axis = self.axis)
        inflections = Tensorflow.experimental.numpy.count_nonzero(infls, axis = self.axis)

        return 2 * inflections / self.norm_max

I'm getting an "InvalidArgumentError : Graph execution error" message during the model fitting because gradients cannot flow through numpy functions. It makes sense but i don't know how to solve my problem, i really need this function. Can anyone help me ?

Thank you.

Please don't focus too much about the presented code and the error. My problem is simple, i just need a way to use numpy's gradient function in a keras model. https://numpy.org/doc/stable/reference/generated/numpy.gradient.html

I've already tried a Lambda layer.

2
  • Neither sign nor count_nonzero have useful gradients, so you cannot train such a layer with gradient descent.
    – xdurch0
    Commented Feb 10 at 18:08
  • What does this have to do with the topic ? Commented Feb 11 at 9:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.