Keras Tips

Rename layer

参考:Keras - All layer names should be unique

for layer in model2.layers:
    layer.name = layer.name + str("_2")
View layer
def view_model_layers(model):
    for i, layer in enumerate(model.layers):
        print(i, layer.name)
多模型融合

参考:keras实现多个模型融合(非keras自带模型,这里以3个自己的模型为例)

如何从预训练的ResNet模型Keras层中提取特征

feature = model.layers[-5].output

Keras迁移学习提取特征 之 finetune InceptionV3

# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.

# let's visualize layer names and layer indices to see how many layers
# we should freeze:
for i, layer in enumerate(base_model.layers):
   print(i, layer.name)

# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 172 layers and unfreeze the rest:
for layer in model.layers[:172]:
   layer.trainable = False
for layer in model.layers[172:]:
   layer.trainable = True

# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')

# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.fit_generator(...)

【Keras初学】keras构建两种特征输入,两个输出同时训练

model = Model(inputs=[main_input, aux_input], outputs=[main_output, aux_output])
#model.compile(optimizer='rmsprop', loss='binary_crossentropy', loss_weights=[1., 0.2])
model.compile(optimizer='rmsprop', 
            loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},
            loss_weights={'main_output': 1., 'aux_output': 0.3})
 
#train data
samples_len = 300
main_data = np.random.randint(1, 10000,size=(samples_len, 100), dtype='int32')
aux_data = np.random.randint(0,10,size=(samples_len,5), dtype='int32')
main_labels = np.random.randint(0,2,size=(samples_len,1), dtype='int32')

model.fit(x={'main_input': main_data, 'aux_input': aux_data},
            y={'main_output': main_labels, 'aux_output': main_labels},
            batch_size=32, epochs=10,verbose=1)
 
score = model.evaluate(x={'main_input': main_data, 'aux_input': aux_data},
            y={'main_output': main_labels, 'aux_output': main_labels},
            batch_size=10, verbose=1)
模型可视化

参考:Docs » Other » 模型可视化

from keras.utils import plot_model
plot_model(model, to_file='model.png', show_shapes=True)

你可能感兴趣的:(Keras Tips)