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)
相关推荐
PNP Robotics3 分钟前
聚焦具身智能,PNP机器人展出力反馈遥操作,VR动作捕捉等方案,获得中国科研贡献奖
大数据·人工智能·python·学习·机器人
小霖家的混江龙3 分钟前
数学不好也能懂:解读 AI 经典论文《Attention is All You Need》与大模型生成原理
人工智能·llm·aigc
njsgcs5 分钟前
ai控制鼠标生成刀路系统2 环境搭建 尝试
人工智能
Vincent_Zhang2336 分钟前
专题:所有宾语类型(持续补充)
笔记
喜欢吃豆6 分钟前
大语言模型(LLM)全栈技术深度综述:理论、系统与工程实践
人工智能·语言模型·自然语言处理·大模型
渡我白衣6 分钟前
计算机组成原理(8):各种码的作用详解
c++·人工智能·深度学习·神经网络·其他·机器学习
黑客思维者7 分钟前
机器学习016:监督学习【分类算法】(支持向量机)-- “分类大师”入门指南
人工智能·学习·机器学习·支持向量机·分类·回归·监督学习
我的golang之路果然有问题9 分钟前
win键盘设置改为类似mac 配置
windows·笔记·macos·计算机外设·键盘
小毅&Nora10 分钟前
【AI微服务】【Spring AI Alibaba】 ④ 深度实战:从零构建通义千问聊天服务(2025 最新版)
人工智能·微服务·spring ai
糖葫芦君10 分钟前
Lora模型微调
人工智能·算法