Keras-型号

Keras-型号 (Keras - Models)

As learned earlier, Keras model represents the actual neural network model. Keras provides a two mode to create the model, simple and easy to use Sequential API as well as more flexible and advanced Functional API. Let us learn now to create model using both Sequential and Functional API in this chapter.

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

顺序的 (Sequential)

The core idea of Sequential API is simply arranging the Keras layers in a sequential order and so, it is called Sequential API. Most of the ANN also has layers in sequential order and the data flows from one layer to another layer in the given order until the data finally reaches the output layer.

顺序API的核心思想是简单地按顺序排列Keras层,因此,它称为顺序API 。 大部分的ANN还具有顺序排列的层,并且数据以给定的顺序从一层流到另一层,直到数据最终到达输出层。

A ANN model can be created by simply calling Sequential() API as specified below −

可以通过简单地调用Sequential() API来创建ANN模型,如下所示:


from keras.models import Sequential 
model = Sequential()

添加图层 (Add layers)

To add a layer, simply create a layer using Keras layer API and then pass the layer through add() function as specified below −

要添加层,只需使用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)

Here, we have created one input layer, one hidden layer and one output layer.

在这里,我们创建了一个输入层,一个隐藏层和一个输出层。

访问模型 (Access the model)

Keras provides few methods to get the model information like layers, input data and output data. They are as follows −

Keras提供了很少的方法来获取模型信息,例如图层,输入数据和输出数据。 它们如下-

  • model.layers − Returns all the layers of the model as list.

    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 − Returns all the input tensors of the model as list.

    model.inputs-将模型的所有输入张量作为列表返回。


>>> inputs = model.inputs 
>>> inputs 
[<tf.Tensor 'dense_13_input:0' shape=(?, 8) dtype=float32>]

  • model.outputs − Returns all the output tensors of the model as list.

    model.outputs-将模型的所有输出张量作为列表返回。


>>> outputs = model.outputs 
>>> outputs 
<tf.Tensor 'dense_15/BiasAdd:0' shape=(?, 8) dtype=float32>]

  • model.get_weights − Returns all the weights as NumPy arrays.

    model.get_weights-将所有权重作为NumPy数组返回。

  • model.set_weights(weight_numpy_array) − Set the weights of the model.

    model.set_weights(weight_numpy_array) -设置模型的权重。

序列化模型 (Serialize the model)

Keras provides methods to serialize the model into object as well as json and load it again later. They are as follows −

Keras提供了将模型序列化为对象以及json并在以后再次加载的方法。 它们如下-

  • get_config() − IReturns the model as an object.

    get_config() -I将模型作为对象返回。


config = model.get_config()

  • from_config() − It accept the model configuration object as argument and create the model accordingly.

    from_config() -接受模型配置对象作为参数并相应地创建模型。


new_model = Sequential.from_config(config)

  • to_json() − Returns the model as an json object.

    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() − Accepts json representation of the model and create a new model.

    model_from_json() -接受模型的json表示并创建一个新模型。


from keras.models import model_from_json 
new_model = model_from_json(json_string)

  • to_yaml() − Returns the model as a yaml 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() − Accepts yaml representation of the model and create a new model.

    model_from_yaml() -接受模型的yaml表示并创建一个新模型。


from keras.models import model_from_yaml 
new_model = model_from_yaml(yaml_string)

总结模型 (Summarise the model)

Understanding the model is very important phase to properly use it for training and prediction purposes. Keras provides a simple method, summary to get the full information about the model and its layers.

理解模型是正确使用模型进行训练和预测的非常重要的阶段。 Keras提供了一种简单的方法,即摘要以获取有关模型及其层的完整信息。

A summary of the model created in the previous section is as follows −

上一节中创建的模型的摘要如下-


>>> 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 
_________________________________________________________________ 
>>>

训练和预测模型 (Train and Predict the model)

Model provides function for training, evaluation and prediction process. They are as follows −

模型为训练,评估和预测过程提供功能。 它们如下-

  • compile − Configure the learning process of the model

    编译 -配置模型的学习过程

  • fit − Train the model using the training data

    拟合 -使用训练数据训练模型

  • evaluate − Evaluate the model using the test data

    评估 -使用测试数据评估模型

  • predict − Predict the results for new input.

    预测 -预测新输入的结果。

功能性API (Functional API)

Sequential API is used to create models layer-by-layer. Functional API is an alternative approach of creating more complex models. Functional model, you can define multiple input or output that share layers. First, we create an instance for model and connecting to the layers to access input and output to the model. This section explains about functional model in brief.

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

建立模型 (Create a model)

Import an input layer using the below module −

使用以下模块导入输入层-


>>> from keras.layers import Input

Now, create an input layer specifying input dimension shape for the model using the below code −

现在,使用以下代码创建一个输入层,指定模型的输入尺寸形状-


>>> data = Input(shape=(2,3))

Define layer for the input using the below module −

使用以下模块为输入定义层-


>>> from keras.layers import Dense

Add Dense layer for the input using the below line of code −

使用下面的代码行为输入添加密集层-


>>> layer = Dense(2)(data) 
>>> print(layer) 
Tensor("dense_1/add:0", shape =(?, 2, 2), dtype = float32)

Define model using the below module −

使用以下模块定义模型-


from keras.models import Model

Create a model in functional way by specifying both input and output layer −

通过指定输入和输出层以功能方式创建模型-


model = Model(inputs = data, outputs = layer)

The complete code to create a simple model is shown below −

创建简单模型的完整代码如下所示-


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 
_________________________________________________________________

翻译自: https://www.tutorialspoint.com/keras/keras_models.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值