对多个深度学习网络的相同输入

时间:2019-10-11 00:25:32

标签: python tensorflow keras

我正在尝试使用VGG16和VGG19创建像此处提到的塔(How to have parallel convolutional layers in keras?)那样的塔。我正在使用flow_from_directory从目录中读取图像以进行训练并有效。我将使用预先训练的imagenet-weights加载VGG16和VGG19,然后合并这些图层作为其他模型的输入。我在尝试弄清楚如何将相同的输入馈送到多个模型时遇到问题。 我在一个正在使用的论坛中遇到了这个生成器函数。这会将多个图像作为输入送入网络。但是,对于我的情况来说,这似乎是过大的选择。

def generate_generator_multiple(generator,dir1, dir2, batch_size, img_height,img_width):
    genX1 = generator.flow_from_directory(dir1, target_size = (img_height,img_width), class_mode = 'categorical', batch_size = batch_size, shuffle=False, seed=7)
    genX2 = generator.flow_from_directory(dir2, target_size = (img_height,img_width), class_mode = 'categorical', batch_size = batch_size, shuffle=False, seed=7)
    while True:
            X1i = genX1.next()
            X2i = genX2.next()

            yield [X1i[0], X2i[0]], X2i[1]  #Yield both images and their mutual label 

有没有更简单的方法将相同的输入馈送到多个网络,而不是提供多个输入。 我已经尝试过https://datascience.stackexchange.com/questions/30423/how-to-pass-common-inputs-to-a-merged-model-in-keras?answertab=active#tab-top中的代码, 但这给了我Graph断开连接错误。

1 个答案:

答案 0 :(得分:0)

这是一个向您展示如何执行此操作的简单示例,关键是将神经网络模型放入一个函数中

import keras
import numpy as np
import tensorflow as tf
from keras.layers import Input, Dense

tf.reset_default_graph()

# assume this is your model
def nn_model(input_x, n):
    feature_maker = Dense(n, activation='relu')(input_x)
    feature_maker = Dense(20, activation='relu')(feature_maker)
    feature_maker = Dense(1, activation='linear')(feature_maker)
    return feature_maker

input_layer = Input(shape=(3, ))
output_1 = nn_model(input_layer, 10)
output_2 = nn_model(input_layer, 20)
output_3 = nn_model(input_layer, 30)

model = keras.models.Model(inputs=input_layer, outputs=[output_1, output_2, output_3])

您可以通过以下方式绘制此模型

from keras.utils.vis_utils import plot_model

plot_model(model, show_shapes=True)

模型看起来像

enter image description here

该模型可以通过

进行训练
model.compile(loss='mse', optimizer='adam')

# example training set
x = np.linspace(1, 90, 270).reshape(90, 3)
y1 = np.random.rand(90)
y2 = np.random.rand(90) * 2
y3 = np.random.rand(90) * 3

model.fit(x, [y1, y2, y3], batch_size=32, epochs=10)