tf.cast()类型转换

本文介绍了TensorFlow中的tf.cast()函数,用于在张量数据类型转换。当需要将例如int8类型的图像数据转换为float32进行训练时,此函数变得至关重要。它能将ndarray转换为tf.Tensor,确保数据可以参与计算图和自动求导等操作。在确保精度的同时,float32类型通常提供更快的计算速度。
摘要由CSDN通过智能技术生成

tf.cast()类型转换
https://www.tensorflow.org/api_docs/python/tf/cast?version=nightly
tf.cast()函数的作用是执行 tensorflow 中张量数据类型转换,比如读入的图片如果是int8类型的,一般在要在训练前把图像的数据格式转换为float32。

import tensorflow as tf
import numpy as np

(x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], -1)
x_test = x_test.reshape(x_test.shape[0], -1)

x_train = tf.cast(x_train, tf.float32) / np.max(x_train)
x_test = tf.cast(x_test, tf.float32) / np.max(x_train)
x_train.shape, x_test.shape
(TensorShape([60000, 784]), TensorShape(</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值