我试图进行切片分配,但即使我将所有张量转换为变量,我也会收到以下错误:
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]
答案 0 :(得分: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.control_dependencies 强>
希望这会有所帮助。