问题
I am searching for a way using Tensorflow to extract all of the sub-elements except for the one corresponding to the tensor's index.
(eg. if looking at index 1 then only sub-elements 0 and 2 are present)
Very similar to this approach using Numpy.
Here's some example code to create a tiled tensor and a boolean mask:
import tensorflow as tf
import numpy as np
_coordinates = np.array([
[1.0, 7.0, 0.0],
[2.0, 7.0, 0.0],
[3.0, 7.0, 0.0],
])
verts_coord = _coordinates
n = verts_coord.shape[0]
mat_loc = tf.Variable(verts_coord)
tile = tf.tile(mat_loc, [n, 1])
tile = tf.reshape(tile, [n, n, n])
mask = tf.constant(~np.eye(n, dtype=bool))
result = tf.somefunc(tile, mask) #somehow extract only the elements where mask == true
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(sess.run(tile))
print(sess.run(mask))
Example output tensors:
>>> print(tile)
[[[ 1. 7. 0.]
[ 2. 7. 0.]
[ 3. 7. 0.]]
[[ 1. 7. 0.]
[ 2. 7. 0.]
[ 3. 7. 0.]]
[[ 1. 7. 0.]
[ 2. 7. 0.]
[ 3. 7. 0.]]]
>>> print(mask)
[[False True True]
[ True False True]
[ True True False]]
Desired output:
>>> print(result)
[[[ 2. 7. 0.]
[ 3. 7. 0.]]
[[ 1. 7. 0.]
[ 3. 7. 0.]]
[[ 1. 7. 0.]
[ 2. 7. 0.]]]
I am also curious if there are more efficient methods for doing this as opposed to creating a large tensor and then masking it?
Thanks!
回答1:
Turns out Tensorflow had exactly what I was looking for already built in :)
result = tf.boolean_mask(tile, mask)
result = tf.reshape(result, [n, n-1, -1])
>>> print(result)
[[[ 2. 7. 0.]
[ 3. 7. 0.]]
[[ 1. 7. 0.]
[ 3. 7. 0.]]
[[ 1. 7. 0.]
[ 2. 7. 0.]]]
来源:https://stackoverflow.com/questions/41849559/removing-or-masking-the-ith-sub-element-of-a-tilted-tensor