python - 值错误 : Output tensors to a Model must be the output of a TensorFlow `Layer`

标签 python tensorflow machine-learning keras tensor

我在 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: 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 层传递给这些函数的情况下,模型可以正常工作:

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

有人可以向我解释一下这个问题以及如何解决它的一些建议吗?

最佳答案

我找到了解决问题的方法。 对于遇到相同问题的任何人,您可以使用 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);

关于python - 值错误 : Output tensors to a Model must be the output of a TensorFlow `Layer` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50715928/

相关文章:

python - 我如何跟踪大量请求的进度?

tensorflow - 如何仅定义 Tensorflow 子图的梯度?

tensorflow - 加载模型后 Keras 精度低

python - 对连接的字符串进行标记

json - 机器学习友好的数据组织

python - to_json() 函数错误地导出了带有 float64 的 Pandas 数据框

python - 如何创建一个将行移动负 1 的 DataFrame,包括上面的行可能不存在的时间?

Tensorflow 1.0 Windows + 64 位 Anaconda 4.3.0 错误

machine-learning - Weka 的预测范围限制

python - Django 迭代列表中的字典并在模板中显示数据