我正在尝试在Keras中编写RMSE函数,该函数仅对不为零的数组值运行RMSE。我有两个数组arr1和arr2。两个数组在完全相同的位置都为零(因此它们对RMSE值贡献为零)。但是,我需要将要除以arr1(或arr2)中非零值的数量更改为数字
def root_mean_squared_error(y_true, y_pred):
nonzero = tf.count_nonzero(y_pred)
num_zeros=tf.reduce_sum(tf.where(tf.not_equal(y_pred,0),tf.ones_like(y_pred),tf.zeros_like(y_pred)))
return K.sqrt((K.sum(K.square(y_pred - y_true))/tf.cast(nonzero, tf.float32)))
mc = keras.callbacks.ModelCheckpoint('modelsPerEpoch/weights{epoch:06d}.hdf5',
save_weights_only=False,
period=1)
decay_learner = ValidationLearningRateScheduler()
main_input = Input(shape=(None, 2, 100, 100), dtype='float32', name='input')
mask=Input(shape=(1, 100, 100), dtype='float32', name='mask')
hidden = ConvLSTM2D(filters=16,
kernel_size=(5, 5),
padding='same',
return_sequences=False,
data_format='channels_first')(main_input)
output = Conv2D(filters=1,
kernel_size=(1, 1),
padding='same',
activation='sigmoid',
kernel_initializer='glorot_uniform',
data_format='channels_first',
name='output')(hidden)
output_with_mask=Multiply()([output, mask])
sgd = SGD(lr=0.002, momentum=0.0, decay=0.0, nesterov=False)
model = Model(inputs=[main_input, mask], outputs=output_with_mask)
model.compile(optimizer=sgd,
loss=root_mean_squared_error,
metrics=[metrics.mse, root_mean_squared_error])
但是,当我运行此命令时,在命令行中返回“ inf”。我该如何解决?
答案 0 :(得分:1)
y_true
和y_pred
在完全相同的位置具有零是无效的。您在命令行中获得inf
,因为y_pred
中的非零数字为0,即您的代码中nonzero
= 0。您应该计算正确的非零数字,并避免被以下代码除以0。
def root_mean_squared_error(y_true, y_pred):
nonzero = tf.count_nonzero(y_true)
...
return K.switch(K.equal(nonzero,0)
, K.constant(value=0.)
, K.sqrt((K.sum(K.square(y_pred - y_true))/tf.cast(nonzero, tf.float32))))