【问题标题】:How to Convert Keras Tensor to TensorFlow Tensor?如何将 Keras 张量转换为 TensorFlow 张量?
【发布时间】: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


【解决方案1】:

这是由于最新版本的 numpy (1.20) 造成的。将 numpy 版本降级如下(假设您使用的是 conda):

conda install -c conda-forge numpy=1.19.5

【讨论】:

  • 亲爱的@omsrisagar,我会在你的指导下努力解决。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2018-12-02
  • 2021-11-19
  • 2016-10-15
  • 2019-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多