我正在使用 Keras(带有 tensorflow 后端)并尝试在训练期间在我的训练集上获取层输出(实际激活)(使用“fit”功能)
作为 on_batch_end 回调的一部分,有什么方法可以获取用于训练的最后一批的激活?或任何其他能够访问图层输出的方式?
我在下面找到了这段代码,但它再次对新数据运行前向传递。我正在尝试利用这样一个事实,即我的网络已经作为批处理本身训练的一部分进行了前向传递,并且只是提取了当前的激活,这可能吗?
def get_activations(model, model_inputs, print_shape_only=False, layer_name=None):
print('----- activations -----')
activations = []
inp = model.input
model_multi_inputs_cond = True
if not isinstance(inp, list):
# only one input! let's wrap it in a list.
inp = [inp]
model_multi_inputs_cond = False
outputs = [layer.output for layer in model.layers if
layer.name == layer_name or layer_name is None] # all layer outputs
funcs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs] # evaluation functions
if model_multi_inputs_cond:
list_inputs = []
list_inputs.extend(model_inputs)
list_inputs.append(0.)
else:
list_inputs = [model_inputs, 0.]
# Learning phase. 0 = Test mode (no dropout or batch normalization)
# layer_outputs = [func([model_inputs, 0.])[0] for func in funcs]
layer_outputs = [func(list_inputs)[0] for func in funcs]
for layer_activations in layer_outputs:
activations.append(layer_activations)
if print_shape_only:
print(layer_activations.shape)
else:
print(layer_activations)
return activations