python - 如何在 Keras 模型的自定义损失中访问张量的内容
问题描述
我正在使用 Keras 模型构建一个自动编码器。我想以alpha* L2(x, x_pred) + beta * L1(day_x, day_x_pred)
. L1损失的第二项关于时间的惩罚(day_x是天数)。这一天是我输入数据中的第一个特征。我的输入数据是形式 ['day', 'beta', 'sigma', 'gamma', 'mu']
。
输入 x 的形状(batch_size,特征数),我有 5 个特征。所以我的问题是如何从x and x_pred
计算中提取第一个特征L1(t_x, t_x_pred)
。这是我当前的损失函数:
def loss_function(x, x_predicted):
#with tf.compat.v1.Session() as sess: print(x.eval())
return 0.7 * K.square(x- x_predicted) + 0.3 * K.abs(x[:,1]-x_predicted[:,1])
但这对我不起作用。
解决方案
这是你需要的损失...
你必须计算你的错误的手段
def loss_function(x, x_predicted):
get_day_true = x[:,0] # get day column
get_day_pred = x_predicted[:,0] # get day column
day_loss = K.mean(K.abs(get_day_true - get_day_pred))
all_loss = K.mean(K.square(x - x_predicted))
return 0.7 * all_loss + 0.3 * day_loss
否则,您必须插入一个维度
def loss_function(x, x_predicted):
get_day_true = x[:,0] # get day column
get_day_pred = x_predicted[:,0] # get day column
day_loss = K.abs(get_day_true - get_day_pred)
all_loss = K.square(x - x_predicted)
return 0.7 * all_loss + 0.3 * tf.expand_dims(day_loss, axis=-1)
编译模型时使用损失
model.compile('adam', loss=loss_function)
推荐阅读
- python - 如何单击 buster 按钮以使用 Python 和 selenium 解决 reCaptcha?
- mysql - 需要在 SQL 帮助中使用 IF 函数(SQL 新手)
- sql-server - 事务日志传送 - 即使我设置了“断开用户连接”,由于独占访问权限恢复失败
- r - 反转 image.plot 中的比例着色
- api - 错误:生成 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\15.0\Bin\MSBuild.exe ENOENT
- spring-boot - 如何运行“独立”Camunda 引擎(带有 cockpit、rest api 等)并让我现有的 Spring Boot 应用程序服务于任务(JavaDelegate)
- python - 如何使用插补类将值替换为上一行中的值?
- python - 如何在 PyQt6 中设置窗口标志?
- python - 使用 PIP 安装手电筒
- typescript - 如何导入这个 JavaScript 库?