Tensorflow学习笔记(二):各种tf类型的函数用法集合

简介: 这篇文章总结了TensorFlow中各种函数的用法,包括创建张量、设备管理、数据类型转换、随机数生成等基础知识。
import tensorflow as tf
import numpy as np
"""tf.constant可用于创建tensor类型的int,float,bool"""

a = tf.constant([1,2],dtype=tf.int32)
b = tf.constant(1.2,dtype=tf.double)
c = tf.constant([True,False])
d = tf.constant('hello world')
print(a) # Tensor("Const:0", shape=(2,), dtype=int32)
print(b) # Tensor("Const_1:0", shape=(), dtype=float64)
print(c) # Tensor("Const_2:0", shape=(2,), dtype=bool)
print(d) # Tensor("Const_3:0", shape=(), dtype=string)
print(a.dtype) # <dtype: 'int32'>
print(b.dtype) # <dtype: 'float64'>
print(c.dtype) # <dtype: 'bool'>
print(d.dtype) # <dtype: 'string'>

"""device 是 string 类型 返回当前tensor所在的设备的名字"""
with tf.device('cpu'):
    a = tf.constant(1)
    print(a.device) # /device:CPU:*
with tf.device('gpu'):
    b =tf.constant(1.2,dtype=tf.double)
    print(b.device) # /device:GPU:*

"""tf.rank返回的是数据的维度"""
e =  tf.ones([1,2,3])
print(tf.rank(e)) # Tensor("Rank:0", shape=(), dtype=int32

"""isinstance用于判断数据是否为tensor,或者tf.is_tensor"""
print(isinstance(e,tf.Tensor)) # True
print(tf.is_tensor(e)) # True

"""通过tf.cast可以转换其它类型"""
f = tf.constant([0,1]) #
print(tf.cast(f,tf.bool)) # Tensor("Cast:0", shape=(2,), dtype=bool)

"""
tf.Variable函数可以优化参数,通过这个函数包装可具备求导的特性 ,也表示可以trainable,可训练的意思
isinstance一般不推荐使用,一般用tf.is_tensor和dtype来观察数据类型是否为tensor
"""
g = tf.Variable(f,name='input')
print(isinstance(g,tf.Variable)) # True
print(isinstance(g,tf.Tensor)) # False
print(tf.is_tensor(f)) # True

print("***********************************如何创建tensor******************************************")
"""1.可以通过numpy数据转换得到,也可以通过list得到,tf.float32更为常见"""
print(tf.convert_to_tensor(np.ones([2,3]))) # Tensor("Const_7:0", shape=(2, 3), dtype=float64)
print(tf.cast(tf.convert_to_tensor(np.zeros([2,3])),tf.float32)) # Tensor("Cast_1:0", shape=(2, 3), dtype=float32)
print(tf.convert_to_tensor([[1],[2.]])) # 两行一列 Tensor("Const_9:0", shape=(2, 1), dtype=float32)
"""
2.通过zeros,ones创建,传入的值为shape
zeros_like(a)可创建于a的shape相似的tensor,但是它的值全为0,相当于函数tf.zeros(a.shape)
通过tf.Session().run()可以将tensor类型转换为数组类型
"""
print("-------zeros/ones------")
h = tf.constant([1,2])
print(tf.Session().run(h)) # [1 2]
print(h) # Tensor("Const_10:0", shape=(2,), dtype=int32)
print(tf.zeros_like(h)) # Tensor("zeros_like:0", shape=(2,), dtype=int32)
print(tf.zeros([])) # Tensor("zeros:0", shape=(), dtype=float32)
print(tf.ones([])) # Tensor("ones_1:0", shape=(), dtype=float32)
print(tf.zeros([1])) # Tensor("zeros_1:0", shape=(1,), dtype=float32)
print(tf.zeros([2,3])) # Tensor("zeros_2:0", shape=(2, 3), dtype=float32)
print(tf.zeros([23,3,3])) # Tensor("zeros_3:0", shape=(23, 3, 3), dtype=float32)
print(tf.cast(tf.ones([25,3,3]),tf.int32)) # Tensor("Cast_2:0", shape=(25, 3, 3), dtype=int32)
"""通过tf.fill来进行填充,表示整个矩阵用后面的值来进行填充"""
print("-----------fill--------")
print(tf.fill([2,2],0)) # Tensor("Fill:0", shape=(2, 2), dtype=int32)
print(tf.fill([2,3],1)) # Tensor("Fill_1:0", shape=(2, 3), dtype=int32)
print(tf.fill([5,6],9)) # Tensor("Fill_2:0", shape=(5, 6), dtype=int32)

"""
通过tf.random.normal,为正态分布产生的随机值:常用的参数就是shape,和dtype了,但是也包括方差和均值,参数(shape,stddev,mean,dtype);
通过tf.random_uniform ,为均匀分布,默然是在0到1之间产生随机数:但是也可以通过maxval指定上界,通过minval指定下界
通过tf.random.truncated_normal表示截断的正态分布,也就是说截去一部分值,重新采样,
     好处就是对于神经网络的sigmoid激活函数,梯度两边趋于0的时候会出现梯度弥散现象(更新会很困难),通过截断的正态分布可杜绝这一现象
"""
print("----------tf.random-------")
print(tf.random.normal([2,2],mean=1,stddev=1,dtype=tf.float32)) # Tensor("random_normal:0", shape=(2, 2), dtype=float32)
"""把tensor类型转换为numpy类型"""
print(tf.Session().run(tf.random_normal([2,2],mean=1,stddev=1))) # [[ 1.9472154   1.5877222 ]  [-0.41115534  2.4914074 ]]
print(tf.Session().run(tf.random.truncated_normal([2,2],mean=0,stddev=1))) # [[ 1.0924922 -0.7859821]  [-1.0922529 -1.6760032]]
print(tf.Session().run(tf.random_uniform([2,2],minval=0,maxval=0.5))) # [[0.18084687 0.07610059]  [0.2441327  0.19389218]]
print(tf.Session().run(tf.random_uniform([2,2],minval=0,maxval=100,dtype=tf.int32))) #[[84 27]  [43 86]]

