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)
相关推荐
吃着火锅x唱着歌10 分钟前
Effective C++ 学习笔记 条款43 学习处理模板化基类内的名称
c++·笔记·学习
AI_小站12 分钟前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain
随风而飘18615 分钟前
KEITHLEY吉时利 2400 数字源表
人工智能·功能测试·科技·测试工具
HyperAI超神经23 分钟前
【Triton 教程】triton_language.fdiv
人工智能·深度学习·triton
心无旁骛~27 分钟前
anywhere-labs/deepseek-harness-desktop 如何围绕上游演进:Submodule、版本溯源与非 Fork 架构
人工智能·架构
xiaohaiAIgeo33 分钟前
【2026年】医药研发实验室GLP的通风设计要求:稳定性可验证性与合规性
网络·人工智能·科普知识
ZGIAI35 分钟前
ZGI Runner 与 Sandbox:两层运行边界
人工智能·架构
ZGIAI42 分钟前
ZGI Workspace:统一组织 Agent 资源
人工智能·架构
芯小途202643 分钟前
微短剧新规 9 月 1 日施行:AIGC 微短剧的「AI 标识 + 占比追溯」怎么在制作流水线里落地(附自查脚本)
人工智能·aigc
诺伦1 小时前
AI Agent 架构实战:从零拆解多Agent协作营销系统的设计与实现
人工智能·架构