稀疏分类交叉熵未按预期工作

时间:2020-05-23 13:02:24

标签: python machine-learning keras classification

我正在研究MIMIC 3数据集以对患者进行分类。我有7000个类别,并且类别的值范围最大为50000,标签是整数。因此,我使用了稀疏的分类熵损失,因此我不必担心标签的范围很大。但是我的模型给标签上的nan损失大于7000。

n_timesteps, n_features, n_outputs = 50, 59, 7000
batch_size=32
model = Sequential()
model.add(CuDNNLSTM(32, input_shape=(n_timesteps,n_features)))
model.add(Dropout(0.3))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(n_outputs, activation='softmax'))
model.compile(loss=keras.losses.sparse_categorical_crossentropy, optimizer=keras.optimizers.Adam(), metrics=['sparse_categorical_accuracy'])

我正在通过

对数据进行归一化
def normalize(df):

  header=df.columns
  subid_col=df['SUBJECT_ID']
  label_col=df['label']
  df = df.replace(0, np.NaN)
  df=pd.DataFrame(df).fillna(method="ffill")
  df=pd.DataFrame(df).fillna(df.mean())
  df=pd.DataFrame(df).fillna(-99)
  x = df.values
  header=df.columns

  min_max_scaler = preprocessing.MinMaxScaler(feature_range = (1,2))
  x_scaled = min_max_scaler.fit_transform(x)
  df = pd.DataFrame(x_scaled)
  df=pd.DataFrame(df).fillna(-1)

  df.columns=header

  df['SUBJECT_ID']=subid_col
  df['label']=label_col
  df.drop(df.columns[0], axis = 1, inplace = True)

  return df

我正在进行时间序列分类。

1 个答案:

答案 0 :(得分:0)

由于您的最后一层的长度为 n_outputs=7000sparse_categorical_crossentropy 需要在 [0, 7000] 范围内使用索引表示法的标签。因此,您需要在训练之前映射您的标签,即:

from sklearn import preprocessing

le = preprocessing.LabelEncoder()
le.fit(label_col)

df['label'] = le.transform(label_col)

要从编码中检索“真实”标签,您可以使用 le.inverse_transform(label_col)


或者,您也可以更改您的 n_outputs = 50000,但是如果您只训练/期望看到其中 7000 个的子集,这可能会效率低下,因为您不必要地添加了理想情况下可以学习的参数0,因为您没有这些标签的数据。