Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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/2/tensorflow/5.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,假设我有一个名为x的张量,其形状为[1,批量大小]。如果x中的相关值小于或等于零,我想将另一个名为my\u tensor的张量的行更改为[batch\u size,seq\u length] 我想我可以通过表示代码来更好地解释: import tensorflow as tf batch_size = 3 seq_length = 5 x = tf.constant([-1, 4, 0]) # size is [1, batch_size] # select the indices of

假设我有一个名为
x
的张量,其形状为
[1,批量大小]
。如果
x
中的相关值小于或等于零,我想将另一个名为
my\u tensor
的张量的行更改为
[batch\u size,seq\u length]

我想我可以通过表示代码来更好地解释:

import tensorflow as tf

batch_size = 3
seq_length = 5

x = tf.constant([-1, 4, 0]) # size is [1, batch_size]

# select the indices of the rows to be changed
candidate_rows = tf.where(tf.less_equal(x, 0))

my_tensor = tf.random.uniform(shape=(batch_size, seq_length), minval=10, maxval=30, seed=123)

sess = tf.InteractiveSession()
print(sess.run(candidate_rows))
print(sess.run(my_tensor))
这将产生:

candidate_rows = 
 [[0]
  [2]]

my_tensor = 
 [[10.816193 14.168425 11.83606  24.044014 24.146267]
 [17.929298 11.330187 15.837727 10.592653 29.098463]
 [10.122135 16.338099 24.35467  15.236387 10.991222]]
我想把张量中的[0]行和[2]行换成另一个值,都等于1

 [[1 1 1 1]
 [17.929298 11.330187 15.837727 10.592653 29.098463]
 [1 1 1 1 1]]

当我使用
tf.where
时,可能所有的问题都会出现。非常感谢您的帮助:)

解决您问题的一个方法是使用
tf.where
在两个张量的元素之间进行选择

t = tf.ones(shape=my_tensor.shape, dtype=my_tensor.dtype)
my_tensor = tf.where(x > 0, my_tensor, t)