简体   繁体   English

自定义损失 function Tensorflow 2 [Keras 符号输入/输出未实现]

[英]Custom loss function Tensorflow 2 [Keras symbolic inputs/outputs do not implement]

I'm trying to use custom loss function and started with simple MSE.我正在尝试使用自定义损失 function 并从简单的 MSE 开始。 Do not pay attention to oscillator function, it needs just for creating data.不要关注oscillator function,它只需要用于创建数据。

import numpy as np
import matplotlib.pyplot as plt

from keras.layers import Input, Dense
from keras.models import Model
import tensorflow as tf


def oscillator(d_, w0_, x):
    assert d_ < w0_
    w = np.sqrt(w0_**2 - d_**2)
    phi = np.arctan(-d_/w)
    A = 1/(2*np.cos(phi))
    cos = np.cos(phi+w*x)
    sin = np.sin(phi+w*x)
    exp = np.exp(-d_*x)
    return exp*2*A*cos



# PARAMETERS:
np.random.seed(5)
N = 20
epochs = 2000
d, w0 = 2, 20
nn_dim = 64


# DATA:
x = np.linspace(0,1,100)
y = oscillator(d,w0,x)

x_train = np.sort(np.random.uniform(0,0.35,N)[:,np.newaxis], axis=0)
y_train = oscillator(d,w0,x_train)

tf_y = tf.Variable(y_train,dtype=tf.float32)



# LAYERS:
input_layer = Input(shape=(1,))
Layer_1 = Dense(nn_dim, activation="tanh")(input_layer)
Layer_2 = Dense(nn_dim, activation="tanh")(Layer_1)
output_layer = Dense(1)(Layer_2)
model = Model(inputs=input_layer, outputs=output_layer)



loss_func = tf.reduce_mean(tf.math.squared_difference(tf_y,output_layer))
model.compile(optimizer='adam', loss=loss_func, metrics=['mse'])


md = model.fit(x_train,y_train,epochs=epochs,verbose=1)
y_pred = model.predict(x[:,np.newaxis])


# PLOTTING:
fig = plt.figure()
plt.plot(md.history['loss'], label='training')
plt.legend()

plt.figure()
plt.plot(x,y,label="Exact solution")
plt.scatter(x_train,y_train,label="Data",color="orange")
plt.plot(x,y_pred,label="Prediction",linestyle="--",color="red")
plt.legend()
plt.show()

The code above produces the following error: TypeError: Keras symbolic inputs/outputs do not implement __len__ .上面的代码产生以下错误: TypeError: Keras 符号输入/输出不实现__len__ You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.如果您尝试直接断言符号输入/输出,也会引发此错误。 Process finished with exit code 1进程以退出代码 1 结束

The problem is in loss_func = tf.reduce_mean(tf.math.squared_difference(tf_y,output_layer)) .问题在于loss_func = tf.reduce_mean(tf.math.squared_difference(tf_y,output_layer)) I think this is because of different dimensions of tf_y and output_layer .我认为这是因为tf_youtput_layer的不同维度。 Any ideas how to compute MSE by hand using output_layer and y ?任何想法如何使用output_layery手动计算 MSE?

I've personally never seen a loss defined like that (and I hardly think that it might work), you usually want to create a function:我个人从未见过这样定义的损失(而且我几乎不认为它可能会起作用),您通常想要创建一个 function:

def loss_func(tf_y, output_layer):
  return tf.reduce_mean(tf.math.squared_difference(tf_y,output_layer))

from the documentation:从文档中:

loss argument of compile : may be a string (name of loss function), or a tf.keras.losses.Loss instance. compile 的 loss 参数:可以是字符串(损失函数的名称),也可以是 tf.keras.losses.Loss 实例。 See tf.keras.losses.参见 tf.keras.losses。 A loss function is any callable with the signature loss = fn(y_true,y_pred), where y_true are the ground truth values, and y_pred are the model's predictions损失 function 是具有签名 loss = fn(y_true,y_pred) 的任何可调用损失,其中 y_true 是真实值,y_pred 是模型的预测

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Keras 符号输入/输出未实现 __len__ 错误 - Keras symbolic inputs/outputs do not implement __len__ Error Keras / Tensorflow自定义损失函数 - Keras/Tensorflow custom loss function 无法将数据输入自定义损失:急切执行 function 的输入不能是 Keras 符号张量 - Can't input data to custom loss: Inputs to eager execution function cannot be Keras symbolic tensors 自定义损失问题:急切执行的输入 function 不能是 keras 符号张量但找到 - Custom loss problem: inputs to eager execution function cannot be keras symbolic tensors but found 基于输入的输出子集上的自定义损失函数 - Custom loss function on subset of outputs based on inputs Keras - 使用多个输出实现自定义损失 function - Keras - Implementation of custom loss function with multiple outputs 自定义损失 function 并拟合 tf.Keras 中多个输入和输出的数据 - Custom loss function and fit data for multiple inputs and outputs in tf.Keras 如何在 tensorflow keras 中实现 AUROC 作为损失函数 - How to implement AUROC as loss function in tensorflow keras 关于带有TensorFlow后端的Keras的自定义损失功能的问题 - Issue on custom loss function with Keras with TensorFlow backend Keras 中的自定义损失 Function - 遍历 TensorFlow - Custom Loss Function in Keras - Iterate through TensorFlow
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM