当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python tf.bitcast用法及代码示例


在不复制数据的情况下,将张量从一种类型转换为另一种类型。

用法

tf.bitcast(
    input, type, name=None
)

参数

  • input 一个Tensor。必须是以下类型之一:bfloat16 , half , float32 , float64 , int64 , int32 , uint8 , uint16 , uint32 , uint64 , int8 , int16 , complex64 , complex128 , qint8 , quint8 , qint16 , quint16 , qint32
  • type A tf.dtypes.DType从:tf.bfloat16, tf.half, tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.uint32, tf.uint64, tf.int8, tf.int16, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint16, tf.quint16, tf.qint32.
  • name 操作的名称(可选)。

返回

  • Tensor 类型为 type

给定一个张量 input ,此操作返回一个与 input 具有相同缓冲区数据且数据类型为 type 的张量。

如果输入数据类型 T 大于输出数据类型 type,则形状从 [...] 更改为 [..., sizeof( T )/sizeof( type )]。

如果 T 小于 type ,则运算符要求最右边的维度等于 sizeof( type )/sizeof( T )。然后形状从 [..., sizeof( type )/sizeof( T )] 变为 [...]。

tf.bitcast() 和 tf.cast() 在将实际 dtype 转换为复杂 dtype(例如 tf.complex64 或 tf.complex128)时的工作方式不同,因为 tf.cast() 将虚部设为 0 而 tf.bitcast() 给出模块错误。例如,

示例 1:

a = [1., 2., 3.]
equality_bitcast = tf.bitcast(a, tf.complex128)
Traceback (most recent call last):

InvalidArgumentError:Cannot bitcast from 1 to 18 [Op:Bitcast]
equality_cast = tf.cast(a, tf.complex128)
print(equality_cast)
tf.Tensor([1.+0.j 2.+0.j 3.+0.j], shape=(3,), dtype=complex128)

示例 2:

tf.bitcast(tf.constant(0xffffffff, dtype=tf.uint32), tf.uint8)
<tf.Tensor:shape=(4,), dtype=uint8, numpy=array([255, 255, 255, 255], dtype=uint8)>

示例 3:

x = [1., 2., 3.]
y = [0., 2., 3.]
equality= tf.equal(x,y)
equality_cast = tf.cast(equality,tf.float32)
equality_bitcast = tf.bitcast(equality_cast,tf.uint8)
print(equality)
tf.Tensor([False True True], shape=(3,), dtype=bool)
print(equality_cast)
tf.Tensor([0. 1. 1.], shape=(3,), dtype=float32)
print(equality_bitcast)
tf.Tensor(
    [[  0   0   0   0]
     [  0   0 128  63]
     [  0   0 128  63]], shape=(3, 4), dtype=uint8)

注意:Bitcast 被实现为低级强制转换,因此具有不同 endian 顺序的机器将给出不同的结果。

相关用法


注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.bitcast。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。