"""tf.random.shuffle可以将索引值进行打散"""
idex = tf.range(10)
idx = tf.random.shuffle(idex)
print(tf.Session().run(idx)) # [1 6 8 2 3 4 5 7 0 9]

"""tf.gather的作用是取出tensor中指定位置的元素"""
i = tf.range(0,10)*15+tf.constant(1,shape=[10],dtype=tf.int32)
i1=tf.gather(i,[1,6,8])
print("tf.gather",tf.Session().run(i)) # tf.gather [  1  16  31  46  61  76  91 106 121 136]
print("tf.gather1",tf.Session().run(i1)) # tf.gather1 [ 16  91 121]

"""通过tf.one_hot可以将数组里面对应的值归为1,其它为0,其它的长度根据它depth来决定"""
j = tf.range(4)
j1 = tf.one_hot(j,depth=10)
print("tf.one_hot:",tf.Session().run(j)) # tf.one_hot: [0 1 2 3]
print("tf.one_hot1:",tf.Session().run(j1)) # tf.one_hot1: [[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.], [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.], [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.], [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]]

"""
根据tf.keras.losses.mse来计算loss
tf.reduce_sum :计算tensor指定轴方向上的所有元素的累加和
tf.reduce_max : 计算tensor指定轴方向上的各个元素的最大值
tf.reduce_all : 计算tensor指定轴方向上的各个元素的逻辑和(and运算)
tf.reduce_any: 计算tensor指定轴方向上的各个元素的逻辑或(or运算)
"""
out = tf.random_uniform([4,10])
j = tf.range(4)
k = tf.constant([[1,2,3],[2,3,4]],dtype=tf.float32)
y = tf.one_hot(j,depth=10) # shape 都是(4,10)
print(tf.Session().run(out))
loss = tf.keras.losses.mse(y,out)
print("the loss is :",tf.Session().run(loss)) # the loss is : [0.39633512 0.35060614 0.3344883  0.3332817 ]
loss1 = tf.reduce_mean(loss)
loss2 = tf.reduce_mean(k,axis=0)
loss3 = tf.reduce_mean(k,axis=1) # 如果加了keep_dims=True返回的值也是和原来维度想同
print("the loss1 is :",tf.Session().run(loss1)) # the loss is : 0.30756846,也就是所有的加起来求平均
print("the loss2 is :",tf.Session().run(loss2)) # the loss2 is : [1.5 2.5 3.5]
print("the loss3 is :",tf.Session().run(loss3)) # the loss3 is : [2. 3.]
目录
相关文章
|
1天前
|
存储 缓存 关系型数据库
MySQL事务日志-Redo Log工作原理分析
事务的隔离性和原子性分别通过锁和事务日志实现,而持久性则依赖于事务日志中的`Redo Log`。在MySQL中,`Redo Log`确保已提交事务的数据能持久保存,即使系统崩溃也能通过重做日志恢复数据。其工作原理是记录数据在内存中的更改,待事务提交时写入磁盘。此外,`Redo Log`采用简单的物理日志格式和高效的顺序IO,确保快速提交。通过不同的落盘策略,可在性能和安全性之间做出权衡。
1517 4
|
29天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
5天前
|
人工智能 Rust Java
10月更文挑战赛火热启动,坚持热爱坚持创作!
开发者社区10月更文挑战,寻找热爱技术内容创作的你,欢迎来创作!
483 17
|
1天前
|
存储 SQL 关系型数据库
彻底搞懂InnoDB的MVCC多版本并发控制
本文详细介绍了InnoDB存储引擎中的两种并发控制方法:MVCC(多版本并发控制)和LBCC(基于锁的并发控制)。MVCC通过记录版本信息和使用快照读取机制,实现了高并发下的读写操作,而LBCC则通过加锁机制控制并发访问。文章深入探讨了MVCC的工作原理,包括插入、删除、修改流程及查询过程中的快照读取机制。通过多个案例演示了不同隔离级别下MVCC的具体表现,并解释了事务ID的分配和管理方式。最后,对比了四种隔离级别的性能特点,帮助读者理解如何根据具体需求选择合适的隔离级别以优化数据库性能。
179 1
|
8天前
|
JSON 自然语言处理 数据管理
阿里云百炼产品月刊【2024年9月】
阿里云百炼产品月刊【2024年9月】,涵盖本月产品和功能发布、活动,应用实践等内容,帮助您快速了解阿里云百炼产品的最新动态。
阿里云百炼产品月刊【2024年9月】
|
21天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。
|
8天前
|
Linux 虚拟化 开发者
一键将CentOs的yum源更换为国内阿里yum源
一键将CentOs的yum源更换为国内阿里yum源
442 4
|
7天前
|
存储 人工智能 搜索推荐
数据治理,是时候打破刻板印象了
瓴羊智能数据建设与治理产品Datapin全面升级,可演进扩展的数据架构体系为企业数据治理预留发展空间,推出敏捷版用以解决企业数据量不大但需构建数据的场景问题,基于大模型打造的DataAgent更是为企业用好数据资产提供了便利。
313 2
|
23天前
|
人工智能 IDE 程序员
期盼已久!通义灵码 AI 程序员开启邀测,全流程开发仅用几分钟
在云栖大会上,阿里云云原生应用平台负责人丁宇宣布,「通义灵码」完成全面升级,并正式发布 AI 程序员。
|
25天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2608 22
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析