python - 自定义keras损失函数
问题描述
我想在 keras 中编写一个自定义损失函数,它还使用输入的输出梯度
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout
model = Sequential()
model.add(Dense(200, input_dim=20, activation='relu'))
model.add(Dense(64, input_dim=20, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
现在,我想替换损失函数。我只知道如何使用tensorflow编写如下:
x = tf.placeholder(tf.float32, shape=[None, 1], name="x")
ext_f0 = tf.placeholder(tf.float32, shape=[None, 1], name="f")
xx0 = tf.concat([[[R_variable['x_start'] * 1.0],[R_variable['x_end'] * 1.0]], x], 0)
yy0 = univAprox(xx0)
Boundary_y = yy0[0:2]
y = yy0[2:]
GradU = tf.gradients(y,x) #***KEY***
GradSum = tf.reduce_sum(tf.square(GradU)) / 2 * dx_train
FSum = tf.reduce_sum(tf.multiply(ext_f0,y)) * dx_train
loss = GradSum + FSum + Beta * tf.reduce_sum(tf.square(Boundary_y))
关键是我需要得到GradU
. 我应该如何在 keras 中做到这一点?
解决方案
您可以编写自定义损失函数。你应该知道的是它的形式:
def custom_loss(y_true, y_pred):
# do something to compute loss
...
return loss
应该就是这样。
推荐阅读
- regex - 使用 yq/sed/grep 提取与 YAML 中的正则表达式匹配的键值对
- r - 如何使用 dplyr 将具有不同值的两个不同行汇总为具有该总和的单行?
- python - 如何在 MongoDB 中设置集合名称
- bash - Bash 脚本的子命令中的问题
- javascript - 脚本;d3.js - 为什么我不能创建热图?
- nginx - nginx 检查文件夹中是否存在 *.pdf 文件
- r - 从坐标列表中制作 Owin 对象
- reactjs - 如何将自定义 CSS 样式应用于 Kendo React 组件?
- python - 在 cmd 提示符和 vscode 中为同一环境显示不同版本的 django
- snapshot-testing - 如何格式化 Verify.PlayWright 返回的 HTML 以便更好地比较