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)
相关推荐
伊玛目的门徒6 分钟前
用 npm 安装 Claude Code CLI 并对接 DeepSeek API 经验分享
人工智能·npm·大模型·ai编程·deepseek·claude code
xiaoduo AI9 分钟前
智能客服机器人能实时监控会话风险规避服务纠纷吗?能规范服务话术守住门店口碑吗?
大数据·人工智能·机器人
逻辑君11 分钟前
认知神经科学研究报告【20260033】
人工智能·机器学习
l1t11 分钟前
DeepSeek总结的Delta 成长记:写入、Unity Catalog 和时间旅行
数据库·人工智能·unity
飞Link11 分钟前
从 Promptbreeder 到 EvoPrompt:深度解析进化 AI (eAI) 的提示词自动优化策略
大数据·人工智能
初圣魔门首席弟子12 分钟前
MLP(多层感知机)(纯大白话 + 生活比喻 + 零公式)
深度学习·生活
code_pgf13 分钟前
llama.cpp 最新架构详解
人工智能·架构·llama
BB8=_=NiMotion14 分钟前
一体式步进伺服电机在自动取药机器人中的应用
人工智能·物联网·自动取药机器人
AI前沿资讯15 分钟前
AI角色一键生成工具推荐:V2Fun 打通3D动画智能化创作全流程
人工智能·3d