Python 除动态矩形外,张量处处等于零
给定Python 除动态矩形外,张量处处等于零,python,tensorflow,Python,Tensorflow,给定a,b,c,d4个类型为tf.int和形状[1]的张量,获得张量X的最简单方法是什么: X具有形状[h,w] X除行a
a,b,c,d
4个类型为tf.int
和形状[1]
的张量,获得张量X
的最简单方法是什么:
具有形状X
[h,w]
除行X
和列a
之间等于c
外,其余位置均为1
0
X
例如:
import tensorflow as tf
h = 5
w = 6
a = 1
b = 3
c = 2
d = 4
cols, rows = tf.meshgrid(tf.range(w), tf.range(h))
mask_rows = tf.logical_and( tf.less(rows, b), tf.greater_equal(rows, a))
mask_cols = tf.logical_and( tf.less(cols, d), tf.greater_equal(cols, c))
mask = tf.logical_and(mask_rows, mask_cols)
X = tf.where(mask, tf.ones([h,w], tf.float32), tf.zeros([h,w], tf.float32))
验证输出:
sess = tf.Session()
print(sess.run(cols))
print(sess.run(rows))
print(sess.run(X))
cols的输出
:
[[0 1 2 3 4 5]
[0 1 2 3 4 5]
[0 1 2 3 4 5]
[0 1 2 3 4 5]
[0 1 2 3 4 5]]
行的输出
[[0 0 0 0 0 0]
[1 1 1 1 1 1]
[2 2 2 2 2 2]
[3 3 3 3 3 3]
[4 4 4 4 4 4]]
X的输出
[[0. 0. 0. 0. 0. 0.]
[0. 0. 1. 1. 0. 0.]
[0. 0. 1. 1. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
使用tf.py\u func
有一种解决方案不是那么优雅。我对更像tensorflow的解决方案耳熟能详。