【问题标题】:tf.keras get computed gradient during trainingtf.keras 在训练期间获得计算梯度
【发布时间】:2019-12-12 22:39:01
【问题描述】:

按照here 所写的内容,我试图在训练期间使用 tf.keras 获取计算梯度,我最终得到了在拟合阶段调用的以下回调函数:

使用的网络是一个非常标准的网络,完全连接和顺序。

r = network.fit(x=trn.X,y=trn.Y,verbose=2,batch_size=50,epochs=50,callbacks=[reporter,])
def on_train_begin(self, logs={}):

    # Functions return weights of each layer
    self.layerweights = []
    for lndx, l in enumerate(self.model.layers):
        if hasattr(l, 'kernel'):
            self.layerweights.append(l.kernel)

    input_tensors = [self.model.inputs[0],
                     self.model.sample_weights[0],
                     self.model.targets[0],
                     K.learning_phase()]

    # Get gradients of all the relevant layers at once
    grads = self.model.optimizer.get_gradients(self.model.total_loss, self.layerweights)
    self.get_gradients = K.function(inputs=input_tensors,outputs=grads) # <-- Error Here

其中出现以下错误信息:

~\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\eager\lift_to_graph.py in (.0)
    312   # Check that the initializer does not depend on any placeholders.
    313   sources = set(sources or [])
--> 314   visited_ops = set([x.op for x in sources])
    315   op_outputs = collections.defaultdict(set)
    316 

AttributeError: 'NoneType' object has no attribute 'op'

知道如何解决吗? 已阅读 this onethis one,但没有成功

【问题讨论】:

    标签: python tensorflow keras gradient


    【解决方案1】:
    AttributeError: 'NoneType' object has no attribute 'op' 
    

    意味着你有一个对象或属性得到了 None。
    要处理它,您可以使用它:

    visited_ops = set([x.op for x in sources if x])
    

    【讨论】:

      【解决方案2】:

      在 python 3.6.9 上使用旧版本的 keras(v. 2.2.4) 和 tensorflow (1.13.1) 解决了这个问题。

      【讨论】:

        猜你喜欢
        • 2020-09-21
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 2019-03-10
        • 1970-01-01
        • 2014-04-08
        • 2022-07-19
        • 2020-05-11
        相关资源
        最近更新 更多