[英]ValueError: Output tensors to a Model must be the output of a TensorFlow `Layer`
I'm building a model in Keras using some tensorflow function (reduce_sum and l2_normalize) in the last layer while encountered this problem. 我在Keras的最后一层中使用一些tensorflow函数(reduce_sum和l2_normalize)构建模型,而遇到此问题。 I have searched for a solution but all of it related to "Keras tensor".
我一直在寻找解决方案,但所有解决方案都与“ Keras张量”有关。
Here is my code: 这是我的代码:
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);
and then the error: 然后是错误:
ValueError: Output tensors to a Model must be the output of a TensorFlow
Layer
(thus holding past layer metadata).ValueError:模型的输出张量必须是TensorFlow
Layer
的输出(因此保留过去的层元数据)。 Found: Tensor("l2_normalize_3:0", shape=(?, 3), dtype=float32)找到:Tensor(“ l2_normalize_3:0”,shape =(?, 3),dtype = float32)
I noticed that without passing fc2 layer to these functions, the model works fine: 我注意到,在不将fc2层传递给这些函数的情况下,该模型可以正常工作:
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? 有人可以向我解释这个问题以及如何解决的建议吗?
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:
对于遇到相同问题的任何人,您都可以使用Lambda层包装张量流操作,这就是我所做的:
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);
I had this issue because I was adding 2 tensors as x1+x2
somewhere in my model instead of using Add()([x1,x2])
. 我遇到了这个问题,因为我在模型中某处添加了两个张量
x1+x2
,而不是使用Add()([x1,x2])
。
That solved the problem. 那解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.