如何使用TensorFlow獲取層中的變數?


可以使用TensorFlow透過使用“layer.Variables”顯示層中的變數,然後使用“layer.kernel”和“layer.bias”訪問這些變數來獲取層中的變數。

閱讀更多: 什麼是TensorFlow以及Keras如何與TensorFlow一起建立神經網路?

包含至少一層的神經網路被稱為卷積層。我們可以使用卷積神經網路來構建學習模型。

影像分類遷移學習背後的直覺是,如果一個模型在一個大型通用資料集上進行訓練,那麼這個模型可以有效地作為一個通用的視覺世界模型。它將學習特徵圖,這意味著使用者不必從頭開始在大型資料集上訓練大型模型。

TensorFlow Hub是一個包含預訓練TensorFlow模型的儲存庫。TensorFlow可用於微調學習模型。

我們將瞭解如何使用來自TensorFlow Hub的模型與tf.keras,使用來自TensorFlow Hub的影像分類模型。完成此操作後,可以執行遷移學習以微調用於自定義影像類的模型。這是透過使用預訓練的分類器模型來獲取影像並預測它是哪個來完成的。這可以在不需要任何訓練的情況下完成。

我們正在使用Google Colaboratory執行以下程式碼。Google Colab或Colaboratory幫助在瀏覽器上執行Python程式碼,無需任何配置即可免費訪問GPU(圖形處理單元)。Colaboratory是基於Jupyter Notebook構建的。

示例

print("The variables in a layer")
print(layer.variables)
print("Variables can be accessed through nice accessors")
print(layer.kernel, layer.bias)

程式碼來源 −https://www.tensorflow.org/tutorials/customization/custom_layers

輸出

The variables in a layer
[<tf.Variable 'dense_5/kernel:0' shape=(5, 10) dtype=float32, numpy=
array([[-0.05103415, -0.6048388 , -0.09445673, 0.00147319, 0.5958504 ,
0.03832638, -0.4617405 , 0.22488767, -0.521616 , -0.4939174 ],
[ 0.2143982 , -0.42745167, -0.19899327, 0.011585 , 0.39148778,
-0.5193864 , 0.11133379, 0.07244939, -0.42842603, -0.07152319],
[ 0.09674573, 0.08572572, -0.44079286, -0.10669523, 0.1977045 ,
0.04525411, 0.41716915, 0.2611121 , -0.1167441 , -0.26781783],
[ 0.38834113, -0.5396006 , -0.33349523, -0.5882891 , -0.2575687 ,
-0.33869067, 0.56990904, 0.3368895 , 0.6290985 , -0.31278375],
[-0.40759754, 0.18778783, 0.11296159, 0.35683256, -0.16895893,
-0.55790913, 0.5088188 , -0.06520861, -0.24566567, -0.15854272]],
dtype=float32)>, <tf.Variable 'dense_5/bias:0' shape=(10,) dtype=float32, numpy=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)>]
Variables can be accessed through nice accessors
<tf.Variable 'dense_5/kernel:0' shape=(5, 10) dtype=float32, numpy=
array([[-0.05103415, -0.6048388 , -0.09445673, 0.00147319, 0.5958504 ,
0.03832638, -0.4617405 , 0.22488767, -0.521616 , -0.4939174 ],
[ 0.2143982 , -0.42745167, -0.19899327, 0.011585 , 0.39148778,
-0.5193864 , 0.11133379, 0.07244939, -0.42842603, -0.07152319],
[ 0.09674573, 0.08572572, -0.44079286, -0.10669523, 0.1977045 ,
0.04525411, 0.41716915, 0.2611121 , -0.1167441 , -0.26781783],
[ 0.38834113, -0.5396006 , -0.33349523, -0.5882891 , -0.2575687 ,
-0.33869067, 0.56990904, 0.3368895 , 0.6290985 , -0.31278375],
[-0.40759754, 0.18778783, 0.11296159, 0.35683256, -0.16895893,
-0.55790913, 0.5088188 , -0.06520861, -0.24566567, -0.15854272]],
dtype=float32)> <tf.Variable 'dense_5/bias:0' shape=(10,) dtype=float32, numpy=array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)>

解釋

  • 層有很多方法。
  • 可以使用層中的方法檢查所有變數。
  • 全連線層將具有權重和偏差變數。

更新於:2021年2月25日

437 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.