Keras自定义损失函数实现:自编码器仅基于指定神经元计算损失
解决方案
核心实现思路
你之前直接修改张量切片报错是因为TensorFlow的计算图张量为不可变对象,不支持直接对某一段切片赋值,也不需要将张量转为numpy数组,直接使用Keras后端的张量切片操作即可实现仅前200列参与损失计算,有两种常用实现方式:
方案1:直接切片计算(推荐)
直接截取y_true和y_pred的前200列计算损失,完全忽略后300列的数值,性能最优:
def vae_loss(y_true, y_pred): # 仅取前200列计算均方误差 reconstruction_loss = K.mean(K.square(y_true[:, :200] - y_pred[:, :200])) return reconstruction_loss
方案2:后300列置0计算(符合你最初的思路)
如果需要保留输出维度一致,将后300列赋值为0后再计算损失:
def vae_loss(y_true, y_pred): # 前200列保留原值,后300列置0 y_true_masked = K.concatenate([y_true[:, :200], K.zeros_like(y_true[:, 200:])], axis=-1) y_pred_masked = K.concatenate([y_pred[:, :200], K.zeros_like(y_pred[:, 200:])], axis=-1) reconstruction_loss = K.mean(K.square(y_true_masked - y_pred_masked)) return reconstruction_loss
原有代码的已知问题修正
你提供的示例代码存在几处语法错误,修复后可正常运行:
- 导入numpy时未指定别名
np,需修改为import numpy as np - 编码器部分变量名错误:此前定义的隐藏层变量为
x,后续误写为z,且Lambda层不支持units参数,应该改为全连接层:
# 修正后的编码器部分 encoder_input = keras.Input(shape=(data.shape[1],), name="encoder_input") x = layers.Dense(units=128, activation='relu')(encoder_input) encoder_output = layers.Dense(units=latent_dim, name="encoder_output")(x) encoder = Model(encoder_input, encoder_output, name='encoder_model')
- 输入层的shape参数需要加逗号表示元组,修改为
shape=(data.shape[1],)
内容的提问来源于stack exchange,提问作者Thomas Kodill
相关产品推荐
相关产品推荐

