如何解决回归模型在训练时间给出nan还是inf?
我有一个用 keras
编写的回归模型。这是一个骨龄评估,数据集来自 here。它提供图像数据集和元信息。任务是预测骨龄。为简单起见,我没有使用图像数据,而是使用诸如性别之类的附加特征作为我的训练集。但是在训练时间它会突然出现 nan 并且有时会出现 inf
损失。我在这里需要一些建议。以下是我迄今为止尝试过的。
import pandas as pd
df = pd.read_csv('boneage_train.csv')
df.head()
仅供参考,您不需要图像集。但只需从数据集中取出 .csv
文件。我们只使用性别信息。在数据集中,它是 Male
和 Female
。所以我们把它转换成这样的一个热点
df['Gender'] = df['Male'].map(lambda x: 1 if x else 0)
这是我的数据生成器
from tensorflow.keras.utils import Sequence
class Generator(Sequence):
def __init__(self,data,batch_size,shuffle=False,random_state=101):
self.data = data
self.shuffle = shuffle
self.batch_size = batch_size
self.label = self.data['Boneage']
self.gender = self.data['Gender']
self.list_idx = data.index.values
self.random_state = random_state
self.on_epoch_end()
def __len__(self):
return int(np.ceil(len(self.data) / float(self.batch_size)))
def __getitem__(self,index):
batch_idx = self.indices[index*self.batch_size:(index+1)*self.batch_size]
idx = [self.list_idx[k] for k in batch_idx]
# placeholder
Gender = np.empty((self.batch_size),dtype = np.float32)
Target = np.empty((self.batch_size),dtype = np.float32)
for i,k in enumerate(idx):
Target[i] = self.label.iloc[k]
Gender[i] = self.gender.iloc[k]
return Gender,Target
def on_epoch_end(self):
self.indices = np.arange(len(self.list_idx))
if self.shuffle:
np.random.seed(self.random_state)
np.random.shuffle(self.indices)
下一步,检查
import numpy as np
batch_size = 64
gen = Generator(df,shuffle = True)
for i,(x,y) in enumerate(gen):
print(x.shape,x)
print(y.shape,y)
print()
if i == 2: break
接下来,这是我的简单模型
import tensorflow as tf
input = tf.keras.layers.Input(shape=(1,))
x = tf.keras.layers.Dense(256,activation='relu')(input)
x = tf.keras.layers.Dense(512,activation='relu')(x)
output = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs=[input],outputs=[output])
编译模型
model.compile(
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001,clipvalue=1.0),loss = tf.keras.losses.MeanSquaredError(),metrics = tf.keras.metrics.MeanAbsoluteError()
)
现在,运行模型
model.fit(
gen,steps_per_epoch=int(len(df)/batch_size),epochs=10,workers=2
)
此时训练后,我得到 nan loss,有时会得到 inf
loss。这里有什么问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。