首页 > 解决方案 > 检查失败:1 == NumElements()(1 vs. 2)必须有一个单元素张量(神经网络度量)

问题描述

我有我的神经网络 int TF2,为此我想制定自己的指标。在我的函数中,我迭代抛出每个张量值并将新值添加到 output_list 中。我将作为新的 y_pred 堆叠并将其放入 mean_absolute_error 中。编译是可以的,但在第一次迭代中我在标题中得到错误。我究竟做错了什么?

@tf.function 
def custom_metric_mae( y_true , y_pred ):
    output_list=tf.TensorArray(dtype=tf.float32, size=tf.shape(y_pred))
    for i in range(223):
        dphi = abs(y_true[i][0]-y_pred[i][0])
        if(dphi > 0.5):
            output_list.write(i,1 - dphi)
        else:
            output_list.write(i,dphi)     
    y_PredChanged = output_list.stack()
    return tf.metrics.mean_absolute_error(y_true , y_PredChanged)

我的模型:

    model = keras.Sequential([
    keras.layers.Flatten(input_shape=(32,32)),
    keras.layers.Dense(64,activation="relu"),
    keras.layers.Dense(32,activation="relu"),
    keras.layers.Dense(16,activation="relu"),
    keras.layers.Dense(1, activation='linear')
    ])
model.compile(optimizer="adam",loss = "mean_absolute_error",metrics=[custom_metric_mae])

标签: pythontensorflowkerasmetrics

解决方案


Keras 的自定义指标的文档中:

该函数需要将 (y_true, y_pred) 作为参数并返回单个张量值。

tf.metrics.mean_absolute_error返回两个值:实际 MAE 和 an update_op,一旦评估,更新运行值并返回 MAE 值。我不完全确定这是否与 Keras 兼容,我建议将其替换为keras.metrics.mae

请注意,使用 Keras 时mae,您需要对最终结果进行平均(该函数应用于 and 的最后一个维度,y_true并且y_pred结果的形状y_true.shape[:-1]通常不会是一个值)。为此,请使用tf.math.reduce_mean

return tf.math.reduce_mean(keras.metrics.mae(y_true , y_PredChanged))

推荐阅读