[keras] 模型保存、加载、model类方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013608336/article/details/82664529

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) container layer
fit summary get_input_at(node_index)
evaluate get_layer get_config()
predict get_weights compute_mask(x, mask)
train on batch set_weights get_input_mask_at(node_index)
test_on_batch get_config get_output_at(node_index)
predict_on_batch compute_output_shape
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 可以访问到后台的变量

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)

猜你喜欢

转载自blog.csdn.net/u013608336/article/details/82664529