keras 用于多输入图像的VGG16网络

o0lyfsai  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(169)

我正在尝试使用VGG16网络来处理多个输入图像。使用一个简单的CNN和2个输入来训练这个模型给了我大约50%的加速率,这就是为什么我想使用一个像VGG16这样的成熟模型来尝试它。
以下是我尝试过的方法:

# imports
from keras.applications.vgg16 import VGG16
from keras.models import Model
from keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense

def def_model():
    model = VGG16(include_top=False, input_shape=(224, 224, 3))
    # mark loaded layers as not trainable
    for layer in model.layers:
        layer.trainable = False
    # return last pooling layer
    pool_layer = model.layers[-1].output
    return pool_layer

m1 = def_model()
m2 = def_model() 
m3 = def_model()

# add classifier layers
merge = concatenate([m1, m2, m3])

# optinal_conv = Conv2D(64, (3, 3), activation='relu', padding='same')(merge)
# optinal_pool = MaxPooling2D(pool_size=(2, 2))(optinal_conv)
# flatten = Flatten()(optinal_pool)

flatten = Flatten()(merge)
dense1 = Dense(512, activation='relu')(flatten)
dense2 = Dropout(0.5)(dense1)
output = Dense(1, activation='sigmoid')(dense2)

inshape1 = Input(shape=(224, 224, 3))
inshape2 = Input(shape=(224, 224, 3))
inshape3 = Input(shape=(224, 224, 3))
model = Model(inputs=[inshape1, inshape2, inshape3], outputs=output)

1.调用Model函数时出现此错误。

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_21:0", shape=(?, 224, 224, 3), dtype=float32) at layer "input_21". The following previous layers were accessed without issue: []`

我知道这张图是断开的,但我找不到断开的地方。
下面是compilefit函数。

# compile model
model.compile(optimizer="Adam", loss='binary_crossentropy', metrics=['accuracy'])
model.fit([train1, train2, train3], train, 
           validation_data=([test1, test2, test3], ytest))

1.我曾评论过一些台词:optinal_convoptinal_pool。在concatenate函数之后应用Conv2DMaxPooling2D会有什么影响?

bnl4lu3b

bnl4lu3b1#

我建议查看Multi-input Multi-output Model with Keras Functional API的答案。下面是一种实现此目的的方法:

# 3 inputs 
input0 = tf.keras.Input(shape=(224, 224, 3), name="img0")
input1 = tf.keras.Input(shape=(224, 224, 3), name="img1")
input2 = tf.keras.Input(shape=(224, 224, 3), name="img2")
concate_input = tf.keras.layers.Concatenate()([input0, input1, input2])
# get 3 feature maps with same size (224, 224)
# pretrained models needs that
input = tf.keras.layers.Conv2D(3, (3, 3), 
                     padding='same', activation="relu")(concate_input)

# pass that to imagenet model 
vg = tf.keras.applications.VGG16(weights=None,
                                 include_top = False, 
                                 input_tensor = input)

# do whatever 
gap = tf.keras.layers.GlobalAveragePooling2D()(vg.output)
den = tf.keras.layers.Dense(1, activation='sigmoid')(gap)

# build the complete model 
model = tf.keras.Model(inputs=[input0, input1, input2], outputs=den)

相关问题