簡體   English   中英

如何索引張量並更改值

[英]How to index a tensor and change the value

我正在研究一種帶有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中實現這一點? Is there any way to to implement this in tensorflow using the same logic, not by converting NumPy arrays to tensor after the calculation, but instead doing all the operation using tensor (eg using tensor to index the tensor, and assign its value by x(張量)如果索引在集合中)。

您可以像這樣在 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]

我沒有清楚地理解你的問題。 但這就是我認為你需要的。 您可以使用 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 arrays 一樣進行各種計算,例如加、減等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM