簡體   English   中英

tf.keras 在訓練期間獲得計算梯度

[英]tf.keras get computed gradient during training

按照這里寫的內容我試圖在訓練期間使用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'

知道如何解決嗎? 已經閱讀了這一本這一本,但沒有運氣

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

意味着你有一個對象或屬性沒有。
要處理它,您可以使用它:

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

在 python 3.6.9 上使用舊版本的 keras(v. 2.2.4) 和 tensorflow (1.13.1) 解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM