我正在尝试使用神经网络(Keras)以及数据和事实d/dx d/dx sin(x) = -sin(x)
来近似正弦函数。正弦函数的此属性用于神经网络的自定义损失函数。
我的代码当前看起来像这样
import tensorflow as tf
import numpy as np
from tensorflow import keras
from numpy import random
# --- Disable eager execution
tf.compat.v1.disable_eager_execution()
# --- 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", input_dim=1))
model.add(keras.layers.Dense(64, activation="tanh"))
model.add(keras.layers.Dense(1, activation="tanh"))
def grad(input_tensor, output_tensor):
return keras.layers.Lambda( lambda z: keras.backend.gradients( z[ 0 ], z[ 1 ] ), output_shape = [1] )( [ output_tensor, input_tensor ] )
def custom_loss_wrapper(input_tensor, output_tensor):
def custom_loss(y_true, y_pred):
mse_loss = keras.losses.mean_squared_error(y_true, y_pred)
derivative_loss = keras.losses.mean_squared_error(input_tensor, -grad(input_tensor, grad(input_tensor, output_tensor))[0])
return mse_loss + derivative_loss
return custom_loss
# --- Configure learning process
model.compile(
optimizer=keras.optimizers.Adam(0.01),
loss=custom_loss_wrapper(model.input, model.output),
metrics=['MeanSquaredError'])
# --- Train from dataset
model.fit(x_train, y_train, batch_size=32, epochs=1000, validation_data=(x_test, y_test))
# --- Evaluate model
model.evaluate(x_test, y_test)
特别重要的是自定义损失函数。导数的Lambda定义来自this question。可悲的是,该模型似乎无法正确训练。损失接近零并保持在10以上。
没有导数项,网络工作正常,但我似乎无法在导数计算中发现错误。谢谢您的帮助!
答案 0 :(得分:0)
对于您的模型,您可以尝试进行超参数调整,
您还可以添加更多层,添加辍学以进行过度拟合,并尝试使用不同的激活功能和优化方法 。
通过执行所有这些操作,您将能够获得良好的模型性能。