我正在尝试进行切片赋值,但出现以下错误,即使在我将所有张量转换为变量之后也是如此:
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
希望这对您有所帮助。
