擅长:python、mysql、java
<p>Rafal的答案几乎可以肯定是计算张量中<code>true</code>元素数量的最简单方法,但问题的另一部分是:</p>
<blockquote>
<p>[H]ow can I access a dimension and use it in an operation like a sum?</p>
</blockquote>
<p>为此,可以使用TensorFlow的<a href="https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#shapes_and_shaping" rel="noreferrer">shape-related operations</a>,它作用于tensor的运行时值。例如,<a href="https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#size" rel="noreferrer">^{<cd2>}</a>生成标量<code>Tensor</code>,包含<code>t</code>中的元素数,<a href="https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#shape" rel="noreferrer">^{<cd5>}</a>生成一维<code>Tensor</code>,包含每个维度中<code>t</code>的大小。</p>
<p>使用这些运算符,您的程序也可以编写为:</p>
<pre><code>myOtherTensor = tf.constant([[True, True], [False, True]])
myTensor = tf.where(myOtherTensor)
countTrue = tf.shape(myTensor)[0] # Size of `myTensor` in the 0th dimension.
sess = tf.Session()
sum = sess.run(countTrue)
</code></pre>