gpt4 book ai didi

python - 张量到变量的切片赋值

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:20 26 4
gpt4 key购买 nike

我正在尝试进行切片赋值,但出现以下错误,即使在我将所有张量转换为变量之后也是如此:

array = tf.Variable(tf.zeros((b,n,m)))
ones = tf.Variable(tf.ones((m)))
labels = tf.Variable(tf.ones((b), dtype=tf.int32))

for i in range(b):
with tf.control_dependencies([array[i][labels[i]].assign(ones)]):
array = tf.identity(array)

ValueError: Sliced assignment is only supported for variables

如何在 TensorFlow 中进行此分配:

array[i][labels[i]] = [1,1,1,1,1,1] 

?

最佳答案

我已经在必要时使用注释更新了您的代码。

array = tf.Variable(tf.zeros((b,n,m)))
ones = tf.Variable(tf.ones((m)))
labels = tf.Variable(tf.ones((b), dtype=tf.int32))
#labels = np.ones(b,dtype=np.int8) if you want a array

with tf.control_dependencies([array[i,labels[i],:].assign(tf.ones(m)) for i in range(b)]): # should give the list of slice assignment here
array = tf.identity(array) #conver to a tensor

sess = tf.Session()
with sess.as_default():
sess.run(tf.global_variables_initializer())
print(array.eval()) #print the new array (optional, only to see the values)

注意事项

  • [array[i][labels[i]] ---> [array[i,labels[i],:]] 对我来说似乎是一个语法错误。

  • tf.identity(array) 返回一个张量作为数组的形状。当您再次将其分配给array 时,array 将变为tensor 而不是不再是变量。您不能对张量进行切片分配

  • 您需要提供一个切片分配列表作为参数tf.control_dependencies

    希望这对您有所帮助。

关于python - 张量到变量的切片赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com