Skip to main content
 首页 » 编程设计

python之Keras 无法在回调中计算图形节点

2024年12月31日9dudu

为了说明这个问题,请考虑以下模型的(完全人为的)示例:

import numpy as np 
from tensorflow.keras.utils import Sequence 
from tensorflow.keras.callbacks import Callback 
from tensorflow.keras import backend as K 
from tensorflow.keras.layers import Input, Dense 
from tensorflow.keras.models import Model 
 
class RandomSeq(Sequence): 
    def __len__(self): 
        return 5 
 
    def __getitem__(self, idx): 
        return (np.array([np.arange(39).reshape((39,)) for i in range(100)]),  
                np.array([-np.arange(39).reshape((39,)) for i in range(100)])) 
 
class Foo(Callback): 
    def __init__(self, d): 
        super(Foo, self).__init__() 
        self._d = d 
 
    def on_epoch_end(self, epoch, logs=None): 
        print(epoch) 
        print(K.eval(self._d)) 
 
 
 
x = Input(shape=(39,), dtype='float32', name='input') 
y_pred = Dense(39)(x) 
 
y_another = x * 2 
 
m = Model(inputs=x, outputs=y_pred) 
m.compile(optimizer='sgd', loss='mse') 
 
seq = RandomSeq() 
m.fit_generator(seq, epochs=5, callbacks=[Foo(y_another)]) 

RandomSeq 只是一个返回 x 和 y 批处理的序列。 Foo 是一个回调,它将尝试在纪元结束时评估附加数量 d。对我来说,如果我选择 d 为 y_pred 或 y_another,那么 Keras 会提示占位符 x (input) 未被馈送。

You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,39]

这是预期的行为吗?如果是这样,是否有另一种方法来计算 Keras 回调中的节点?请注意,如果没有计算上述图形节点的回调,则该示例可以正常工作。

请您参考如下方法:

这不是正确的做法。 运行 K.eval(y_another) 你要求 keras 后端评估一个 Input 对象(它只是你想输入网络的数据的占位符)而不用任何数据输入它,这就是你出错的原因。

因此,假设你想计算网络的输出,给定一个新的输入,这个新输入是一个随机序列乘以 2(这样对吗?),那么你应该修改 on_epoch_end(self, epoch , logs=None) 在你的回调中如下:

x, _ = next(RandomSeq())      
print(self.model.predict(x*2))