Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建随机索引为零的张量_Python_Tensorflow - Fatal编程技术网

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]]