[英]Translating numpy operations to tensorflow
I am looking to translate numpy operations to tensorflow.我希望将 numpy 操作转换为 tensorflow。
A function given a 2D ndarray, I want to make all entries that are not the maximum along axis 0 update to the value of 0.一个给定 2D ndarray 的函数,我想让所有不是沿轴 0 的最大值的条目更新为 0 的值。
def rows_to_zero(arr: np.ndarray):
def row_to_zero(row: np.ndarray):
row[row < row.max()] = 0
return row
return np.apply_along_axis(row_to_zero, 0, arr)
In: [[1, 2, 1, 4, 5, 3],
[2, 4, 5, 0, 1, 3],
[3, 5, 3, 6, 7, 1]]
Out: [[0, 0, 0, 0, 5, 0],
[0, 0, 5, 0, 0, 0],
[0, 0, 0, 0, 7, 0]]
I want to write this same functionality using Tensorflow tensors我想使用 Tensorflow 张量编写相同的功能
Would anyone be able to help with something like this?任何人都可以帮助解决这样的问题吗?
You just need tf.reduce_max
and tf.where
.你只需要
tf.reduce_max
和tf.where
。
import tensorflow as tf
a = tf.constant([[1, 2, 1, 4, 5, 3],
[2, 4, 5, 0, 1, 3],
[3, 5, 3, 6, 7, 1]],tf.float32)
b = tf.reduce_max(a,axis=1,keepdims=True)
result = tf.where(tf.less(a,b),tf.zeros_like(a),a)
with tf.Session() as sess:
print(sess.run(result))
# [[0. 0. 0. 0. 5. 0.]
# [0. 0. 5. 0. 0. 0.]
# [0. 0. 0. 0. 7. 0.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.