如何在 TensorFlow 中获取张量中元素的计数?
How to get the count of an element in a tensor in TensorFlow?
我想获取张量中某个元素的个数,例如t = [1, 2, 0, 0, 0, 0]
(t
是一个张量)。我可以通过在 Python 中调用 t.count(0)
来获得数量为 4 的零,但是在 TensorFlow 中,我找不到任何函数来执行此操作。我怎样才能得到零的数量?
目前 TensorFlow 中没有内置的计数方法。但是您可以使用现有工具以如下方法完成此操作:
def tf_count(t, val):
elements_equal_to_value = tf.equal(t, val)
as_ints = tf.cast(elements_equal_to_value, tf.int32)
count = tf.reduce_sum(as_ints)
return count
对上面 Slater 的回答的补充。如果要获取 all 个元素的计数,可以使用 one_hot
和 reduce_sum
来避免 python 中的任何循环。例如,下面的代码片段 returns 一个词汇,按 word_tensor.
中出现的次数排序
def build_vocab(word_tensor, vocab_size):
unique, idx = tf.unique(word_tensor)
counts_one_hot = tf.one_hot(
idx,
tf.shape(unique)[0],
dtype=tf.int32
)
counts = tf.reduce_sum(counts_one_hot, 0)
_, indices = tf.nn.top_k(counts, k=vocab_size)
return tf.gather(unique, indices)
编辑:经过一些实验,我发现 one_hot
张量很容易爆炸超过 TF 的最大张量大小。用这样的东西替换 counts
调用可能更有效(如果不那么优雅的话):
counts = tf.foldl(
lambda counts, item: counts + tf.one_hot(
item, tf.shape(unique)[0], dtype=tf.int32),
idx,
initializer=tf.zeros_like(unique, dtype=tf.int32),
back_prop=False
)
要仅计算一个特定元素,您可以创建一个布尔掩码,将其转换为 int
并求和:
import tensorflow as tf
X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
res = tf.reduce_sum(tf.cast(tf.equal(X, 3), tf.int32))
with tf.Session() as sess:
print sess.run(res)
您还可以使用 tf.unique_with_counts;
计算 list/tensor 中的每个元素
import tensorflow as tf
X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
y, idx, cnts = tf.unique_with_counts(X)
with tf.Session() as sess:
a, _, b = sess.run([y, idx, cnts])
print a
print b
我想获取张量中某个元素的个数,例如t = [1, 2, 0, 0, 0, 0]
(t
是一个张量)。我可以通过在 Python 中调用 t.count(0)
来获得数量为 4 的零,但是在 TensorFlow 中,我找不到任何函数来执行此操作。我怎样才能得到零的数量?
目前 TensorFlow 中没有内置的计数方法。但是您可以使用现有工具以如下方法完成此操作:
def tf_count(t, val):
elements_equal_to_value = tf.equal(t, val)
as_ints = tf.cast(elements_equal_to_value, tf.int32)
count = tf.reduce_sum(as_ints)
return count
对上面 Slater 的回答的补充。如果要获取 all 个元素的计数,可以使用 one_hot
和 reduce_sum
来避免 python 中的任何循环。例如,下面的代码片段 returns 一个词汇,按 word_tensor.
def build_vocab(word_tensor, vocab_size):
unique, idx = tf.unique(word_tensor)
counts_one_hot = tf.one_hot(
idx,
tf.shape(unique)[0],
dtype=tf.int32
)
counts = tf.reduce_sum(counts_one_hot, 0)
_, indices = tf.nn.top_k(counts, k=vocab_size)
return tf.gather(unique, indices)
编辑:经过一些实验,我发现 one_hot
张量很容易爆炸超过 TF 的最大张量大小。用这样的东西替换 counts
调用可能更有效(如果不那么优雅的话):
counts = tf.foldl(
lambda counts, item: counts + tf.one_hot(
item, tf.shape(unique)[0], dtype=tf.int32),
idx,
initializer=tf.zeros_like(unique, dtype=tf.int32),
back_prop=False
)
要仅计算一个特定元素,您可以创建一个布尔掩码,将其转换为 int
并求和:
import tensorflow as tf
X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
res = tf.reduce_sum(tf.cast(tf.equal(X, 3), tf.int32))
with tf.Session() as sess:
print sess.run(res)
您还可以使用 tf.unique_with_counts;
计算 list/tensor 中的每个元素import tensorflow as tf
X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
y, idx, cnts = tf.unique_with_counts(X)
with tf.Session() as sess:
a, _, b = sess.run([y, idx, cnts])
print a
print b