【问题标题】:Write Numpy operations using Tensor使用 Tensor 编写 Numpy 操作
【发布时间】:2021-01-01 09:31:13
【问题描述】:

我希望在损失函数中使用这个 numpy 代码:

import numpy as np

y_true = np.random.randint(10, size=10000)
y_pred = np.random.randint(10, size=10000)
A = np.random.randint(12, size=(12,12))

S = -np.sum(A[y_true[:], y_pred[:]]) 

Obs:“A”是二维 numpy 数组,我需要用于损失函数的“惩罚矩阵”,其尺寸为 12x12。 y_true 和 y_pred 都是 nx1 numpy 数组 它工作正常,但我真正想要的是它的张量版本。我已经尝试了以下方法:

import keras.backend as K
import tensorflow as tf

A = tf.constant(A)
y_true = tf.constant(y_true)
y_pred = tf.constant(y_pred)

S = -K.sum(A[y_true[:], y_pred[:]])

Obs:在这种情况下,“A”是一个二维张量,是我的损失函数需要使用的“惩罚矩阵”,它的尺寸是 12x12。 y_true 和 y_pred 都是 Nx1 张量。 我想执行相同的操作,但使用张量。我已经尝试过以下方法: 但我收到以下错误:

InvalidArgumentError: Expected begin, end, and strides to be 1D equal size tensors, but got shapes [2,12,1], [2,12,1], and [2] instead. [Op:StridedSlice] name: strided_slice/

【问题讨论】:

  • 请提供一个最小的、可重现的例子。用户无需更改任何内容即可复制、粘贴和运行的内容。
  • 好的,刚刚添加了一些示例数据。

标签: python numpy tensorflow keras


【解决方案1】:

您可以为此使用tf.gather_nd

tf.gather_nd(A, tf.stack((y_true, y_pred), axis=-1))

等价于

A[y_true, y_pred]

完整的 numpy 和 tensorflow 代码请参见下文。

import numpy as np
import tensorflow as tf

K = tf.keras.backend

y_true = np.random.randint(10, size=10000)
y_pred = np.random.randint(10, size=10000)
A = np.random.randint(12, size=(12,12))

S_np = -np.sum(A[y_true, y_pred])
S_tf = -K.sum(tf.gather_nd(A, tf.stack((y_true, y_pred), axis=-1)))

assert S_np == S_tf.numpy()

顺便说一下,y_true[:]在这种情况下是多余的,可以写成y_true

另外,不要混用 tf.keraskeras。我不确定你是不是,但请坚持其中一个,最好是tf.keras

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多