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

【TensorFlow2.0】(1) tensor数据类型,类型转换_tensorflow tensor转int-CSDN博客文章浏览阅读1.5w次,点赞8次,收藏28次。各位同学好,今天和大家分享一下TensorFlow2.0中的tensor数据类型,以及各种类型之间的相互转换方法。1. tf.tensor 基础操作scaler标量:1.2vector向量:[1.2]、[1.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)
相关推荐
唐某人丶11 分钟前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
FIT2CLOUD飞致云29 分钟前
九月月报丨MaxKB在不同规模医疗机构的应用进展汇报
人工智能·开源
阿里云大数据AI技术31 分钟前
【新模型速递】PAI-Model Gallery云上一键部署Qwen3-Next系列模型
人工智能
袁庭新1 小时前
全球首位AI机器人部长,背负反腐重任
人工智能·aigc
机器之心1 小时前
谁说Scaling Law到头了?新研究:每一步的微小提升会带来指数级增长
人工智能·openai
算家计算1 小时前
AI配音革命!B站最新开源IndexTTS2本地部署教程:精准对口型,情感随心换
人工智能·开源·aigc
量子位1 小时前
马斯克周末血裁xAI 500人
人工智能·ai编程
算家计算2 小时前
OpenAI最强编程模型GPT-5-Codex发布!可独立编程7小时,编程效率提升10倍
人工智能·ai编程·资讯
聚客AI3 小时前
🌟大模型为什么产生幻觉?预训练到推理的漏洞全揭秘
人工智能·llm·掘金·日新计划
Juchecar3 小时前
一文讲清 nn.Sequential 等容器类
人工智能