tf.keras 计算训练期间的梯度

2024-10-04 01:30:36 发布

您现在位置:Python中文网/ 问答频道 /正文

根据所写内容here我试图在训练期间使用获得计算的梯度克拉斯特遣部队,我得到了以下回调函数,该函数在配件阶段调用:

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

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 one,和this one,但是没有运气


Tags: of函数inself网络formodelon
2条回答
AttributeError: 'NoneType' object has no attribute 'op' 

意味着你有一个对象或属性没有。
要处理它,您可以使用以下方法:

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

在python3.6.9上使用旧版本的keras(v.2.2.4)和tensorflow(1.13.1)解决了这个问题。你知道吗

相关问题 更多 >