如何使用 Python 中的 Tensorflow 返回層例項的建構函式引數?


Tensorflow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用以實現演算法、深度學習應用程式等等。它用於研究和生產目的。

Keras 是作為 ONEIROS(開放式神經電子智慧機器人作業系統)專案研究的一部分開發的。Keras 是一個深度學習 API,用 Python 編寫。它是一個高階 API,具有高效的介面,有助於解決機器學習問題。

它執行在 Tensorflow 框架之上。它旨在幫助快速進行實驗。它提供了開發和封裝機器學習解決方案所必需的基本抽象和構建塊。

它具有高度可擴充套件性並具有跨平臺功能。這意味著 Keras 可以執行在 TPU 或 GPU 叢集上。Keras 模型還可以匯出到 Web 瀏覽器或手機上執行。

Keras 已經存在於 Tensorflow 包中。可以使用以下程式碼行訪問它。

import tensorflow
from tensorflow import keras

Keras 函式式 API 有助於建立比使用順序 API 建立的模型更靈活的模型。函式式 API 可以處理具有非線性拓撲的模型,可以共享層並處理多個輸入和輸出。深度學習模型通常是一個包含多個層的無環有向圖 (DAG)。函式式 API 有助於構建層的圖形。

我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 有助於透過瀏覽器執行 Python 程式碼,並且無需任何配置即可免費訪問 GPU(圖形處理單元)。Colaboratory 是建立在 Jupyter Notebook 之上的。以下是使用 Python 返回層例項的建構函式引數的程式碼片段:

示例

class CustomDense(layers.Layer):
   def __init__(self, units=32):
      super(CustomDense, self).__init__()
      self.units = units
   def build(self, input_shape):
      self.w = self.add_weight(
         shape=(input_shape[-1], self.units),
         initializer="random_normal",
         trainable=True,
      )
      self.b = self.add_weight(
         shape=(self.units,), initializer="random_normal", trainable=True
      )
   def call(self, inputs):
      return tf.matmul(inputs, self.w) + self.b
   def get_config(self):
      return {"units": self.units}
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)

model = keras.Model(inputs, outputs)
print("The below function returns constructor arguments for the instance of the layer")
config = model.get_config()

new_model = keras.Model.from_config(config, custom_objects={"CustomDense": CustomDense})

程式碼來源 - https://www.tensorflow.org/guide/keras/functional

輸出

The below function returns constructor arguments for the instance of the layer

解釋

  • 建立了一個名為“CustomDense”的類,用於向模型新增權重。

  • 定義了另一個名為“get_config”的函式,該函式返回每一層例項的建構函式引數。

  • 定義了模型的輸入層。

  • 接下來,定義模型並呼叫函式。

更新於: 2021年1月18日

78 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.