Rob*_*oby 4 python numpy tensorflow
我有以下操作使用numpy.where:
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
index = np.array([[1,0,0],[0,1,0],[0,0,1]])
mat[np.where(index>0)] = 100
print(mat)
Run Code Online (Sandbox Code Playgroud)
如何在 TensorFlow 中实现等价物?
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
index = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
tf_mat = tf.constant(mat)
tf_index = tf.constant(index)
indi = tf.where(tf_index>0)
tf_mat[indi] = -1 <===== not allowed
Run Code Online (Sandbox Code Playgroud)
假设您想要的是创建一个带有一些替换元素的新张量,而不是更新变量,您可以执行以下操作:
import numpy as np
import tensorflow as tf
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32)
index = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
tf_mat = tf.constant(mat)
tf_index = tf.constant(index)
tf_mat = tf.where(tf_index > 0, -tf.ones_like(tf_mat), tf_mat)
with tf.Session() as sess:
print(sess.run(tf_mat))
Run Code Online (Sandbox Code Playgroud)
输出:
[[-1 2 3]
[ 4 -1 6]
[ 7 8 -1]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4486 次 |
| 最近记录: |