将 unsigned int 的张量与 python int 进行比较

Compare tensor of unsigned int to python int

我想比较 unsigned int 的 TensorFlow 张量,例如tf.uint32 到 python 整数 1。我怎么做?以下全部失败

ones = tf.ones((2, 3), dtype=tf.uint32)
ones == 1
ones == [[1, 1, 1], [1, 1, 1]]
ones == tf.constant(1, dtype=tf.uint32)
ones == tf.ones((2, 3), dtype=tf.uint32)  # ?!!! I'm surprised this doesn't work
ones == tf.constant([[1, 1, 1], [1, 1, 1]], dtype=tf.uint32)

含糊不清

tensorflow.python.framework.errors_impl.NotFoundError: Could not find valid device for node.
Node:{{node Equal}}
All kernels registered for op Equal :
  device='XLA_GPU'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_QUINT8, DT_QINT32, DT_BFLOAT16, DT_COMPLEX128, DT_HALF]
  device='XLA_CPU_JIT'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_QUINT8, DT_QINT32, DT_BFLOAT16, DT_COMPLEX128, DT_HALF]
  device='XLA_GPU_JIT'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_QUINT8, DT_QINT32, DT_BFLOAT16, DT_COMPLEX128, DT_HALF]
  device='GPU'; T in [DT_BOOL]
  device='GPU'; T in [DT_COMPLEX128]
  device='GPU'; T in [DT_COMPLEX64]
  device='GPU'; T in [DT_INT64]
  device='GPU'; T in [DT_INT16]
  device='GPU'; T in [DT_INT8]
  device='GPU'; T in [DT_INT32]
  device='GPU'; T in [DT_UINT8]
  device='GPU'; T in [DT_DOUBLE]
  device='GPU'; T in [DT_HALF]
  device='GPU'; T in [DT_FLOAT]
  device='CPU'; T in [DT_BOOL]
  device='CPU'; T in [DT_STRING]
  device='CPU'; T in [DT_COMPLEX128]
  device='CPU'; T in [DT_COMPLEX64]
  device='CPU'; T in [DT_INT64]
  device='CPU'; T in [DT_INT32]
  device='CPU'; T in [DT_BFLOAT16]
  device='CPU'; T in [DT_INT16]
  device='CPU'; T in [DT_INT8]
  device='CPU'; T in [DT_UINT8]
  device='CPU'; T in [DT_DOUBLE]
  device='CPU'; T in [DT_HALF]
  device='CPU'; T in [DT_FLOAT]
  device='XLA_CPU'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, ..., DT_QUINT8, DT_QINT32, DT_BFLOAT16, DT_COMPLEX128, DT_HALF]
 [Op:Equal]

使用 tf.int32 时效果很好

>>> tf.ones((2, 3), dtype=tf.int32) == 1
<tf.Tensor: shape=(2, 3), dtype=bool, numpy=
array([[ True,  True,  True],
       [ True,  True,  True]])>

可以和uint8比较。例如,以下片段给出了正确的输出:

ones = tf.ones((2, 3), dtype=tf.uint8)
ones == 1
<tf.Tensor: shape=(2, 3), dtype=bool, numpy=
array([[ True,  True,  True],
       [ True,  True,  True]])>

您还可以转换为任何不受支持的数据类型。

ones = tf.ones((2, 3), dtype = tf.uint32)
ones_c = tf.cast(ones, dtype = tf.int32)
ones_c == 1
<tf.Tensor: shape=(2, 3), dtype=bool, numpy=
array([[ True,  True,  True],
       [ True,  True,  True]])>

因为它看起来像一个错误,这里有一个关于行为(跟踪)的 GitHub 问题:

https://github.com/tensorflow/tensorflow/issues/39457

更新:现在,您可以使用tf-nightly来比较uint16uint32

https://pypi.org/project/tf-nightly-gpu/