我在使用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张量,它不能被张量流操纵。那么我该如何处理这个问题呢?谢谢
这是由于最新版本的numpy(1.20(造成的。按如下方式降级numpy版本(假设您使用的是conda(:
conda install -c conda-forge numpy=1.19.5