keras訓練模型遇到loss nan 解決辦法

2021-09-29 05:26:42 字數 1210 閱讀 1321

訓練神經網路的時候,增大了隱藏層的神經元個數,突然間loss值變成了nan

經過多方搜尋,找到了原因

tensorflow解決方法網上已有,這裡貼keras的解決辦法

在pycharm裡

import keras

keras.losses

ctrl + 左鍵 losses 進入損失函式模組

找到呼叫的損失函式,這裡是

def

categorical_crossentropy

(y_true, y_pred, from_logits=

false

, label_smoothing=0)

: y_pred = k.constant(y_pred)

ifnot k.is_tensor(y_pred)

else y_pred

y_true = k.cast(y_true, y_pred.dtype)

if label_smoothing is

not0

: smoothing = k.cast_to_floatx(label_smoothing)

def_smooth_labels()

: num_classes = k.cast(k.shape(y_true)[1

], y_pred.dtype)

return y_true *

(1.0

- smoothing)

+(smoothing / num_classes)

y_true = k.switch(k.greater(smoothing,0)

, _smooth_labels,

lambda

: y_true)

return k.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)

把最後的一句改為

return k.categorical_crossentropy(y_true, y_pred+1e-

5, from_logits=from_logits)

儲存關閉,問題解決。

keras 訓練是 各種loss 變化情況

1 學習率可能太大 2 batch size太小 3 樣本分佈不均勻 4 缺少加入正則化 大家可以在這幾個方面去進行調整,一步一步的調整,先調整學習率,然後再調整batch size,一般這兩種情況比較多,很容易就可以解決。如果還不行,再考慮一下val 集的資料樣本和訓練集的樣本是不是同樣的分布。從...

使用Keras訓練模型二三事兒

資料時tensor格式時,會建議使用steps per epoch,validation steps這些引數,但是使用這些引數時非常容易出現oom記憶體溢位情況 hist model.fit data lable cfg train dir validation data x1,y1 steps p...

keras 預訓練模型的使用方法

tensorflow 幾個最新版本的更新大力推崇 keras 相當於官宣啊 相信keras的可用性給大家做深度學習帶來方便 暢快的同時 逐漸會變成主流的開發元件 imagenet的影象識別任務目睹了近幾年人工神經網路的進展 linux下是放在 keras models 中 win下則放在python...