【问题标题】:how to Edit the GradientTape function in the keras source code如何在keras源码中编辑GradientTape函数
【发布时间】:2022-01-23 10:47:28
【问题描述】:

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/eager/backprop.py#L994-L1095这里是'GradientTape'函数的源代码,但是修改源代码不影响后续回答中的函数。

    flat_grad = imperative_grad.imperative_grad(
        self._tape,
        flat_targets,
        flat_sources,
        output_gradients=output_gradients,
        sources_raw=flat_sources_raw,
        unconnected_gradients=unconnected_gradients)

    if not self._persistent:
      # Keep track of watched variables before setting tape to None
      self._watched_variables = self._tape.watched_variables()
      self._tape = None

    grad = nest.pack_sequence_as(sources, flat_grad)
    return 0

这里我改变了return语句。但是使用

x = tf.Variable(3.0)

with tf.GradientTape() as tape:
  y = x**2
dy_dx = tape.gradient(y, x)
dy_dx.numpy()

输出为 6.0 还有什么需要改变的?

【问题讨论】:

    标签: python keras gradient gradienttape


    【解决方案1】:

    您不应该编辑已安装的软件包。

    由于tf.GradientTape是一个类,你可以inherit这个类并重写.gradient方法来返回你想要的值。

    from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients
    
    class TestGradientTape(tf.GradientTape):
        def gradient(self,
                     target,
                     sources,
                     output_gradients=None,
                     unconnected_gradients=UnconnectedGradients.NONE):
    
            # Calls the original .gradient method from the parent class
            super().gradient(target, sources, output_gradients, unconnected_gradients)
            
            # Returns 0 instead of whatever the above method gave you
            return 0
    
    # Now you can use TestGradientTape instead of tf.GradientTape
    
    with TestGradientTape() as tape:
      y = x**2
    
    # And this should go through our overriden method from TestGradientTape
    dy_dx = tape.gradient(y, x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多