Keras - 模块

  • 简述

    如前所述,Keras 模型代表了实际的神经网络模型。Keras 提供了两种模式来创建模型,简单易用的Sequential API以及更灵活和高级的Functional API。现在让我们在本章中学习使用SequentialAPI和功能API 创建模型。
  • Sequential

    Sequential API的核心思想是简单地按Sequential排列 Keras 层,因此,它被称为Sequential API。大多数 ANN 也有按Sequential排列的层,数据按照给定的Sequential从一层流到另一层,直到数据最终到达输出层。
    可以通过简单地调用Sequential() API 来创建 ANN 模型,如下所示 -
    
    
    from keras.models import Sequential 
    
    model = Sequential()
    
    

    添加图层

    要添加一个层,只需使用 Keras 层 API 创建一个层,然后通过 add() 函数传递该层,如下所示 -
    
    
    from keras.models import Sequential 
    
    
    
    model = Sequential() 
    
    input_layer = Dense(32, input_shape=(8,)) model.add(input_layer) 
    
    hidden_layer = Dense(64, activation='relu'); model.add(hidden_layer) 
    
    output_layer = Dense(8) 
    
    model.add(output_layer)
    
    
    在这里,我们创建了一个输入层、一个隐藏层和一个输出层。

    访问模型

    Keras 提供了一些方法来获取模型信息,如层、输入数据和输出数据。它们如下 -
    • model.layers - 将模型的所有层作为列表返回。
    
    
    >>> layers = model.layers 
    
    >>> layers 
    
    [
    
       <keras.layers.core.Dense object at 0x000002C8C888B8D0>, 
    
       <keras.layers.core.Dense object at 0x000002C8C888B7B8>
    
       <keras.layers.core.Dense object at 0x 000002C8C888B898>
    
    ]
    
    
    • model.inputs - 将模型的所有输入张量作为列表返回。
    
    
    >>> inputs = model.inputs 
    
    >>> inputs 
    
    [<tf.Tensor 'dense_13_input:0' shape=(?, 8) dtype=float32>]
    
    
    • model.outputs - 将模型的所有输出张量作为列表返回。
    
    
    >>> outputs = model.outputs 
    
    >>> outputs 
    
    <tf.Tensor 'dense_15/BiasAdd:0' shape=(?, 8) dtype=float32>]
    
    
    • model.get_weights - 将所有权重作为 NumPy 数组返回。
    • model.set_weights(weight_numpy_array) - 设置模型的权重。

    序列化模型

    Keras 提供了将模型序列化为对象以及 json 并稍后再次加载它的方法。它们如下 -
    • get_config() - 将模型作为对象返回。
    
    
    config = model.get_config()
    
    
    • from_config() - 它接受模型配置对象作为参数并相应地创建模型。
    
    
    new_model = Sequential.from_config(config)
    
    
    • to_json() - 将模型作为 json 对象返回。
    
    
    >>> json_string = model.to_json() 
    
    >>> json_string '{"class_name": "Sequential", "config": 
    
    {"name": "sequential_10", "layers": 
    
    [{"class_name": "Dense", "config": 
    
    {"name": "dense_13", "trainable": true, "batch_input_shape": 
    
    [null, 8], "dtype": "float32", "units": 32, "activation": "linear", 
    
    "use_bias": true, "kernel_initializer": 
    
    {"class_name": "Vari anceScaling", "config": 
    
    {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}},
    
    "bias_initializer": {"class_name": "Zeros", "conf 
    
    ig": {}}, "kernel_regularizer": null, "bias_regularizer": null, 
    
    "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, 
    
    {" class_name": "Dense", "config": {"name": "dense_14", "trainable": true, 
    
    "dtype": "float32", "units": 64, "activation": "relu", "use_bias": true, 
    
    "kern el_initializer": {"class_name": "VarianceScaling", "config": 
    
    {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, 
    
    "bias_initia lizer": {"class_name": "Zeros", 
    
    "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, 
    
    "activity_regularizer": null, "kernel_constraint" : null, "bias_constraint": null}}, 
    
    {"class_name": "Dense", "config": {"name": "dense_15", "trainable": true, 
    
    "dtype": "float32", "units": 8, "activation": "linear", "use_bias": true, 
    
    "kernel_initializer": {"class_name": "VarianceScaling", "config": 
    
    {"scale": 1.0, "mode": "fan_avg", "distribution": " uniform", "seed": null}}, 
    
    "bias_initializer": {"class_name": "Zeros", "config": {}}, 
    
    "kernel_regularizer": null, "bias_regularizer": null, "activity_r egularizer": 
    
    null, "kernel_constraint": null, "bias_constraint": 
    
    null}}]}, "keras_version": "2.2.5", "backend": "tensorflow"}' 
    
    >>>
    
    
    • model_from_json() - 接受模型的 json 表示并创建一个新模型。
    
    
    from keras.models import model_from_json 
    
    new_model = model_from_json(json_string)
    
    
    • to_yaml() - 将模型作为 yaml 字符串返回。
    
    
    >>> yaml_string = model.to_yaml() 
    
    >>> yaml_string 'backend: tensorflow\nclass_name: 
    
    Sequential\nconfig:\n layers:\n - class_name: Dense\n config:\n 
    
    activation: linear\n activity_regular izer: null\n batch_input_shape: 
    
    !!python/tuple\n - null\n - 8\n bias_constraint: null\n bias_initializer:\n 
    
    class_name : Zeros\n config: {}\n bias_regularizer: null\n dtype: 
    
    float32\n kernel_constraint: null\n 
    
    kernel_initializer:\n cla ss_name: VarianceScaling\n config:\n 
    
    distribution: uniform\n mode: fan_avg\n 
    
    scale: 1.0\n seed: null\n kernel_regularizer: null\n name: dense_13\n 
    
    trainable: true\n units: 32\n 
    
    use_bias: true\n - class_name: Dense\n config:\n activation: relu\n activity_regularizer: null\n 
    
    bias_constraint: null\n bias_initializer:\n class_name: Zeros\n 
    
    config : {}\n bias_regularizer: null\n dtype: float32\n 
    
    kernel_constraint: null\n kernel_initializer:\n class_name: VarianceScalin g\n 
    
    config:\n distribution: uniform\n mode: fan_avg\n scale: 1.0\n 
    
    seed: null\n kernel_regularizer: nu ll\n name: dense_14\n trainable: true\n 
    
    units: 64\n use_bias: true\n - class_name: Dense\n config:\n 
    
    activation: linear\n activity_regularizer: null\n 
    
    bias_constraint: null\n bias_initializer:\n 
    
    class_name: Zeros\n config: {}\n bias_regu larizer: null\n 
    
    dtype: float32\n kernel_constraint: null\n 
    
    kernel_initializer:\n class_name: VarianceScaling\n config:\n 
    
    distribution: uniform\n mode: fan_avg\n 
    
    scale: 1.0\n seed: null\n kernel_regularizer: null\n name: dense _15\n 
    
    trainable: true\n units: 8\n 
    
    use_bias: true\n name: sequential_10\nkeras_version: 2.2.5\n' 
    
    >>>
    
    
    • model_from_yaml() - 接受模型的 yaml 表示并创建一个新模型。
    
    
    from keras.models import model_from_yaml 
    
    new_model = model_from_yaml(yaml_string)
    
    

    总结模型

    理解模型是正确使用模型进行训练和预测的非常重要的阶段。Keras 提供了一种简单的方法,summary 以获取有关模型及其层的完整信息。
    上一节中创建的模型摘要如下 -
    
    
    >>> model.summary() Model: "sequential_10" 
    
    _________________________________________________________________ 
    
    Layer (type) Output Shape Param 
    
    #================================================================ 
    
    dense_13 (Dense) (None, 32) 288 
    
    _________________________________________________________________ 
    
    dense_14 (Dense) (None, 64) 2112 
    
    _________________________________________________________________ 
    
    dense_15 (Dense) (None, 8) 520 
    
    ================================================================= 
    
    Total params: 2,920 
    
    Trainable params: 2,920 
    
    Non-trainable params: 0 
    
    _________________________________________________________________ 
    
    >>>
    
    

    训练和预测模型

    模型为训练、评估和预测过程提供功能。它们如下 -
    • compile - 配置模型的学习过程
    • fit - 使用训练数据训练模型
    • evaluate- 使用测试数据评估模型
    • predict - 预测新输入的结果。
  • 函数式 API

    Sequential API 用于逐层创建模型。功能 API 是创建更复杂模型的另一种方法。功能模型,您可以定义共享层的多个输入或输出。首先,我们为模型创建一个实例并连接到层以访问模型的输入和输出。本节简要介绍功能模型。

    创建模型

    使用以下模块导入输入层 -
    
    
    >>> from keras.layers import Input
    
    
    现在,使用以下代码创建一个输入层,指定模型的输入尺寸形状 -
    
    
    >>> data = Input(shape=(2,3))
    
    
    使用以下模块为输入定义层 -
    
    
    >>> from keras.layers import Dense
    
    
    使用下面的代码行为输入添加密集层 -
    
    
    >>> layer = Dense(2)(data) 
    
    >>> print(layer) 
    
    Tensor("dense_1/add:0", shape =(?, 2, 2), dtype = float32)
    
    
    使用以下模块定义模型 -
    
    
    from keras.models import Model
    
    
    通过指定输入和输出层以功能方式创建模型 -
    
    
    model = Model(inputs = data, outputs = layer)
    
    
    创建简单模型的完整代码如下所示 -
    
    
    from keras.layers import Input 
    
    from keras.models import Model 
    
    from keras.layers import Dense 
    
    
    
    data = Input(shape=(2,3)) 
    
    layer = Dense(2)(data) model = 
    
    Model(inputs=data,outputs=layer) model.summary() 
    
    _________________________________________________________________ 
    
    Layer (type)               Output Shape               Param # 
    
    ================================================================= 
    
    input_2 (InputLayer)       (None, 2, 3)               0 
    
    _________________________________________________________________ 
    
    dense_2 (Dense)            (None, 2, 2)               8 
    
    ================================================================= 
    
    Total params: 8 
    
    Trainable params: 8 
    
    Non-trainable params: 0 
    
    _________________________________________________________________