如何将Keras张量转换为TensorFlow张量?

4

我在使用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
@ShubhamPanchal 我已经尝试了,但是它不起作用... - Zimu Wang
1个回答

0
这是由于最新版本的numpy(1.20)导致的。按照以下方式降级numpy版本(假设您正在使用conda):
conda install -c conda-forge numpy=1.19.5

1
亲爱的 @omsrisagar,我会在您的指导下尝试处理它。谢谢! - Zimu Wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接