【发布时间】:2021-07-20 03:01:35
【问题描述】:
我在使用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。 -
@ShubhamPanchal 我试过了,但是没用...
标签: python tensorflow keras deep-learning