从 TensorFlow 中的矩阵中删除零向量 [英] Remove zero vectors from a matrix in TensorFlow
问题描述
正如问题所说,我正在尝试从张量中删除所有零向量(即 [0, 0, 0, 0]
).
给定:
array([[ 0. , 0. , 0. , 0. ],[ 0.19999981, 0.5 , 0. , 0. ],[ 0.4000001 , 0.29999995, 0.10000002, 0. ],...,[-0.5999999 , 0. , -0.0999999 , -0.20000005],[-0.29999971, -0.4000001, -0.30000019, -0.5 ],[ 0. , 0. , 0. , 0. ]], dtype=float32)
我尝试了以下代码(灵感来自 this SO):
x = tf.placeholder(tf.float32, shape=(10000, 4))zeros_vector = tf.zeros(shape=(1, 4), dtype=tf.float32)bool_mask = tf.not_equal(x, zero_vector)omit_zeros = tf.boolean_mask(x, bool_mask)
但是 bool_mask
似乎也是 (10000, 4) 的形状,就像它将 x
张量中的每个元素都比较为零,而不是行.>
我想过使用 tf.reduce_sum
,其中整行为零,但这也会省略像 [1, -1, 0, 0]
和我这样的行不想那样.
想法?
一种可能的方法是对行的绝对值求和,这样就不会像 [1, -1,0, 0]
然后将其与零向量进行比较.你可以这样做:
intermediate_tensor = reduce_sum(tf.abs(x), 1)zero_vector = tf.zeros(shape=(1,1), dtype=tf.float32)bool_mask = tf.not_equal(intermediate_tensor, zero_vector)omit_zeros = tf.boolean_mask(x, bool_mask)
Just like the question says, I'm trying to remove all zeros vectors (i.e [0, 0, 0, 0]
) from a tensor.
Given:
array([[ 0. , 0. , 0. , 0. ],
[ 0.19999981, 0.5 , 0. , 0. ],
[ 0.4000001 , 0.29999995, 0.10000002, 0. ],
...,
[-0.5999999 , 0. , -0.0999999 , -0.20000005],
[-0.29999971, -0.4000001 , -0.30000019, -0.5 ],
[ 0. , 0. , 0. , 0. ]], dtype=float32)
I had tried the following code (inspired by this SO):
x = tf.placeholder(tf.float32, shape=(10000, 4))
zeros_vector = tf.zeros(shape=(1, 4), dtype=tf.float32)
bool_mask = tf.not_equal(x, zero_vector)
omit_zeros = tf.boolean_mask(x, bool_mask)
But bool_mask
seem also to be of shape (10000, 4), like it was comparing every element in the x
tensor to zero, and not rows.
I thought about using tf.reduce_sum
where an entire row is zero, but that will omit also rows like [1, -1, 0, 0]
and I don't want that.
Ideas?
One possible way would be to sum over the absolute values of the row, in this way it will not omit rows like [1, -1, 0, 0]
and then compare it with a zero vector. You can do something like this:
intermediate_tensor = reduce_sum(tf.abs(x), 1)
zero_vector = tf.zeros(shape=(1,1), dtype=tf.float32)
bool_mask = tf.not_equal(intermediate_tensor, zero_vector)
omit_zeros = tf.boolean_mask(x, bool_mask)
这篇关于从 TensorFlow 中的矩阵中删除零向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!