Python 创建随机索引为零的张量
现在我有一个张量Python 创建随机索引为零的张量,python,tensorflow,Python,Tensorflow,现在我有一个张量random\u row,我想创建一个新的张量,它的形状是2维的,它的random\u row是全零,所有其他行都是一,例如 random_row=[1,3]#random_row本身就是一个张量 #新的_张量需要是另一个张量,其随机_行中的行都是零 #我们已经知道新的张量的形状是(4,2) 新的_张量=[[1,1],[0,0],[1,1],[0,0]] 我怎样才能做到这一点?如果有人能帮忙,我真的很感激 您可以使用类似于his的函数来实现这一点: import tensorf
random\u row
,我想创建一个新的张量,它的形状是2维的,它的random\u row
是全零,所有其他行都是一,例如
random_row=[1,3]#random_row本身就是一个张量
#新的_张量需要是另一个张量,其随机_行中的行都是零
#我们已经知道新的张量的形状是(4,2)
新的_张量=[[1,1],[0,0],[1,1],[0,0]]
我怎样才能做到这一点?如果有人能帮忙,我真的很感激 您可以使用类似于his的函数来实现这一点:
import tensorflow as tf
def zero_rows(x, idx)
# Turn row indices into a boolean mask
n = tf.shape(x)[0]
m = tf.scatter_nd(tf.expand_dims(idx, 1), tf.ones_like(idx, dtype=tf.bool), [n])
# Select zeros where the indices are or the data elsewhere
return tf.where(m, tf.zeros_like(x), x)
# Test
with tf.Graph().as_default(), tf.Session() as sess:
y = zero_rows(x, idx)
print(sess.run(y, feed_dict={x: [[1, 2], [3, 4], [5, 6], [7, 8]], idx: [1, 3]}))
# [[1 2]
# [0 0]
# [5 6]
# [0 0]]
您可以使用类似于his的功能:
import tensorflow as tf
def zero_rows(x, idx)
# Turn row indices into a boolean mask
n = tf.shape(x)[0]
m = tf.scatter_nd(tf.expand_dims(idx, 1), tf.ones_like(idx, dtype=tf.bool), [n])
# Select zeros where the indices are or the data elsewhere
return tf.where(m, tf.zeros_like(x), x)
# Test
with tf.Graph().as_default(), tf.Session() as sess:
y = zero_rows(x, idx)
print(sess.run(y, feed_dict={x: [[1, 2], [3, 4], [5, 6], [7, 8]], idx: [1, 3]}))
# [[1 2]
# [0 0]
# [5 6]
# [0 0]]