python - 多个损失函数,梯度没有
问题描述
除了 Keras 模型中的均方误差损失函数外,我还在使用自定义损失函数。自定义损失函数的代码如下:
def grad1(matrix):
dx = 1.0
u_x = np.gradient(matrix,dx,axis=0)
u_xx = np.gradient(u_x,dx,axis=0)
return u_xx
def artificial_diffusion(y_true, y_pred):
u_xxt = tf.py_func(grad1,[y_true],tf.float32)
u_xxp = tf.py_func(grad1,[y_pred],tf.float32)
lap_mse = tf.losses.mean_squared_error(u_xxt,u_xxp) + K.epsilon()
我有 1D CNN 模型。
input_img = Input(shape=(n_states,n_features))
x = Conv1D(32, kernel_size=5, activation='relu', padding='same')(input_img)
x = Conv1D(32, kernel_size=5, activation='relu', padding='same')(x)
x = Conv1D(32, kernel_size=5, activation='relu', padding='same')(x)
decoded1 = Conv1D(n_outputs, kernel_size=3, activation='linear', padding='same',
name='regression')(x)
decoded2 = Conv1D(n_outputs, kernel_size=3, activation='linear', padding='same',
name='diffusion')(x)
model = Model(inputs=input_img, outputs=[decoded1,decoded2])
model.compile(loss=['mse',artificial_diffusion],
loss_weights=[1, 1],
optimizer='adam',metrics=[coeff_determination])
当我编译并运行模型时,我得到一个错误An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.
。如果我将模型创建为model = Model(inputs=input_img, outputs=[decoded1,decoded1])
,则没有错误。但是,我不能分别监控两个损失。我在构建模型时是否犯了任何错误?
解决方案
推荐阅读
- css - 关键 CSS Rails:找不到路由的 css
- python - 如何使用鼠标滚轮用 Kivy 缩放矩形?
- gnuplot - 如何使用gnuplot在拟合()中的多项式曲线中的系数始终具有正值?
- python - 使用随机森林应用分层 10 折交叉验证
- angular - 解析器在到达确切网址之前将我路由到第 404 页
- bash - 自制的 ansible 模块不适用于 bash 脚本?
- vb.net - 发送电子邮件 VB.NET 时未将对象引用设置为对象的实例
- artifactory - 如何从没有属性的神器中获取最新的神器
- curl - 使用 cURL 传输原始数据
- python - 如何从 for 循环中创建绘图