首页 > 解决方案 > 多个损失函数,梯度没有

问题描述

除了 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]),则没有错误。但是,我不能分别监控两个损失。我在构建模型时是否犯了任何错误?

标签: pythontensorflowkeras

解决方案


推荐阅读