python - 为变分自编码器 keras 添加自定义损失函数
问题描述
我正在尝试为变分自动编码器添加自定义损失函数。除了重建损失,KL 散度我希望添加一个基于输入和输出对的汉明距离差异的损失。
但是我遇到的问题是,无论有没有这种额外的损失,结果都是一样的。谁能指出我应该做些什么来纠正它?它与尺寸或其他东西有关。
这是我的代码片段:
def ham_loss(y_true,y_pred):
# calculate pairwise hamming distance matrix
# differences of y_pred probabilities)
pairwise_diff_pred = K.expand_dims(y_pred, 0) - K.expand_dims(y_pred, 1)
pairwise_distance_pred = K.sum(pairwise_diff_pred, axis=-1)
# calculate pairwise hamming distance matrix for inputs
pairwise_diff_true = K.expand_dims(y_true, 0) - K.expand_dims(y_true, 1)
pairwise_distance_true = K.sum(pairwise_diff_true, axis=-1)
#Difference between the distances of y_true and y_predictions
hamm_sum= Lambda(differences)([pairwise_distance_true, pairwise_distance_pred])
print(hamm_sum)
return K.sum(hamm_sum, axis=-1)
def vae_loss(y_true, y_pred):
""" Calculate loss = reconstruction loss + KL loss for each data in minibatch """
# E[log P(X|z)]
recon = K.sum(K.binary_crossentropy(y_true,y_pred),axis=1)
# D_KL(Q(z|X) || P(z|X)); calculate in closed form as both dist. are Gaussian
kl = 0.5 * K.sum(K.exp(z_log_var) + K.square(z_mean) - 1. - z_log_var, axis=1)
hamming_loss = ham_loss(y_true,y_pred)
return recon + kl + hamming_loss
非常感谢任何帮助!
提前致谢..
解决方案
推荐阅读
- function - 使用功能 swiftUI 将视图添加到 contentView 不起作用
- multipartform-data - 如何解释缺少 CRLF 的多部分?
- azure - 将 Function App 连接到特定设备?
- css - 下拉菜单高度动画
- javascript - 如何使用 NextJS 和 useContext 挂钩跨页面保持状态?
- list - 有人可以用我的 Haskell 代码诊断问题吗?
- pg-promise - 在 pg-promise 查询中返回未定义的空值
- multithreading - 在阿姆达尔定律中估计 P
- java - 用asm如何声明一个非泛型类实现泛型接口
- c# - WPF绑定到静态资源不起作用