python - 检查失败: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])
解决方案
从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))
推荐阅读
- php - Silverstripe 3:取消链接许多关系
- java - java.lang.String 类型中没有由@DynamoDBHashKey 注释的方法或字段
- matlab - 如何优化需要多个带通滤波器的基于 matlab 的音频可视化器?
- r - 通过 factor() 并使用 argparse 中的变量重新排序数据帧的列
- qt - Qtvirtualkeyboard 未显示在应用程序中
- javascript - StencilJS组件ReferenceError:添加第三方脚本时Firefox中的“模块未定义”错误
- css - Geonode-project 不假设 css 发生变化
- r - R创建替换组合
- r - 按列拆分 data.frame,将非顺序值作为单独的组处理
- python - 如何在熊猫的一栏中创建字典?