我在使用tensorflow.keras训练时遇到了一些问题。我使用了tensorflow.keras.backend定义了一个损失函数。代码如下:
import tensorflow.keras.backend as K
def gradient_penalty_loss(y_true, y_pred, averaged_samples, weight):
gradients = K.gradients(y_pred, averaged_samples)[0]
gradients_sqr = K.square(gradients)
gradient_penalty = K.sum(gradients_sqr,
axis=np.arange(1, len(gradients_sqr.shape)))
# (weight / 2) * ||grad||^2
# Penalize the gradient norm
return K.mean(gradient_penalty) * (weight / 2)
def hinge_d(y_true, y_pred):
return K.mean(K.relu(1.0 - (y_true * y_pred)))
def w_loss(y_true, y_pred):
return K.mean(y_true * y_pred)
然而,以下语句出现了错误:
Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, 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.
在查找了一些信息后,我注意到问题可能是因为损失函数的输出是 Keras 张量,无法由 TensorFlow 操作。那么我该如何解决这个问题?谢谢!
K.arange
替代np.arange
。 - Shubham Panchal