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.]
目录
相关文章
|
2天前
|
缓存 TensorFlow 算法框架/工具
TensorFlow学习笔记(一): tf.Variable() 和tf.get_variable()详解
这篇文章详细介绍了TensorFlow中`tf.Variable()`和`tf.get_variable()`的使用方法、参数含义以及它们之间的区别。
6 0
|
2月前
|
TensorFlow 算法框架/工具
【Tensorflow】图解tf.image.extract_patches的用法--提取图片特定区域
文章通过图解和示例详细解释了TensorFlow中tf.image.extract_patches函数的用法,展示了如何使用该函数从图像中提取特定区域或分割图像为多个子图像。
47 0
|
4月前
|
机器学习/深度学习 TensorFlow 算法框架/工具
tensorflow的常用函数
tensorflow的常用函数
20 1
|
5月前
|
机器学习/深度学习 数据可视化 TensorFlow
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
Python用线性回归和TensorFlow非线性概率神经网络不同激活函数分析可视化
|
5月前
|
机器学习/深度学习 PyTorch TensorFlow
【TensorFlow】TF介绍及代码实践
【4月更文挑战第1天】TF简介及代码示例学习
85 0
|
TensorFlow 算法框架/工具 异构计算
Tensorflow基本用法
Tensorflow基本用法
100 0
|
10月前
|
TensorFlow 算法框架/工具 Python
把python函数转化为 tensorflow 函数 加速运算
把python函数转化为 tensorflow 函数 加速运算
35 1
|
10月前
|
前端开发 TensorFlow 算法框架/工具
新容器 react tf tensorflow 物体识别 web版本
新容器 react tf tensorflow 物体识别 web版本
59 0
|
10月前
|
机器学习/深度学习 人工智能 TensorFlow
人工智能实验 python tensorflow keras拟合正弦函数,工资预测,公司收益预测
人工智能实验 python tensorflow keras拟合正弦函数,工资预测,公司收益预测
77 0
|
29天前
|
机器学习/深度学习 数据挖掘 TensorFlow
解锁Python数据分析新技能,TensorFlow&PyTorch双引擎驱动深度学习实战盛宴
在数据驱动时代,Python凭借简洁的语法和强大的库支持,成为数据分析与机器学习的首选语言。Pandas和NumPy是Python数据分析的基础,前者提供高效的数据处理工具,后者则支持科学计算。TensorFlow与PyTorch作为深度学习领域的两大框架,助力数据科学家构建复杂神经网络,挖掘数据深层价值。通过Python打下的坚实基础,结合TensorFlow和PyTorch的强大功能,我们能在数据科学领域探索无限可能,解决复杂问题并推动科研进步。
49 0

热门文章

最新文章