首页 > 解决方案 > 设置模型的输入层时,“张量”对象不可调用

问题描述

我正在构建一个连体网络来接收 2 个图像输入,通过相同的卷积网络提取特征,然后计算图像的距离。

为了获得更好的准确性,我正在尝试为卷积层加载一个带有 imagenet 权重的预训练 Xception 模型,但只有第一层,因为我需要提取的特征比 imagenet 的图像简单得多(我需要检查手写文本之间的距离)。

这是我的模型架构的样子:

def siameseNet(input_shape):
    # Input tensors
    input1 = Input(input_shape)
    input2 = Input(input_shape)

    # Load the Xception model and freeze the layers
    xc = Xception(weights='imagenet', include_top=False, input_tensor=Input(shape=INPUT_SHAPE))
    for l in xc.layers:
        l.trainable = False

    # Create layer dict
    layers = dict([(l.name, l) for l in xc.layers])

    # I only want to use the first 3 conv blocks
    x = layers['block3_pool'].output

    # Add my custom top layer
    x = Flatten()(x)
    x = Dense(500, activation='sigmoid')(x)

    # Create two models, based on the same conv nets
    input_model_1 = x(input1)
    input_model_2 = x(input2)

    # Distance function tensor
    distance_func = Lambda(lambda t: K.abs(t[0]-t[1]))

    # Feed the distance function with the outputs
    distance_layer = distance_func([input_model_1, input_model_2])

    # Final prediction layer
    prediction = Dense(1,activation='sigmoid')(distance_layer)

    #Create the full siamese model
    network = Model(inputs=[input1,input2],outputs=prediction)

    return network

model = siameseNet((299,299,3))

但是当我打电话时,siameseNet我得到了错误:

38 39 ---> 40 模型 = siameseNet((299,299,3)) 中的 TypeError Traceback(最近一次调用最后一次)

in siameseNet(input_shape) 20 21 # 创建两个模型,基于相同的卷积网络 ---> 22 input_model_1 = x(input1) 23 input_model_2 = x(input2) 24

TypeError:“张量”对象不可调用

我之前在没有预训练模型的情况下完成了相同的任务,不同之处在于我没有构建自定义张量(x在本例中),而是使用了Sequential从头构建的模型。

我应该在我的模型中进行哪些更改才能使我的架构正常工作?

标签: keras

解决方案


您只能将张量传递给模型或图层,而不能直接传递给另一个张量。对于您的情况,您需要为连体分支构建一个临时模型:

xc_input = Input(shape=INPUT_SHAPE)
xc = Xception(weights='imagenet', include_top=False, input_tensor=xc_input)
for l in xc.layers:
    l.trainable = False

# Create layer dict
layers = dict([(l.name, l) for l in xc.layers])

# I only want to use the first 3 conv blocks
x = layers['block3_pool'].output

# Add my custom top layer
x = Flatten()(x)
x = Dense(500, activation='sigmoid')(x)

xc_branch = Model(xc_input, x)

# Create two models, based on the same conv nets
input_model_1 = xc_branch(input1)
input_model_2 = xc_branch(input2)

推荐阅读