Extracting last layers of keras model as a submodel

前端 未结 3 1502
不知归路
不知归路 2021-02-06 08:37

Say we have a convolutional neural network M. I can extract features from images by using

extractor = Model(M.inputs, M.get_layer(\'last_conv\').output)
feat         


        
3条回答
  •  半阙折子戏
    2021-02-06 09:27

    This is not the nicest solution, but it works:

    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)
    

提交回复
热议问题