如何使用 Keras 建立一個模型,其中模型的輸入形狀事先指定?


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

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

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

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

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

import tensorflow
from tensorflow import keras

我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 幫助在瀏覽器上執行 Python 程式碼,無需任何配置,並且可以免費訪問 GPU(圖形處理單元)。Colaboratory 建立在 Jupyter Notebook 之上。以下是程式碼片段:

示例

print("Three dense layers are being created")
layer = layers.Dense(3)
print("The weights associated with the layers are")
print(layer.weights)

print("The created layers is called on test data")
x = tf.ones((2, 3))
y = layer(x)
print("Now, the weights are : ")
print(layer.weights)

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

輸出

Three dense layers are being created
The weights associated with the layers are
[]
The created layers is called on test data
Now, the weights are :
[<tf.Variable 'dense_11/kernel:0' shape=(3, 3) dtype=float32, numpy=
array([[-0.9901273 , -0.70897937, -0.44804883],
   [ 0.6849613 , 0.5198808 , 0.48534775],
   [-0.07876515, -0.73648643, 0.44018626]], dtype=float32)>, <tf.Variable 'dense_11/bias:0'
shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>]

解釋

  • Keras 模型中的所有層都需要知道輸入的形狀,以便能夠建立最佳權重。

  • 最初,當建立層時,它沒有任何與之關聯的權重。

  • 因此,當它第一次在輸入上被呼叫時,它會建立權重。

  • 這是因為權重取決於輸入的形狀。

  • 這些層是按順序建立的。

  • 這在測試資料上呼叫。

  • 與這個新模型相關的權重顯示在控制檯上。

更新於: 2021年1月18日

92 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.