问题
I'm beginner with tensorflow. I created this tensor
z = tf.zeros([20,2], tf.float32)
and I want to change the value of index z[2,1]
and z[2,2]
to 1.0
instead of zeros.
How can I do that?
回答1:
What you exactly ask is not possible for two reasons:
z
is a constant tensor, it can't be changed.- There is no
z[2,2]
, onlyz[2,0]
andz[2,1]
.
But assuming you want to change z
to a variable and fix the indices, it can be done this way:
z = tf.Variable(tf.zeros([20,2], tf.float32)) # a variable, not a const
assign21 = tf.assign(z[2, 0], 1.0) # an op to update z
assign22 = tf.assign(z[2, 1], 1.0) # an op to update z
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(z)) # prints all zeros
sess.run([assign21, assign22])
print(sess.run(z)) # prints 1.0 in the 3d row
回答2:
an easy way:
import numpy as np
import tensorflow as tf
init = np.zeros((20,2), np.float32)
init[2,1] = 1.0
z = tf.variable(init)
or use tf.scatter_update(ref, indices, updates)
https://www.tensorflow.org/api_docs/python/tf/scatter_update
回答3:
A much better way to accomplish this is to use tf.sparse_to_dense.
tf.sparse_to_dense(sparse_indices=[[0, 0], [1, 2]],
output_shape=[3, 4],
default_value=0,
sparse_values=1,
)
Output:
[[1, 0, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 0]]
However, tf.sparse_to_dense
is deprecated recently. Thus, use tf.SparseTensor and then use tf.sparse.to_dense to get the same result as above
来源:https://stackoverflow.com/questions/48842037/fill-a-specific-index-in-tensor-with-a-value