Tensorflow2.0笔记 - 基本数据类型,数据类型转换

【TensorFlow2.0】(1) tensor数据类型,类型转换_tensorflow tensor转int-CSDN博客文章浏览阅读1.5w次,点赞8次,收藏28次。各位同学好,今天和大家分享一下TensorFlow2.0中的tensor数据类型,以及各种类型之间的相互转换方法。1. tf.tensor 基础操作scaler标量:1.2vector向量:1.21.1,2.2,3.3 注意:此处的1.2是一维的,而1.2是0维的matrix矩阵:\[1.1,2.2,3.3,4.4]tensor张量:代表任意维度的数据1.1 创建一个tensor创建方法: tf.constant(value, shape=维度, d..._tensorflow tensor转inthttps://blog.csdn.net/dgvv4/article/details/121478256

关于tensorflow的数据类型的文章,网上有很多。本笔记只记录代码。

复制代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

tf.__version__

#constant
a = tf.constant([1.5])
b = tf.constant([True, False])
c = tf.constant('Hello TensorFlow')
d = np.arange(4)

#检查是否是tensor类型
print(tf.is_tensor(a))
print(tf.is_tensor(b))
print(tf.is_tensor(c))
print(tf.is_tensor(d))

#返回数据类型
print(a.dtype)
print(b.dtype)
print(c.dtype)
print(d.dtype)

print(a.dtype == tf.float32)
print(b.dtype == tf.bool)
print(c.dtype == tf.string)

#数据类型转换
a = np.arange(5)
print(a)
#将numpy数组转换为tensor
tensor_a = tf.convert_to_tensor(a)
print(tensor_a)
tensor_a_int64 = tf.convert_to_tensor(a, dtype=tf.int64)
print(tensor_a_int64)
tensor_a_cast_float32 = tf.cast(tensor_a, dtype=tf.float32)
print(tensor_a_cast_float32)
#整型转换为bool
b = tf.constant([1,0,1,0])
b = tf.cast(b, dtype=tf.bool)
print(b)

#TensorFlow变量Variable, Variable的trainable属性为Ture,表示可以进行求导更新
a = tf.range(5)
b = tf.Variable(a)
print(b)
print(tf.is_tensor(b))
print(b.trainable)

#Tensor转回numpy
a = tf.range(4)
print(a)
a_numpy = a.numpy()
print(a_numpy)
相关推荐
miaowu3571 分钟前
企业 AI 智能体实施周期短吗?各阶段费用明细
人工智能
Xiaok10184 分钟前
NumPy 数组 vs PyTorch Tensor
人工智能·pytorch·numpy
卡梅德生物科技小能手13 分钟前
卡梅德生物科普 TSLP
经验分享·深度学习·生活
一只小菜鸡..16 分钟前
南京大学 操作系统 (JYY) 学习笔记:CPU 的局限、GPU 与 AI 时代的算力革命
人工智能·笔记·学习
AI创界者30 分钟前
开源硬核LTX-Video 本地部署整合包教程:超低显存生成高清AI视频,告别云端排队!
人工智能·aigc·音视频
Bruce_Liuxiaowei39 分钟前
当AI以可验证的方式攻克数学难题——它如何重写了“科研“的成本与门槛
人工智能·智能体
deepseek2344 分钟前
MiniMax H3 全模态模型拆解:2K 视频成本被腰斩背后,H3-VAE 和 In-context Regeneration 做了什么
人工智能·多模态·视频生成
智道天成1 小时前
杭州智道天成信息科技有限公司:助力浙江企业合规高效落地
大数据·人工智能·科技
董员外1 小时前
RAG 系统进化论(五):Corrective RAG 与 Self-RAG,让系统发现并纠正错误
人工智能·后端·设计模式
MistyStar1 小时前
Fast 模式为什么更快也更贵:从 Prefill/Decode 到 Batch 经济学
人工智能