首页 > 解决方案 > Tensorflow/Keras - 在损失函数中使用 NN 导数

问题描述

我目前正在使用 tensorflow 估计正弦函数。我想通过在我的损失函数中添加一个导数项来包括 sinus 的二阶导数等于 -sinus 的事实。我对 tf. 我当前的代码看起来像这样

import tensorflow as tf
import numpy as np

from tensorflow import keras
from numpy import random

# --- Settings
x_min = 0
x_max = 2*np.pi

n_train = 64
n_test = 64

# --- Generate dataset
x_train = random.uniform(x_min, x_max, n_train)
y_train = np.sin(x_train)

x_test = random.uniform(x_min, x_max, n_test)
y_test = np.sin(x_test)

# --- Create model
model = keras.Sequential()

model.add(keras.layers.Dense(64, activation="tanh"))
model.add(keras.layers.Dense(64, activation="tanh"))

model.add(keras.layers.Dense(1, activation="tanh"))

def custom_loss(y_true, y_pred):
    return keras.losses.mean_squared_error(y_true, y_pred)

# --- Configure learning process
model.compile(
        optimizer=keras.optimizers.Adam(0.01),
        loss=custom_loss,
        metrics=['MeanSquaredError'])

# --- Train from dataset
model.fit(x_train, y_train, epochs=100, batch_size=32, validation_data=(x_test, y_test))

model.evaluate(x_test, y_test)

目前该custom_loss功能只是普通的 MSE。我想包括 NN 输出 wrt 输入点的导数x_test。我怎样才能将这样一个术语纳入我的损失函数中。

我已经查了几个问题。特别是这个问题看起来很相似,但我不知道如何在我的代码示例中使用答案。谢谢您的帮助。

标签: pythontensorflowkerasderivativemean-square-error

解决方案


推荐阅读