【问题标题】:Using model.pop() changes the model's summary but does not effect the output使用 model.pop() 会更改模型的摘要,但不会影响输出
【发布时间】:2017-02-08 11:08:06
【问题描述】:

我正在尝试从我之前训练过的模型中删除顶层。 这是我使用的代码:

import os
import h5py
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers import Activation, Dropout, Flatten, Dense

# KERAS_BACKEND=theano python
import keras
keras.backend.set_image_dim_ordering("th")
img_width, img_height = 150, 150
data_dir = '//shared_directory/projects/try_CD/data/validation'

nb_train_samples = 2000
nb_validation_samples = 800
nb_epoch = 50



def make_bottleneck_features(model):
    datagen = ImageDataGenerator(rescale=1./255)
    generator = datagen.flow_from_directory(
            data_dir,
            target_size=(img_width, img_height),
            batch_size=32,
            class_mode=None,
            shuffle=False)
    bottleneck_features = model.predict_generator(generator, nb_validation_samples)
    return (bottleneck_features)


model=keras.models.load_model('/shared_directory/projects/think_exp/CD_M1.h5')
A = make_bottleneck_features(model)
model.summary()    
for i in range (6):  
    model.pop()    

B = make_bottleneck_features(model)
model.summary() 

比较对 model.summary() 的两次调用的结果,我可以看到确实移除了最顶层的 6 个。

但是,模型的输出(保存到 A 和 B)在丢弃这些层后不会改变。

这种差异的根源是什么? 如何检索所需层的输出而不是整个模型的输出?

提前致谢!

【问题讨论】:

    标签: keras keras-layer


    【解决方案1】:

    你不能像那样删除层,为了让它生效,你需要重新编译模型(AKA model.compile)。

    但这不是从中间层获取输出的最佳方法,您可以只使用 K.function(其中 K 是 keras.backend)从输入到其中一个层构建一个函数,然后调用该函数。更多详情可在this 答案中找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多