我试图训练一个自编码器,并使用下面的自定义损失函数。输入missing_matrix是一个n x m的数组,包含1和0,对应于n x m的特征数组。我需要对missing_array和y_pred进行逐元素乘法,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
编辑:进展了一点
from keras.losses import MeanSquaredErrorimport tensorflow as tfdef 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
出现错误
InvalidArgumentError: Incompatible shapes: [64,1455] vs. [13580,1455] [[node gradient_tape/missing_mse/BroadcastGradientArgs (defined at <ipython-input-454-b60d74568bf2>:64) ]] [Op:__inference_train_function_25950]Function call stack:train_function
64让我觉得这是批次。可能我需要取我的缺失矩阵的64个批次?
编辑2:这很有趣!所以我验证了如果我这样做,自定义损失函数会训练
def train(self, model, X_train): """ 模型训练 """ #model.fit(X_train, X_train, epochs = 10, batch_size = 64, validation_split = 0.10) for batch_idx in range(0, len(X_train), 70): self.batch_start = batch_idx self.batch_end = batch_idx + 70 model.train_on_batch(X_train[self.batch_start:self.batch_end,:], X_train[self.batch_start:self.batch_end,:]) return model
并修改我的自定义损失
def custom_loss2(self, 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[self.batch_start:self.batch_end,:], dtype=tf.float32)) return mse(y_true = y_true[self.batch_start:self.batch_end,:], y_pred = y_pred_masked[self.batch_start:self.batch_end,:]) return missing_mse
那么现在我如何获得epochs并打印出验证损失等…?或者说更好的方法是什么?今晚就到这里了。晚安!
回答:
问题在于y_true
和y_pred
是分批次的,而掩码是一次性传递的。一个简单的解决方案是使用model.add_loss()
来自动将数据分割成相等的批次。
下面我用一个自编码器和一个自定义掩码损失函数重现了一个虚拟示例。掩码作为模型输入传递,这是使其工作的简单技巧。
另外,使用mean_squared_error
而不是MeanSquaredError
。
def missing_mse(y_true, y_pred, missing_array): y_pred_masked = tf.math.multiply(y_pred, missing_array) mse = tf.keras.losses.mean_squared_error(y_true = y_true, y_pred = y_pred_masked) return mseinp = Input((100,))x = Dense(20)(inp)out = Dense(100)(x)inp_mask = Input((100,))model = Model([inp, inp_mask], out)model.add_loss(missing_mse(inp, out, inp_mask))model.compile('adam', loss=None)X = np.random.uniform(0,1, (300,100))mask = np.random.randint(0,2, (300,100))model.fit(x=[X,mask], y=None, epochs=10, batch_size=64)# 在推理时,你可以通过这种方式移除掩码输入new_model = Model(model.input[0], model.output)new_model.predict(X).shape