Keras 模型

2021-10-15 14:52 更新

如前所述,Keras 模型代表了實(shí)際的神經(jīng)網(wǎng)絡(luò)模型。Keras 提供了兩種模式來(lái)創(chuàng)建模型,簡(jiǎn)單易用的 Sequential API 以及更靈活和高級(jí)的 Functional API?,F(xiàn)在讓我們學(xué)習(xí)如何在本章中使用 Sequential 和 Functional API 創(chuàng)建模型。

線(xiàn)性(Sequential)

Sequential API的核心思想是簡(jiǎn)單地按順序排列 Keras 層,因此稱(chēng)為Sequential API。大多數(shù)ANN還具有按順序排列的層,數(shù)據(jù)以給定的順序從一層流向另一層,直到數(shù)據(jù)最終到達(dá)輸出層。

可以通過(guò)簡(jiǎn)單地調(diào)用Sequential() API來(lái)創(chuàng)建 ANN 模型,如下所示:

  1. from keras.models import Sequential
  2. model = Sequential()

添加圖層

要添加一個(gè)層,只需使用 Keras 層 API 創(chuàng)建一個(gè)層,然后通過(guò) add() 函數(shù)傳遞該層,如下所示:

  1. from keras.models import Sequential
  2. model = Sequential()
  3. input_layer = Dense(32, input_shape=(8,)) model.add(input_layer)
  4. hidden_layer = Dense(64, activation='relu'); model.add(hidden_layer)
  5. output_layer = Dense(8)
  6. model.add(output_layer)

在這里,我們創(chuàng)建了一個(gè)輸入層、一個(gè)隱藏層和一個(gè)輸出層

訪(fǎng)問(wèn)模型

