如前所述,Keras 模型代表了實(shí)際的神經(jīng)網(wǎng)絡(luò)模型。Keras 提供了兩種模式來創(chuàng)建模型,簡單易用的 Sequential API 以及更靈活和高級的 Functional API?,F(xiàn)在讓我們學(xué)習(xí)如何在本章中使用 Sequential 和 Functional API 創(chuàng)建模型。
Sequential API
的核心思想是簡單地按順序排列 Keras 層,因此稱為Sequential API。大多數(shù)ANN
還具有按順序排列的層,數(shù)據(jù)以給定的順序從一層流向另一層,直到數(shù)據(jù)最終到達(dá)輸出層。
可以通過簡單地調(diào)用Sequential()
API來創(chuàng)建 ANN 模型,如下所示:
from keras.models import Sequential
model = Sequential()
要添加一個層,只需使用 Keras 層 API 創(chuàng)建一個層,然后通過 add() 函數(shù)傳遞該層,如下所示:
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)
在這里,我們創(chuàng)建了一個輸入層、一個隱藏層和一個輸出層
Keras 提供了一些方法來獲取模型信息,如層、輸入數(shù)據(jù)和輸出數(shù)據(jù)。它們?nèi)缦拢?/p>
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
將所有權(quán)重作為 NumPy 數(shù)組返回。model.set_weights(weight_numpy_array)
設(shè)置模型的權(quán)重。Keras 提供了將模型序列化為對象以及 json 并稍后再次加載的方法。它們?nèi)缦?
get_config()
IReturns 模型作為一個對象。
config = model.get_config()
from_config()
它接受模型配置對象作為參數(shù)并相應(yīng)地創(chuàng)建模型。
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 表示并創(chuàng)建一個新模型。
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 表示并創(chuàng)建一個新模型。
model_from_yaml() - 接受模型的 yaml 表示并創(chuàng)建一個新模型。
理解模型是正確使用模型進(jìn)行訓(xùn)練和預(yù)測的非常重要的階段。Keras 提供了一種簡單的方法,摘要來獲取有關(guān)模型及其層的完整信息。
上一節(jié)中創(chuàng)建的模型摘要如下:
>>> 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
_________________________________________________________________
>>>
模型為訓(xùn)練、評估和預(yù)測過程提供功能。它們?nèi)缦?
compile
配置模型的學(xué)習(xí)過程fit
使用訓(xùn)練數(shù)據(jù)訓(xùn)練模型evaluate
使用測試數(shù)據(jù)評估模型predict
預(yù)測新輸入的結(jié)果。Sequential API 用于逐層創(chuàng)建模型。函數(shù)式 API 是創(chuàng)建更復(fù)雜模型的另一種方法。功能模型,您可以定義多個共享層的輸入或輸出。首先,我們?yōu)槟P蛣?chuàng)建一個實(shí)例并連接到層以訪問模型的輸入和輸出。本節(jié)簡要介紹功能模型。
使用以下模塊導(dǎo)入輸入層:
>>> from keras.layers import Input
現(xiàn)在,使用以下代碼為模型創(chuàng)建一個指定輸入維度形狀的輸入層:
>>> 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
通過指定輸入和輸出層以功能方式創(chuàng)建模型:
model = Model(inputs = data, outputs = layer)
創(chuàng)建簡單模型的完整代碼如下所示:
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
_________________________________________________________________
更多建議: