TensorFlow中张量数据类型转换操作tf.cast/tf.dtypes.cast用法

本文介绍如何使用TensorFlow的tf.cast或tf.dtypes.cast函数进行数据类型转换,适用于多种数据类型,包括张量、稀疏张量和索引切片等。通过示例展示将浮点数张量转换为整数张量的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、环境

TensorFlow API r1.12

CUDA 9.2 V9.2.148

cudnn64_7.dll

Python 3.6.3

Windows 10

二、官方说明

tf.cast 或 tf.dtypes.cast

将输入张量转换数据类型

https://www.tensorflow.org/api_docs/python/tf/dtypes/cast

tf.dtypes.cast(
    x,
    dtype,
    name=None
)

输入:

(1)x:可以是张量(Tensor)、稀疏张量(SparseTensor)或数值类型的索引切片(IndexedSlices),如:uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64, complex64, complex128, bfloat16.

(2)dtype:要转换的目标数据类型,支持的数据类型种类同上面的x

(3)name:可选参数,操作的名称

三、示例

>>> x = tf.constant([1.8,2.2])
>>> x1 = tf.cast(x,tf.int32)
>>> with tf.Session() as sess:
...     print(sess.run(x1))
...
[1 2]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值