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.
sign
norcount_nonzero
have useful gradients, so you cannot train such a layer with gradient descent.