[keras] 模型保存、加载、model类方法、打印各层权重

893 阅读1分钟

1.模型保存

model.save_model()可以保存网络结构权重以及优化器的参数
model.save_weights() 仅仅保存权重

2.模型加载

from keras.models import load_model
load_model()只能load 由save_model保存的,将模型和weight全load进来

 filepath: String, path to the saved model.
 custom_objects: Optional dictionary mapping names
     (strings) to custom classes or functions to be
     considered during deserialization.
 compile: Boolean, whether to compile the model
     after loading.

model.load_weights(self, filepath, by_name=False):
在加载权重之前,model必须编译好

        metrics = ['accuracy']
        if self.nb_classes >= 10:
            metrics.append('top_k_categorical_accuracy')

       # self.input_shape = (seq_length, features_length)
        self.model,self.original_model = self.zf_model()
        optimizer = SGD(lr=1e-3)
        self.model.compile(loss='categorical_crossentropy', optimizer=optimizer,
                           metrics=metrics) #

3.sequential 和functional

序列式模型只能有单输入单输出,函数式模型可以有多个输入输出

4.model类

因为是继承, model对象有 container和layer的所有方法,可以用model对象访问下面三个类的所有方法

Model(Container)containerlayer
fitsummaryget_input_at(node_index)
evaluateget_layerget_input_at(node_index)
predictget_weightsget_config()
train on batchset_weightscompute_mask(x, mask)
test_on_batchget_configget_input_mask_at(node_index)
predict_on_batchcompute_output_shapeget_output_at(node_index)
evaluate_generator
predict_generator

Container

类属性,不是函数
        name
        inputs
        outputs
        input_layers
        output_layers
        input_spec 
        trainable (boolean)
        input_shape
        output_shape
        inbound_nodes: list of nodes
        outbound_nodes: list of nodes
        trainable_weights (list of variables)
        non_trainable_weights (list of variables)

layer.get_weights返回的是没有名字的权重array,Model.get_weights() 是他们的拼接,也没有名字,利用layer.weights 可以访问到后台的变量

5.打印各层权重


    for layer in model.layers:
        for weight in layer.weights:
            print weight.name,weight.shape
        #打印各层名字,权重的形状
block14_sepconv1/pointwise_kernel:0 (1, 1, 1024, 1536)
block14_sepconv1_bn/gamma:0 (1536,)
block14_sepconv1_bn/beta:0 (1536,)
block14_sepconv1_bn/moving_mean:0 (1536,
conv_att/bias:0 (5,)
linear_1/kernel:0 (2048, 256)
linear_1/bias:0 (256,)
linear_2/kernel:0 (2048, 256)
linear_2/bias:0 (256,)
linear_3/kernel:0 (2048, 256)
linear_3/bias:0 (256,)
linear_4/kernel:0 (2048, 256)
linear_4/bias:0 (256,)
linear_5/kernel:0 (2048, 256)
linear_5/bias:0 (256,)
rgb_softmax/kernel:0 (1280, 60)
rgb_softmax/bias:0 (60,)
from keras.applications.vgg16 import VGG16
# model.layers  ,layer.weights
model = VGG16()
names = [weight.name for layer in model.layers for weight in layer.weights]
weights = model.get_weights()
for name, weight in zip(names, weights):
    print(name, weight.shape)