簡體   English   中英

在 TensorFlow 中使用 SSIM 損失返回 NaN 值

[英]Using SSIM loss in TensorFlow returns NaN values

我正在用 MRI 圖像訓練 a.network,我想使用 SSIM 作為損失 function。直到現在我一直在使用 MSE,並且一切正常。 但是當我嘗試使用 SSIM (tf.image.ssim) 時,我收到了一堆警告消息:

 /usr/local/lib/python3.7/dist-packages/matplotlib/image.py:397: UserWarning: Warning: converting a masked element to nan.
  dv = (np.float64(self.norm.vmax) -
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py:398: UserWarning: Warning: converting a masked element to nan.
  np.float64(self.norm.vmin))
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py:405: UserWarning: Warning: converting a masked element to nan.
  a_min = np.float64(newmin)
/usr/local/lib/python3.7/dist-packages/matplotlib/image.py:410: UserWarning: Warning: converting a masked element to nan.
  a_max = np.float64(newmax)
/usr/local/lib/python3.7/dist-packages/matplotlib/colors.py:933: UserWarning: Warning: converting a masked element to nan.
  dtype = np.min_scalar_type(value)
/usr/local/lib/python3.7/dist-packages/numpy/ma/core.py:713: UserWarning: Warning: converting a masked element to nan.
  data = np.array(a, copy=False, subok=subok)

我的代碼無論如何都在運行,但沒有生成任何數字。 我不確定這里發生了什么或我應該去哪里看。 我正在使用 tensorflow 2.4.0。

我在這里附上我的代碼摘要:

generator = Generator()  #An u-net defined in tf.keras

gen_learningrate = 5e-4
generator_optimizer = tf.keras.optimizers.Adam(gen_learningrate, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
# Generator loss

def generator_loss(gen_output, target):
    # SSIM loss
    loss = - tf.reduce_mean(tf.image.ssim(target, gen_output, 2)) 
    return loss

@tf.function
def train_step(input_image, target, epoch):
    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
        gen_output = generator(input_image, training=True)
        
        loss = generator_loss(gen_output, target)

    generator_gradients = gen_tape.gradient(loss, generator.trainable_variables)
    generator_optimizer.apply_gradients(zip(generator_gradients, 
                                                 generator.trainable_variables))

    return loss

def fit(train_ds, epochs, test_ds):
    for input_image, target in train_ds:
            loss = train_step(input_image,target,epoch) 

fit(train_dataset, EPOCHS, test_dataset)

我進行了一些探索,發現大多數使用tf.image.ssim()作為損失的人 function 使用了tf.train() 1.0 中的model.fit() 我懷疑返回的 NaN 值與GradientTape() function 有關,但我不確定如何。

根據我的經驗,此警告通常與嘗試繪制具有無窮遠坐標的點有關。 當然,您真的應該向我們展示更多代碼,以便我們有效地幫助您。

您可能會得到與真實圖像非常接近的網絡預測,因此它會給出無窮大(如果您對它執行某些操作,則為 NaN)。

小心使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM