数值错误:模型的输出张量必须是TensorFlow“层”的输出

30

我正在使用Keras构建模型,最后一层中使用了一些tensorflow函数(reduce_sum和l2_normalize),然后遇到了这个问题。我已经搜索了解决方案,但所有相关的都与“Keras张量”有关。

以下是我的代码:

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 的输出(因此包含过去层的元数据)。找到了: Tensor("l2_normalize_3:0", shape=(?, 3), dtype=float32)

我发现,如果不将 fc2 层传递给这些函数,则模型可以正常工作:

FC_model = Model(inputs = vgg16_model.input, outputs = fc2);

有人可以解释一下这个问题,并提出如何修复它的建议吗?

2个回答

40

我已经找到了一个解决问题的方法。

对于任何遇到相同问题的人,你可以使用Lambda层来包装你的Tensorflow操作,这就是我所做的:

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);

7
当使用Concatenate层时,我遇到了同样的问题:正确的写法是Concatenate()([<previous_layers>])。如果忘记了前面的(),就会出现错误提示。 - CGFoX

5

我的这个问题是因为在模型中某处我将两个张量相加写成了x1+x2,而不是使用Add()([x1,x2])

修改后问题得到解决。


1
类似的事情也发生在我身上;不是添加,而是切片。 - Yishai E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接