我正在尝试使用如下所示的自定义损失函数来训练自动编码器。输入 Missing_matrix 是一个由 1 和 0 组成的 nxm 数组,对应于 nxm 特征数组。我需要将 Missing_array 与 y_pred 进行逐个元素相乘,这应该是输入特征的重建,以便我可以屏蔽那些乘以 0 的特征,以忽略它们在成本函数中的贡献。我以前从未编写过自定义损失函数,下面的函数根本不起作用。我曾尝试搜索类似的自定义成本函数,但无法找到一个引入像这样的输入数组的函数。我将不胜感激您的帮助或正确方向的指出。
def custom_loss(missing_array):
def missing_mse(y_true, y_pred):
mse = MeanSquaredError()
y_pred_masked = tf.math.multiply(y_pred, missing_array)
return mse(y_true = y_true, y_pred = y_pred_masked)
return missing_mse
Run Code Online (Sandbox Code Playgroud)
编辑:更进一步
from keras.losses import MeanSquaredError
import tensorflow as tf
def custom_loss(missing_matrix):
def missing_mse(y_true, y_pred):
mse = MeanSquaredError()
y_pred_masked = tf.math.multiply(y_pred, tf.convert_to_tensor(missing_matrix, dtype=tf.float32))
return mse(y_true = y_true, y_pred = y_pred_masked)
return missing_mse
Run Code Online (Sandbox Code Playgroud)
有错误
InvalidArgumentError: Incompatible shapes: [64,1455] vs. [13580,1455]
[[node gradient_tape/missing_mse/BroadcastGradientArgs (defined at …Run Code Online (Sandbox Code Playgroud)