我正在嘗試將一些 pytorch 代碼轉換為 tensorflow。在 pytorch 代碼中,他們使用module.register_parameter(name, param). 我如何在 tensorflow 上隱藏這部分代碼?
下面的示例代碼:
for module_name, module in self.model.named_modules():
module.register_parameter(name, new_parameter)
uj5u.com熱心網友回復:
tf.Variable相當于nn.ParameterPyTorch 中的。tf.Variable主要用于存盤模型引數,因為它們的值在訓練期間不斷更新。
要將張量用作新的模型引數,您需要將其轉換為tf.Variable. 您可以在此處查看如何從張量創建變數。
如果你想在模型本身的 TensorFlow 中添加模型引數,你可以簡單地在模型類中創建一個變數,它會被 TensorFlow 自動注冊為模型引數。
如果您想將一個tf.Variable 外部添加到模型作為模型引數,您可以通過像這樣擴展它手動將其添加到trainable_weights屬性-tf.keras.layers.Layer
model.layers[-1].trainable_weights.extend([new_parameter])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476642.html
