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)
相关推荐
DKPT1 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
子燕若水2 小时前
Unreal Engine 5中的AI知识
人工智能
极限实验室3 小时前
Coco AI 实战(一):Coco Server Linux 平台部署
人工智能
杨过过儿3 小时前
【学习笔记】4.1 什么是 LLM
人工智能
巴伦是只猫3 小时前
【机器学习笔记Ⅰ】13 正则化代价函数
人工智能·笔记·机器学习
伍哥的传说3 小时前
React 各颜色转换方法、颜色值换算工具HEX、RGB/RGBA、HSL/HSLA、HSV、CMYK
深度学习·神经网络·react.js
大千AI助手3 小时前
DTW模版匹配:弹性对齐的时间序列相似度度量算法
人工智能·算法·机器学习·数据挖掘·模版匹配·dtw模版匹配
AI生存日记3 小时前
百度文心大模型 4.5 系列全面开源 英特尔同步支持端侧部署
人工智能·百度·开源·open ai大模型
LCG元4 小时前
自动驾驶感知模块的多模态数据融合:时序同步与空间对齐的框架解析
人工智能·机器学习·自动驾驶