首页 > 解决方案 > 如何使用 tf.range 创建 complex128 张量

问题描述

以下几行有效:

t1 = tf.constant([-2.0, -1.0, 0, 1.0, 2.0], dtype=tf.complex128)
tf.sqrt(t1)
print(t1)

现在如果我使用

t1 = tf.range(-2.0, 3.0, 1, dtype=tf.complex128)
tf.sqrt(t1)
print(t1)

我得到通常的错误:

Node:{{node Range}} 为 op Range 注册的所有内核:
device='CPU'; [DT_FLOAT] 设备中的 Tidx='CPU'; [DT_DOUBLE]
设备中的 Tidx='CPU'; [DT_INT32] 中的 Tidx 设备='CPU'; [DT_INT64] 中的 Tidx
设备='GPU'; [DT_FLOAT] 中的 Tidx 设备='GPU'; [DT_DOUBLE]
设备中的 Tidx='GPU'; [DT_INT32] 中的 Tidx 设备='GPU'; [DT_INT64]
设备中的 Tidx='XLA_CPU_JIT'; Tidx 在 [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF] device='XLA_GPU_JIT'; Tidx 在 [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]
device='XLA_CPU'; Tidx in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF] device='XLA_GPU'; Tidx 在 [DT_FLOAT, DT_DOUBLE, DT_INT32,

我究竟做错了什么?

标签: tensorflow

解决方案


根据这个错误,它的输入tf.range应该是double, float,int注册为op Range on device: CPU and GPU. 但是您的输入是complex128,因此它返回NotFoundError

如果我们没有指定任何dtype(即 dtype 为 None),则它是dtypedtype_hierarchy: dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64as per推断出来的arg.dtype

在以下帮助下创建complex128张量的解决方法tf.range如下tf.cast

t1 = tf.range(-2.0, 3.0, 1)
# casts tensor to a complex128 dtype.
t2 = tf.cast(t1, dtype=tf.complex128)
# apply sqrt function
tf.sqrt(t2)
# print output
print(t1)
print(t2)

输出:

tf.Tensor([-2. -1.  0.  1.  2.], shape=(5,), dtype=float32)
tf.Tensor([-2.+0.j -1.+0.j  0.+0.j  1.+0.j  2.+0.j], shape=(5,), dtype=complex128)

推荐阅读