📅  最后修改于: 2020-12-11 04:57:18             🧑  作者: Mango
如前所述,Keras模型代表实际的神经网络模型。 Keras提供了两种创建模型的模式:简单易用的Sequential API以及更灵活,更高级的Functional API 。现在让我们学习本章中同时使用顺序API和功能API创建模型的方法。
顺序API的核心思想是简单地按顺序排列Keras层,因此,它称为顺序API 。大部分的ANN还具有顺序排列的层,并且数据以给定的顺序从一层流到另一层,直到数据最终到达输出层。
可以通过简单地调用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
[
,
]
model.inputs-将模型的所有输入张量作为列表返回。
>>> inputs = model.inputs
>>> inputs
[]
model.outputs-将模型的所有输出张量作为列表返回。
>>> outputs = model.outputs
>>> outputs
]
model.get_weights-将所有权重作为NumPy数组返回。
model.set_weights(weight_numpy_array) -设置模型的权重。
Keras提供了将模型序列化为对象以及json并在以后再次加载的方法。它们如下-
get_config() -I将模型作为对象返回。
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提供了一种简单的方法,即摘要以获取有关模型及其层的完整信息。
上一节中创建的模型的摘要如下-
>>> 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
_________________________________________________________________
>>>
模型为训练,评估和预测过程提供函数。它们如下-
编译-配置模型的学习过程
拟合-使用训练数据训练模型
评估-使用测试数据评估模型
预测-预测新输入的结果。
顺序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
_________________________________________________________________