Python 3.x 使用model.predict输出作为另一个模型的输入
我正在尝试使用Python 3.x 使用model.predict输出作为另一个模型的输入,python-3.x,tensorflow,neural-network,keras,deep-learning,Python 3.x,Tensorflow,Neural Network,Keras,Deep Learning,我正在尝试使用model.predict的输出作为另一个模型的输入。 这实际上是为了调试目的,也是为什么我不使用get\u layer.output或使用统一这两个模型的全局模型的原因 我遇到了以下错误: TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("input_1:0", shape=(?, 10, 10, 2048), dtype=float32) is not an element of this g
model.predict
的输出作为另一个模型的输入。
这实际上是为了调试目的,也是为什么我不使用get\u layer.output
或使用统一这两个模型的全局模型的原因
我遇到了以下错误:
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("input_1:0", shape=(?, 10, 10, 2048), dtype=float32) is not an element of this graph.
这是我目前的代码:
我使用下面的函数作为生成器
def test_model_predictions(params):
batch_size = params['batch_size'] #params just contains model parameters
base_model = create_model() #this just creates an instance of Inception model with final layers cutoff
train,_ = create_generators(params) #creats a generator for image files
while True:
for x, y in train:
predict1 = base_model.predict(x)
yield (predict1, y)
def training_bottleneck():
bottleneck_train = test_model_predictions(params) #generator
def bottleneck_model_1():
bottleneck_input = Input(shape = (10, 10, 2048))
x = GlobalAveragePooling2D()(bottleneck_input)
x = Dense(1024, activation='relu')(x)
predictions = Dense(params['classes'], activation='softmax')(x)
model = Model(inputs=bottleneck_input, outputs=predictions)
return model
model2 = bottleneck_model_1()
model2.compile(optimizer= optimizers.SGD(lr=0.0001, momentum=0.99),
loss='categorical_crossentropy', metrics = ['accuracy'])
print('Starting model training')
history = model2.fit_generator(bottleneck_train,
steps_per_epoch = 1000,
epochs = 85,
shuffle= False,
verbose = 2, )
return history
关于如何使这项工作起作用,有什么线索吗
多谢各位
编辑:对于我为什么这样做似乎有些困惑,所以我将添加更多信息
我特别使用了predict
,因为我在将model.predict值(瓶颈值)保存到hdf5文件,然后将这些值加载到另一个模型(原始模型的后半部分)时注意到了一个差异
而不是仅仅加载整个模型并冻结上半部分(无法训练上半部分)。我注意到尽管使用了相同的hypeparameters,
本质上相同的模型是,完整的模型正确地训练和收敛,而加载瓶颈值的模型并没有真正改善。
因此,我试图看到我融合了
模型。预测以保存瓶颈值是两个模型之间差异的原因 那么基本上你想用一个模型的预测作为第二个模型的输入?
在代码中,您将张量和“普通”python数据结构混为一谈,这无法工作,因为您必须使用张量构建孔计算图
我猜您想使用第一个模型的“预测”,并添加一些其他特性来使用第二个模型进行预测?在这种情况下,您可以这样做:
from keras.layers import Input, Dense, concatenate
input_1= Input(shape=(32,))
input_2= Input(shape=(64,))
out_1= Dense(48, input_shape=(32,))(input_1) # your model 1
x = concatenate([out_1, input_2]) # stack both feature vectors
x = Dense(1, activation='sigmoid')(x) # your model 2
model = Model(inputs=[input_1, input_2], outputs=[x]) # if you want the outputs of model 1 you can add the output out1
history = model.fit([x_train, x_meta_train], y_train, ...)
基本上,这意味着该变量与您当前运行的变量不在同一图形范围内定义。尝试在相同的图形范围内定义它们。我有点困惑如何正确地做到这一点,同时仍然使用model.predict作为第二个模型的输入(请参阅更新的OP)。我们能不能让两个单独的图按顺序工作?第一个Model.predict输出一个numpy数组,应该是一个单独的图。因为输出是一个数组而不是张量,我认为它不应该与第二个模型有任何联系,第二个模型应该是一个单独的图。弄不明白为什么所有的东西都需要在一个图中。有没有一种方法可以创建一个单独的图形,并且仍然使用model.predict作为第二个模型的输入?谢谢。我在OP中添加了更多信息,说明我为什么要使用model.predict作为输入。