【问题标题】:How to index a tensor and change the value如何索引张量并更改值
【发布时间】:2020-10-16 22:42:42
【问题描述】:

我正在使用tensorflow 研究算法。 以下是所需代码的NumPy 版本:

x = [1,2,3,4,5,6,7,8,9,10]
sets = {1,5,7}
y = [0,0,0,0,0,0,0,0,0,0]

for i in range(10):
    if i in sets:
        y[i] = x[i]

得到结果:

y = [0,2,0,0,0,6,0,8,0,0]

如何在tensorflow 中实现这一点? 有没有办法在tensorflow 中使用相同的逻辑来实现这一点,而不是在计算后将NumPy 数组转换为张量,而是使用张量进行所有操作(例如,使用张量来索引张量,并分配其如果索引在集合中,则按 x(tensor) 计算值)。

【问题讨论】:

  • 我不明白你在问什么。您的代码似乎运行良好。
  • @Hoppo 他的代码很好。他在问如何在 tensorflow 中做同样的事情......

标签: python tensorflow


【解决方案1】:

你可以在 TensorFlow 中这样做:

import tensorflow as tf
x = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
sets = tf.constant([1, 5, 7])
y = tf.constant([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
y2 = tf.tensor_scatter_nd_update(y, tf.expand_dims(sets, 1), tf.gather(x, sets))
print(y2.numpy())
# [0 2 0 0 0 6 0 8 0 0]

如果你的y 总是由零组成(也就是说,你只想“填充”sets 给出的位置),那么你可以这样做:

import tensorflow as tf
x = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
sets = tf.constant([1, 5, 7])
y2 = tf.scatter_nd(tf.expand_dims(sets, 1), tf.gather(x, sets), tf.shape(x))
print(y2.numpy())
# [0 2 0 0 0 6 0 8 0 0]

作为一种替代方法,您也可以使用遮罩来做到这一点,尽管我认为它不应该更快:

import tensorflow as tf
x = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
sets = tf.constant([1, 5, 7])
y = tf.constant([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
s = tf.shape(x, out_type=sets.dtype)
mask = tf.math.reduce_any(tf.equal(tf.range(s[0]), tf.expand_dims(sets, 1)), 0)
y2 = tf.where(mask, x, y)
# Or if y is always zeros:
#y2 = x * tf.dtypes.cast(mask, x.dtype)
print(y2.numpy())
# [0 2 0 0 0 6 0 8 0 0]

【讨论】:

    【解决方案2】:

    我没有清楚地理解你的问题。但这就是我认为你需要的。您可以使用

    将numpy数组转换为张量
    test_array = np.array([1,2,3,4])
    random1_array = tf.convert_to_tensor(test_array)
    

    如果您不想使用 numpy 并将其转换为张量,这是另一种方法。

    test_array = tf.Variable([1,2,3,4])
    test_array_2 = tf.Variable([5,6,7,8])
     
    

    现在您可以进行各种计算,例如加法、减法等。 就像你对 numpy 数组所做的那样。

    【讨论】:

    • 我知道有一种方法可以使用 convert_to_tensor ,有没有办法以张量的方式计算,而不是在通过 numpy 计算后进行转换?谢谢
    猜你喜欢
    • 2018-07-02
    • 2020-06-11
    • 2021-12-30
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多