ValueError:模型的输出张量必须是 TensorFlow `Layer` 的输出 [英] ValueError: Output tensors to a Model must be the output of a TensorFlow `Layer`
问题描述
我在最后一层使用一些张量流函数(reduce_sum 和 l2_normalize)在 Keras 中构建模型,同时遇到了这个问题.我已经寻找了一个解决方案,但所有这些都与Keras 张量"有关.
I'm building a model in Keras using some tensorflow function (reduce_sum and l2_normalize) in the last layer while encountered this problem. I have searched for a solution but all of it related to "Keras tensor".
这是我的代码:
import tensorflow as tf;
from tensorflow.python.keras import backend as K
vgg16_model = VGG16(weights = 'imagenet', include_top = False, input_shape = input_shape);
fire8 = extract_layer_from_model(vgg16_model, layer_name = 'block4_pool');
pool8 = MaxPooling2D((3,3), strides = (2,2), name = 'pool8')(fire8.output);
fc1 = Conv2D(64, (6,6), strides= (1, 1), padding = 'same', name = 'fc1')(pool8);
fc1 = Dropout(rate = 0.5)(fc1);
fc2 = Conv2D(3, (1, 1), strides = (1, 1), padding = 'same', name = 'fc2')(fc1);
fc2 = Activation('relu')(fc2);
fc2 = Conv2D(3, (15, 15), padding = 'valid', name = 'fc_pooling')(fc2);
fc2_norm = K.l2_normalize(fc2, axis = 3);
est = tf.reduce_sum(fc2_norm, axis = (1, 2));
est = K.l2_normalize(est);
FC_model = Model(inputs = vgg16_model.input, outputs = est);
然后是错误:
ValueError:模型的输出张量必须是模型的输出TensorFlow Layer
(因此保存过去的层元数据).成立:张量("l2_normalize_3:0", shape=(?, 3), dtype=float32)
ValueError: Output tensors to a Model must be the output of a TensorFlow
Layer
(thus holding past layer metadata). Found: Tensor("l2_normalize_3:0", shape=(?, 3), dtype=float32)
我注意到没有将 fc2 层传递给这些函数,模型工作正常:
I noticed that without passing fc2 layer to these functions, the model works fine:
FC_model = Model(inputs = vgg16_model.input, outputs = fc2);
有人可以向我解释这个问题并提供一些关于如何解决它的建议吗?
Can someone please explain to me this problem and some suggestion on how to fix it?
推荐答案
我找到了解决问题的方法.对于遇到同样问题的任何人,您可以使用Lambda层来包装您的tensorflow操作,这是我所做的:
I have found a way to work around to solve the problem. For anyone who encounters the same issue, you can use the Lambda layer to wrap your tensorflow operations, this is what I did:
from tensorflow.python.keras.layers import Lambda;
def norm(fc2):
fc2_norm = K.l2_normalize(fc2, axis = 3);
illum_est = tf.reduce_sum(fc2_norm, axis = (1, 2));
illum_est = K.l2_normalize(illum_est);
return illum_est;
illum_est = Lambda(norm)(fc2);
这篇关于ValueError:模型的输出张量必须是 TensorFlow `Layer` 的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!