提取keras模型的最后一层作为子模型

ecl*_*que 9 python keras

假设我们有一个卷积神经网络 M。我可以通过使用从图像中提取特征

extractor = Model(M.inputs, M.get_layer('last_conv').output)
features = extractor.predict(X)
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到将使用预测类的模型features

我不能使用以下几行,因为它需要模型的输入作为占位符。

predictor = Model([M.get_layer('next_layer').input], M.outputs)
pred = predictor.predict(features)
Run Code Online (Sandbox Code Playgroud)

我也不能使用,K.function因为稍后我想将它用作另一个模型的一部分,所以我会将预测器应用于 tf.tensor,而不是 np.array。

Oli*_*ken 8

这不是最好的解决方案,但它有效:

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Dropout, Flatten

def cnn():
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3),
                     activation='relu',
                     input_shape=(28, 28, 1), name='l_01'))
    model.add(Conv2D(64, (3, 3), activation='relu', name='l_02'))
    model.add(MaxPooling2D(pool_size=(2, 2), name='l_03'))
    model.add(Dropout(0.25, name='l_04'))
    model.add(Flatten(name='l_05'))
    model.add(Dense(128, activation='relu', name='l_06'))
    model.add(Dropout(0.5, name='l_07'))
    model.add(Dense(10, activation='softmax', name='l_08'))
    return model

def predictor(input_shape):
    model = Sequential()
    model.add(Flatten(name='l_05', input_shape=(12, 12, 64)))
    model.add(Dense(128, activation='relu', name='l_06'))
    model.add(Dropout(0.5, name='l_07'))
    model.add(Dense(10, activation='softmax', name='l_08'))
    return model

cnn_model = cnn()
cnn_model.save('/tmp/cnn_model.h5')

predictor_model = predictor(cnn_model.output.shape)
predictor_model.load_weights('/tmp/cnn_model.h5', by_name=True)
Run Code Online (Sandbox Code Playgroud)