如何使用 TensorFlow 中的 num_elements?

How to use num_elements from TensorFlow?

我只想要张量中元素的数量,而不考虑形状。

我在文档中看到 num_elements 符合我的目的。但是,如果我尝试将其用作 myTensor.num_elements(),则会出现此错误:

AttributeError: 'Tensor' object has no attribute 'num_elements'

我该怎么做?

此方法属于 TensorShape 而不是 Tensor。可以这样获取元素个数

import tensorflow as tf
a = tf.random.uniform((1,16,23))
a.shape.num_elements()
# 368