将tf.tensor转换为numpy

发布于 2025-01-27 04:35:12 字数 492 浏览 1 评论 0原文

我已经构建了一个自定义损耗功能来训练我的模型,

def JSD_Tensor_loss(P,Q):
  P=tf.make_ndarray(P)
  Q=tf.make_ndarray(Q)

  M=np.divide((np.sum(P,Q)),2)
  D1=np.multiply(P,(np.log(P,M)))
  D2=np.multiply(Q,(np.log(Q,M)))

  JSD=np.divide((np.sum(D1,D2)),2)
  JSD=np.sum(JSD)
  return JSD

model.compile(optimizer='adam', loss=JSD_Tensor_loss, metrics=['accuracy'])
model.fit(x_train, x_test, epochs=EPOCHS)

尽管我将张量参数转换为numpy,但是我有以下错误,无法解决它 attributeError:“张量”对象没有属性'tensor_shape'

I've built a custom loss function to train my model

def JSD_Tensor_loss(P,Q):
  P=tf.make_ndarray(P)
  Q=tf.make_ndarray(Q)

  M=np.divide((np.sum(P,Q)),2)
  D1=np.multiply(P,(np.log(P,M)))
  D2=np.multiply(Q,(np.log(Q,M)))

  JSD=np.divide((np.sum(D1,D2)),2)
  JSD=np.sum(JSD)
  return JSD

model.compile(optimizer='adam', loss=JSD_Tensor_loss, metrics=['accuracy'])
model.fit(x_train, x_test, epochs=EPOCHS)

Although I've converted the tensor params to numpy but I've having the following error and cant solve it
AttributeError: 'Tensor' object has no attribute 'tensor_shape'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想念有你 2025-02-03 04:35:12

您的错误源于您的转换为numpy.Array(前两行)。

如果您必须转换张量(我认为在这种情况下不应该这样),我会选择:

P, Q = P.numpy(), Q.numpy()

但是,这确实不是必需的。只需用相应的tf.math函数替换numpy函数(您应该很好:(

def JSD_Tensor_loss(P,Q):

    M=tf.math.divide((tf.math.add(P,Q)),2)
    D1=tf.math.multiply(P,(tf.math.log(P)))
    D2=tf.math.multiply(Q,(tf.math.log(Q)))

    JSD=tf.math.divide((tf.add(D1,D2)),2)
    JSD=tf.math.reduce_sum(JSD)
    return JSD

我不明白您对NP.Log的电话。您是否可以使用该函数的过时版本( docs

Your error stems from your conversion to numpy.array (first two lines).

If you have to convert a tensor (which in my opinion you shouldn't in this case), I would go with:

P, Q = P.numpy(), Q.numpy()

However, this is really not necessary here. Just replace the numpy function with the respective tf.math function (docs) and you should be good:

def JSD_Tensor_loss(P,Q):

    M=tf.math.divide((tf.math.add(P,Q)),2)
    D1=tf.math.multiply(P,(tf.math.log(P)))
    D2=tf.math.multiply(Q,(tf.math.log(Q)))

    JSD=tf.math.divide((tf.add(D1,D2)),2)
    JSD=tf.math.reduce_sum(JSD)
    return JSD

(I did not understand your call to np.log. Do you maybe use an outdated version of the function (docs))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文