Keras 提供了一些方法來(lái)獲取模型信息,如層、輸入數(shù)據(jù)和輸出數(shù)據(jù)。它們?nèi)缦拢?/p>

  • model.layers 將模型的所有層作為列表返回。
    1. >>> layers = model.layers
    2. >>> layers
    3. [
    4. <keras.layers.core.Dense object at 0x000002C8C888B8D0>,
    5. <keras.layers.core.Dense object at 0x000002C8C888B7B8>
    6. <keras.layers.core.Dense object at 0x 000002C8C888B898>
    7. ]
  • model.inputs 將模型的所有輸入張量作為列表返回。
    1. >>> inputs = model.inputs
    2. >>> inputs
    3. [<tf.Tensor 'dense_13_input:0' shape=(?, 8) dtype=float32>]
  • model.outputs 將模型的所有輸出張量作為列表返回。
    1. >>> outputs = model.outputs
    2. >>> outputs
    3. <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 提供了將模型序列化為對(duì)象以及 json 并稍后再次加載的方法。它們?nèi)缦?

  • get_config() IReturns 模型作為一個(gè)對(duì)象。
    1. config = model.get_config()
  • from_config() 它接受模型配置對(duì)象作為參數(shù)并相應(yīng)地創(chuàng)建模型。
    1. new_model = Sequential.from_config(config)
  • to_json() 將模型作為 json 對(duì)象返回。
    1. >>> json_string = model.to_json()
    2. >>> json_string '{"class_name": "Sequential", "config":
    3. {"name": "sequential_10", "layers":
    4. [{"class_name": "Dense", "config":
    5. {"name": "dense_13", "trainable": true, "batch_input_shape":
    6. [null, 8], "dtype": "float32", "units": 32, "activation": "linear",
    7. "use_bias": true, "kernel_initializer":
    8. {"class_name": "Vari anceScaling", "config":
    9. {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}},
    10. "bias_initializer": {"class_name": "Zeros", "conf
    11. ig": {}}, "kernel_regularizer": null, "bias_regularizer": null,
    12. "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}},
    13. {" class_name": "Dense", "config": {"name": "dense_14", "trainable": true,
    14. "dtype": "float32", "units": 64, "activation": "relu", "use_bias": true,
    15. "kern el_initializer": {"class_name": "VarianceScaling", "config":
    16. {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}},
    17. "bias_initia lizer": {"class_name": "Zeros",
    18. "config": {}}, "kernel_regularizer": null, "bias_regularizer": null,
    19. "activity_regularizer": null, "kernel_constraint" : null, "bias_constraint": null}},
    20. {"class_name": "Dense", "config": {"name": "dense_15", "trainable": true,
    21. "dtype": "float32", "units": 8, "activation": "linear", "use_bias": true,
    22. "kernel_initializer": {"class_name": "VarianceScaling", "config":
    23. {"scale": 1.0, "mode": "fan_avg", "distribution": " uniform", "seed": null}},
    24. "bias_initializer": {"class_name": "Zeros", "config": {}},
    25. "kernel_regularizer": null, "bias_regularizer": null, "activity_r egularizer":
    26. null, "kernel_constraint": null, "bias_constraint":
    27. null}}]}, "keras_version": "2.2.5", "backend": "tensorflow"}'
    28. >>>
  • model_from_json() 接受模型的 json 表示并創(chuàng)建一個(gè)新模型。
    1. from keras.models import model_from_json
    2. new_model = model_from_json(json_string)
  • to_yaml() 將模型作為 yaml 字符串返回。
    1. >>> yaml_string = model.to_yaml()
    2. >>> yaml_string 'backend: tensorflow\nclass_name:
    3. Sequential\nconfig:\n layers:\n - class_name: Dense\n config:\n
    4. activation: linear\n activity_regular izer: null\n batch_input_shape:
    5. !!python/tuple\n - null\n - 8\n bias_constraint: null\n bias_initializer:\n
    6. class_name : Zeros\n config: {}\n bias_regularizer: null\n dtype:
    7. float32\n kernel_constraint: null\n
    8. kernel_initializer:\n cla ss_name: VarianceScaling\n config:\n
    9. distribution: uniform\n mode: fan_avg\n
    10. scale: 1.0\n seed: null\n kernel_regularizer: null\n name: dense_13\n
    11. trainable: true\n units: 32\n
    12. use_bias: true\n - class_name: Dense\n config:\n activation: relu\n activity_regularizer: null\n
    13. bias_constraint: null\n bias_initializer:\n class_name: Zeros\n
    14. config : {}\n bias_regularizer: null\n dtype: float32\n
    15. kernel_constraint: null\n kernel_initializer:\n class_name: VarianceScalin g\n
    16. config:\n distribution: uniform\n mode: fan_avg\n scale: 1.0\n
    17. seed: null\n kernel_regularizer: nu ll\n name: dense_14\n trainable: true\n
    18. units: 64\n use_bias: true\n - class_name: Dense\n config:\n
    19. activation: linear\n activity_regularizer: null\n
    20. bias_constraint: null\n bias_initializer:\n
    21. class_name: Zeros\n config: {}\n bias_regu larizer: null\n
    22. dtype: float32\n kernel_constraint: null\n
    23. kernel_initializer:\n class_name: VarianceScaling\n config:\n
    24. distribution: uniform\n mode: fan_avg\n
    25. scale: 1.0\n seed: null\n kernel_regularizer: null\n name: dense _15\n
    26. trainable: true\n units: 8\n
    27. use_bias: true\n name: sequential_10\nkeras_version: 2.2.5\n'
    28. >>>
  • model_from_yaml() 接受模型的 yaml 表示并創(chuàng)建一個(gè)新模型。
    1. model_from_yaml() - 接受模型的 yaml 表示并創(chuàng)建一個(gè)新模型。

總結(jié)模型

理解模型是正確使用模型進(jìn)行訓(xùn)練和預(yù)測(cè)的非常重要的階段。Keras 提供了一種簡(jiǎn)單的方法,摘要來(lái)獲取有關(guān)模型及其層的完整信息。

上一節(jié)中創(chuàng)建的模型摘要如下:

  1. >>> model.summary() Model: "sequential_10"
  2. _________________________________________________________________
  3. Layer (type) Output Shape Param
  4. #================================================================
  5. dense_13 (Dense) (None, 32) 288
  6. _________________________________________________________________
  7. dense_14 (Dense) (None, 64) 2112
  8. _________________________________________________________________
  9. dense_15 (Dense) (None, 8) 520
  10. =================================================================
  11. Total params: 2,920
  12. Trainable params: 2,920
  13. Non-trainable params: 0
  14. _________________________________________________________________
  15. >>>

訓(xùn)練和預(yù)測(cè)模型

模型為訓(xùn)練、評(píng)估和預(yù)測(cè)過(guò)程提供功能。它們?nèi)缦?

  • compile 配置模型的學(xué)習(xí)過(guò)程
  • fit 使用訓(xùn)練數(shù)據(jù)訓(xùn)練模型
  • evaluate 使用測(cè)試數(shù)據(jù)評(píng)估模型
  • predict 預(yù)測(cè)新輸入的結(jié)果。

功能API

Sequential API 用于逐層創(chuàng)建模型。函數(shù)式 API 是創(chuàng)建更復(fù)雜模型的另一種方法。功能模型,您可以定義多個(gè)共享層的輸入或輸出。首先,我們?yōu)槟P蛣?chuàng)建一個(gè)實(shí)例并連接到層以訪(fǎng)問(wèn)模型的輸入和輸出。本節(jié)簡(jiǎn)要介紹功能模型。

創(chuàng)建模型

使用以下模塊導(dǎo)入輸入層:

  1. >>> from keras.layers import Input

現(xiàn)在,使用以下代碼為模型創(chuàng)建一個(gè)指定輸入維度形狀的輸入層:

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

使用以下模塊定義輸入層:

  1. >>> from keras.layers import Dense

使用以下代碼行為輸入添加密集層:

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

使用以下模塊定義模型 :

  1. from keras.models import Model

通過(guò)指定輸入和輸出層以功能方式創(chuàng)建模型:

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

創(chuàng)建簡(jiǎn)單模型的完整代碼如下所示:

  1. from keras.layers import Input
  2. from keras.models import Model
  3. from keras.layers import Dense
  4. data = Input(shape=(2,3))
  5. layer = Dense(2)(data) model =
  6. Model(inputs=data,outputs=layer) model.summary()
  7. _________________________________________________________________
  8. Layer (type) Output Shape Param #
  9. =================================================================
  10. input_2 (InputLayer) (None, 2, 3) 0
  11. _________________________________________________________________
  12. dense_2 (Dense) (None, 2, 2) 8
  13. =================================================================
  14. Total params: 8
  15. Trainable params: 8
  16. Non-trainable params: 0
  17. _________________________________________________________________
以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)