我需要计算Tensorflow中张量的密度(稀疏度)。 我在https://www.tensorflow.org/versions/r0.9/how_tos/summaries_and_tensorboard/index.html中使用了MNIST Neural Net Tensorbench示例。
我已将此代码段插入到示例代码(https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py)中,以计算张量中的稀疏性(在我的情况下,我只会满足于0的数量)。
在此示例中,有两个张量:hidden1
为784 x 500
,y
为500 x 10
。
def tf_count(t):
elements_equal_to_value = tf.equal(t, 0)
count = tf.reduce_sum(tf.cast(elements_equal_to_value, tf.int32))
return count
然后我在运行期间使用以下语句将其打印出来
print ('Sparsity of hidden1: ', tf_count(hidden1))
print ('Sparsity of y: ', tf_count(y))
我得到以下
Sparsity of hidden1: Tensor("Sum:0", shape=(), dtype=int32)
Sparsity of y: Tensor("Sum_1:0", shape=(), dtype=int32)
随着神经网络的迭代次数逐渐增加:
Sparsity of hidden1: Tensor("Sum_18:0", shape=(), dtype=int32)
Sparsity of y: Tensor("Sum_19:0", shape=(), dtype=int32)
如何在每个张量中得到0的标量计数?
答案 0 :(得分:2)
最初想要答案的人可能会迟到,但衡量张量流中稀疏度的简单方法是tf.nn.zero_fraction,例如:
tf.summary.scalar(tensor_name + '/sparsity', tf.nn.zero_fraction(x))
答案 1 :(得分:1)
当您使用tensorflow
(tf
)包中的ops时,您将在计算图中定义必须放在设备上并执行到会话中的操作。
因此,每次调用python函数tf_count
时,您都会在计算图中定义一个新操作:这就是操作名称旁边的数字增加的原因。
如果你想要一个python值,你必须执行操作并获取结果。
所以:
#first define your operation:
def tf_count(t):
elements_equal_to_value = tf.equal(t, 0)
count = tf.reduce_sum(tf.cast(elements_equal_to_value, tf.int32))
return count
# then define your model (your input placeholders, the model architecture ecc...)
#
# than start a Session and run the operation into the graph
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
sparsity_of_h1 = sess.run(tf_count(hidden1))
print ('Sparsity of hidden1: ', sparsity_of_h1)