亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 TensorFlow 在 ResNetv2 101 上沒有梯度

使用 TensorFlow 在 ResNetv2 101 上沒有梯度

千巷貓影 2023-06-20 17:20:58
使用 TensorFlow 2.3,在 Ubuntu 18.04 上,在 Python 中,我想訓練一個殘差網絡來生成熱圖。我是TF的新手。到目前為止,我可以解決所有問題,直到出現No gradients provided for any variable異常。我能夠使用以下基本代碼重現異常。import tensorflow as tfdef dummy_image_float(w,h):? ? return tf.constant([0.,]*(h*w*3), shape=[1,w,h,3], dtype=tf.float32)def dummy_result(w,h,nfeature):? ? return tf.constant([0,]*(h*w*nfeature), shape=[1,w,h,nfeature], dtype=tf.float32)model = tf.keras.applications.ResNet101V2(? ? ? ? include_top=False,? ? ? ? #input_tensor=x1,? ? ? ? weights='imagenet',? ? ? ? input_shape=(224, 224, 3),? ? ? ? pooling=None? ? ? ? )model.compile(optimizer='adam', loss="mean_squared_error", run_eagerly=True)train_ds = [ (dummy_image_float(224,224), dummy_result(7,7,2048)) ]model.fit(train_ds, epochs=1)此代碼以“ValueError:沒有為任何變量提供梯度”結尾。我可以在互聯網上找到相關錯誤。我想我可以使用 tf.GradientTape 編寫自己的學習循環,但我希望上面的代碼能夠在不需要自定義學習循環的情況下工作。有誰知道為什么上面的代碼失敗了?經過一番挖掘,這就是我想出的。import tensorflow as tfdef dummy_image_float(w,h):? ? return tf.constant([0.,]*(h*w*3), shape=[1,w,h,3], dtype=tf.float32)def dummy_result(w,h,nfeature):? ? return tf.constant([0,]*(h*w*nfeature), shape=[1,w,h,nfeature], dtype=tf.float32)model = tf.keras.applications.ResNet101V2(? ? ? ? include_top=False,? ? ? ? weights='imagenet',? ? ? ? input_shape=(224, 224, 3),? ? ? ? pooling=None? ? ? ? )train_ds = [ (dummy_image_float(224,224), dummy_result(7,7,2048)) ]opt = tf.keras.optimizers.Adam()loss_fn = lambda: tf.keras.losses.mse(model(input), output)for input, output in train_ds:? opt.minimize(loss_fn, model.trainable_weights)我仍然不知道為什么原始代碼會生成無梯度異常(因此我不認為此編輯是答案)。
查看完整描述

1 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

我試圖通過僅更改 model.fit() 操作中代碼的最后一部分來復制和解析您在 TF 2.6 版本中的代碼。這是編輯后的代碼:


import tensorflow as tf


def dummy_image_float(w,h):

    return tf.constant([0.,]*(h*w*3), shape=[1,w,h,3], dtype=tf.float32)

def dummy_result(w,h,nfeature):

    return tf.constant([0,]*(h*w*nfeature), shape=[1,w,h,nfeature], dtype=tf.float32)


model = tf.keras.applications.ResNet101V2(

        include_top=False,

        #input_tensor=x1,

        weights='imagenet',

        input_shape=(224, 224, 3),

        pooling=None

        )


model.compile(optimizer='adam', loss="mean_squared_error", run_eagerly=True)


#train_ds = [ (dummy_image_float(224,224), dummy_result(7,7,2048)) ]

model.fit(dummy_image_float(224,224), dummy_result(7,7,2048), epochs=2)


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號