TensorFlow 2.0 入门实战笔记(二)Tensorflow基础操作

二、Tensorflow基础操作

2.1 数据类型

  • 标量:单个实数,维度(秩)为0,shape为 [ ]
  • 向量:n个实数的有序集合,秩为1,shape为[n]
  • 矩阵:n行m列的有序集合,秩为2,shape为[n, m]
  • 张量:所有维度数 dim > 2 的数组统称为张量,张量的每个维度也叫做轴(axis)
    在tensorflow中,一般也把标量、向量、矩阵也统称为张量,不作区分。

2.1.1 数据载体

list支持不同的数据类型,效率低
np.array相同类型的载体,效率高,但是不支持GPU,不支持自动求导
tf.Tensortensorflow中存储大量连续数据的载体

2.1.2 基本数据类型

tf.int32:tf.constant(1)
tf.float32:tf.constant(1.)
tf.float64: tf.constant(1., dtype=tf.double)
tf.bool: tf.constant([True, False])
tf.string:tf.constant('hello')

2.1.3 数值精度

常用的数值精度有:tf.int16, tf.int32, tf.int64, tf.float16, tf.float32, tf.float64, 其中tf.float64即为tf.double
可通过dtype设置数值精度

In [10]: tf.constant(2, dtype = tf.double)                                      
Out[10]: <tf.Tensor: id=8, shape=(), dtype=float64, numpy=2.0>

2.1.4 数据基本属性

with tf.device("cpu"):
    a=tf.range(4)
a.device # '/job:localhost/replica:0/task:0/device:CPU:0'
aa=a.gpu() 
a.numpy() # array([0, 1, 2, 3], dtype=int32) [转换为numpy格式]
a.ndim # 1  (0的话就是标量) [显示当前维度,返回一个标量]
a.shape # TensorShape([4]) [返回张量的形状]
a.name # AttributeError: Tensor.name is meaningless when eager execution is enabled. 
tf.rank(tf.ones([3,4,2])) # <tf.Tensor: id=466672, shape=(), dtype=int32, numpy=3>[显示当前维度,返回一个张量]
tf.is_tensor(a) # True [判断是否为Tensor类型,返回True/False]
a.dtype # tf.int32 [返回数据类型]

device:显示当前设备
a.gpu()/ a.cpu:设备的切换
rank和ndim的区别在于返回的类型不同
name属性在tensorflow2没有意义,因为变量名本身就是name

2.1.4 Array 和 Tensor的不同之处:

判断一个变量究竟是tensor还是array,直接输出它的dtype,输出上面那样的就是tensor,输出下面那样的就是array

输入
a=tf.constant([[1,2],[3,4]],dtype=tf.float32)
print(a.dtype)
b=np.array([[1,2],[3,4]],dtype='float32')
print(b.dtype)

输出:
<dtype: 'float32'>  
float32

2.1.5 Array 和 Tensor的转换:

Numpy中的存储格式为Array

a=np.arange(5) # [0, 1, 2, 3, 4]
a.dtype # dtype('int64')
aa=tf.convert_to_tensor(a) # <tf.Tensor: id=466678, shape=(5,), dtype=int64, numpy=array([0, 1, 2, 3, 4])>[将aa转换为tensor]
aa=tf.convert_to_tensor(a, dtype=tf.int32) # <tf.Tensor: id=466683, shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>[将aa转换为tensor类型的同时指定dtype]
tf.cast(aa, tf.float32) # 将aa 转换为 float32类型

b=tf.constant([0,1])
tf.cast(b, tf.bool) # <tf.Tensor: id=466697, shape=(2,), dtype=bool, numpy=array([False,  True])>

a.tf.ones([2,3])
a.numpy()# [将a转换为Array]
int(a) #标量可以直接这样类型转换
float(a)

2.1.6 可训练数据类型:

只有Variable类型的张量可以通过训练自动改变值

a=tf.range(5)
b=tf.Variable(a)
b.dtype # tf.int32
b.name # 'Variable:0' 其实没啥用
b.trainable #True 可训练

2.2 创建Tensor

tf.convert_to_tensor(data) 将data转换为tensor,其中data 可以为np.ones(shape)、np.zeros(shape) 、[1,2]等numpy矩阵
tf.zeros(shape)生成一个tensor,维度形状为shape
tf.ones(1)生成一个一维tensor,包含一个1
tf.ones([])生成一个标量1
tf.ones([2])生成一个一维tensor,包含两个1
tf.ones_like(a)相当于tf.ones(a.shape)
tf.fill([3,4], 9) 全部填充9
tf.random.normal([3,4], mean=1, stddev=1) 正态分布随机生成,形状为(3,4)mean 均值 ,stddev 标准差
tf.random.truncated_normal([3,4], mean=0, stddev=1) 带截断的正态分布,(大于某个值重新采样),比如在经过sigmoid激活后,如果用带截断的,可以避免出现梯度消失问题。
tf.random.uniform([3,4], minval=0, maxval=100, dtype=tf.int32)平均分布
tf.constant(a)a为常量或定值Tensor
idx=tf.random.shuffle(idx)#随机打散idx
令a,b有对应关系,则a,b打散之后仍有对应关系

idx=tf.range(5)
idx=tf.random.shuffle(idx) # 随机打散idx
a=tf.random.normal([10,784])
b=tf.random.uniform([10])
a=tf.gather(a, idx) # a中随机取5行
b=tf.gather(b, idx) # b中随机取5个

2.3 索引与切片

2.3.1 索引

基本:a[idx][idx][idx],a为Tensor

In [4]:a=tf. ones([1,5,5,3])
In [5]:a[0][0]
<tf. Tensor: id=16, shape=(5,3), dtype=float32, numpy=
array([ [1.,1.,1.],
		[1.,1.,1.],
		[1.,1.,1.],
		[1.,1.,1.],
		[1.,1.,1.]], dtype=float32)>
In [6]:a[0][0][0]
Out[6]:<tf. Tensor: id=29, shape=(3,), dtype=float32, numpy=array([1.,1.,1.], dtype=float32)>
In [7]:a[0][0][0][2]
0ut[7]:<tf. Tensor: id=46, shape=(), dtype=float32, numpy=1.0>

numpy风格:a[idx,idx,idx]可读性更强

In [8]:a=tf. random. normal([4,28,28,3])
In [9]:a[1]. shape 
Out[9]: TensorShape([28,28,3])
In [10]:a[1,2]. shape
Out[10]: TensorShape([28,3])
In [11]:a[1,2,3]. shape 
Out[11]: TensorShape([3]) 
In [12]:a[1,2,3,2]. shape 
Out[12]: TensorShape([])

2.3.2 一般切片

与numpy基本一致
a[start:end:positive_step]
a[end:start:negative_step]
a[0, 1, ..., 0]代表任意多个: 只要能推断出有多少个:就是合法的
[A:B]表示从A位置取到B位置,A位置包含在内,B位置不包含在内
[A: ]从A位置去到末尾位置
[ :B]从起始0位置取到B位置,但不包含B位置
[ : ]从起始位置到末尾位置,取遍所有

Start:End

In [8]:a=tf. range(10)
Out[9]:<tf. Tensor: numpy=array([o,1,2,3,4,5,6,7,8,9])>
In [14]:a[-1:]
Out[14]:<tf. Tensor: id=48, shape=(1,), dtype=int32, numpy=array([9])>
In [15]:a[-2:]
Out[15]:<tf. Tensor: id=53, shape=(2,), dtype=int32, numpy=array([8,9])>
In [16]:a[:2]
Out[16]:<tf. Tensor: id=58, shape=(2,), dtype=int32, numpy=array([o,1])>
In [17]:a[:-1]
Out[17]:<tf. Tensor: id=63, shape=(9,), dtype=int32, numpy=array([o,1,2,3,4,
5,6,7,8])>
In [14]:a. shape # TensorShape([4,28,28,3])
In [15]:a[0]. shape # TensorShape([28,28,3])
In [16]:a[0,:,:,:]. shape
0ut[16]: TensorShape([28,28,3])
In[17]:a[0,1,:,:]. shape
0ut[17]: TensorShape([28,3])
In [18]:a[:,:,:,0]. shape
0ut[18]: TensorShape([4,28,28])
In [19]:a[:,:,:,2]. shape
0ut[19]: TensorShape([4,28,28])
In [20]:a[:,0,:,:]. shape
0ut[20]: TensorShape([4,28,3])

[A:B:N]表示从A位置到B位置,每隔N个位置取一次,A位置包含在内,B位置不包含在内,

Start:End:Step

In [21]:a. shape 
Out[21]: TensorShape([4,28,28,3])
In [22]:a[0:2,:,:,:]. shape
Out[22]: TensorShape([2,28,28,3])
In [23]: al:,0:28:2,0:28:2,:]. shape
Out[23]: TensorShape([4,14,14,3])
In [24]:a[:,:14,:14,:]. shape
Out[24]: TensorShape([4,14,14,3])
In [25]:a[:,14:,14:,:]. shape
0ut[25]: TensorShape([4,14,14,3])
In [26]: al:,::2,::2,:]. shape
Out[26]: TensorShape([4,14,14,3])

Step还可以为负值

In [27]:a=tf. range(4)
Out[28]:<tf. Tensor: id=118, shape=(4,), dtype=int32, numpy=array([o,1,2,3], dtype=int32)>
In [29]:a[::-1]
Out[29]:<tf. Tensor: id=123, shape=(4,), dtype=int32, numpy=array([3,2,1,0], dtype=int32)>
In [30]:a[::-2]
Out[30]:<tf. Tensor: id=128, shape=(2,), dtype=int32, numpy=array([3,1], dtype=int32)>
In [31]:a[2::-2]
out[31]:<tf. Tensor: id=133, shape=(2,), dtype=int32, numpy=array([2,0], dtype=int32)>

"···" 表示系统自动推断剩余维度

In [36]:a=tf. random. normal([2,4,28,28,3])
In [37]:a[0]. shape 
Out[37]: TensorShape([4,28,28,3])
In [38]:a[0,:,:,:,:]. shape 
Out[38]: TensorShape([4,28,28,3])
In [39]:a[0,...]. shape 
Out[39]: TensorShape([4,28,28,3])
In [40]:a[:,:,:,:,0]. shape 
Out[40]: TensorShape([2,4,28,28])
In [41]:a[...,0]. shape 
Out[41]: TensorShape([2,4,28,28])
In [42]:a[0,...,2]. shape 
Out[42]: TensorShape([4,28,28])
In [43]:a[1,0,...,0]. shape 
Out[43]: TensorShape([28,28])

2.3.3 Selective Indexing

tf.gather(params,,axis ,indices)
其中params为张量,axis为维度轴,indices表示从此维度选取的元素并且重排为设定顺序,
场景:
假设每个维度的意义:data: [classes, students, subjects]
[4, 35, 8] 代表有4个classes,每个class有35个student,每个学生学习8个subject

# a[4,35,8]
In [46]: tf.gather(a, axis=0, indices=[2,3]).,shape #axis=0表示按照classes维度取 
								# indices=[2,3]表从4个班级中选取第二个和第三个班级顺序按照2,3
Out[46]: TensorShape([2,35,8])
In [47]:a[2:4]. shape 
Out[47]: Tensor Shape([2,35,8])
In [48]: tf. gather(a, axis=0, indices=[2,1,4,0]). shape # indices=[2,1,4,0]取到的班级顺序按照2,1,4,0 重排顺序
Out[48]: TensorShape([4,35,8])
In [49]: tf. gather(a, axis=1, indices=[2,3,7,9,16]). shape 
Out[49]: TensorShape([4,5,8])
In [50]: tf. gather(a, axis=2, indices=[2,3,7]). shape 
Out[50]: TensorShape([4,35,3])

tf.gather_nd( params, indices, name=None)
W3Cshool解释
类比tf.gather可同时制定多个维度进行选择切片


In [55]:a. shape Out[55]: Tensor Shape([4,35,8])
In [60]: tf. gather_nd(a,[0]). shape 
Out[60]: TensorShape([35,8])
In [61]: tf. gather_nd(a,[0,1]). shape 
Out[61]: TensorShape([8])
In [62]: tf. gather_nd(a,[o,1,2]). shape 
Out[62]: TensorShape([])
In [63]: tf. gather_nd(a,[[o,1,2]]). shape 
Out[63]: TensorShape([1])
In [55]:a. shape Out[55]: TensorShape([4,35,8])
In [56]: tf. gather_nd(a,[[o,0],[1,1]]). shape 
Out[56]: Tensor Shape([2,8])
In [57]: tf. gather_nd(a,[[0,0],[1,1],[2,2]]). shape 
Out[57]: TensorShape([3,8])
In [58]: tf. gather_nd(a,[[o,0,0],[1,1,1],[2,2,2]]). shape
Out[58]: Tensor Shape([3])
In [59]: tf. gather_nd(a,[[[0,0,0],[1,1,1],[2,2,2]]]). shape
Out[59]: TensorShape([1,3])

tf.boolean_mask
tf.boolean_mask(a, mask=[True, True, False], axis=3)axis=3是第四维度表RGB, 相当于只取3个通道中的前两个RG的数据, a的shape是[4, 28, 28, 3]。mask可以是一个list。

In[75]:a. shape 
Out[75]: TensorShape([4,28,28,3])
In [76]: tf. boolean_mask(a, mask=[ True, True, False, False]). shape
0ut[76]: Tensor Shape([2,28,28,3])
In [77]: tf. boolean_mask(a, mask=[ True, True, False], axis=3). shape 
Out[77]: TensorShape([4,28,28,2])
In [78]:a=tf. ones([2,3,4])
In [79]: tf. boolean_mask(a, mask=[[ True, False, False],[ False, True, True]])
<tf. Tensor: id=354, shape=(3,4), dtype=float32, numpy=
array([ [1.,1.,1.,1.],
		[1.,1.,1.,1.],
		[1.,1.,1.,1.J], dtype=float32)>

2.4 维度变换

  • 查看形状a.shape
  • 查看当前维度a.ndim

2.4.1 图片的存储View

  • [b, 28, 28] 考虑行和列
  • →[b, 28*28] 不考虑行和列,神经网络全连接的View方式
  • →[b, 2, 14*28] 图片存储为上下两部分
  • →[b, 28, 28, 1] 加入channel概念,1可省略

2.4.2 tf.transpose 交换图像的行列【转置】

a=tf.random.normal([4, 3, 2, 1])
tf.transpose(a, perm=[0, 1, 3, 2])# 0,1不变,相当于交换最后两维
# 输出为 [4,3,1,2]

2.4.2 tf.reshape 重置维度

Reshape可提供无数种重置形状的可能,但并非都可解释,或者说属性都有物理意义
Reshape要保证所有pixel数量不变

In [80]:a=tf. random. normal([4,28,28,3])
Out[81]: TensorShape([4,28,28,3])
In [82]:a. shape,a. ndim
0ut[82]:(Tensor Shape([4,28,28,3]),4)
In [83]: tf. reshape(a,[4,784,3]). shape 
Out[83]: TensorShape([4,784,3])
In [84]: tf. reshape(a,[4,-1,3]). shape 
Out[84]: TensorShape([4,784,3])
In [85]: tf. reshape(a,[4,784*3]). shape 
Out[85]: TensorShape([4,2352])
In [86]: tf. reshape(a,[4,-1]). shape 
Out[86]: TensorShape([4,2352])

2.4.3 tf.expand_dims增加维度

dim和axis含义类似

a=tf.random.normal([4, 35, 8])
tf.expand_dims(a, axis=3)  # 增加的维度是第4(3+1)维 shape是[4, 35, 8, 1]
tf.expand_dims(a, axis=0)  # 增加的维度是第 0 维 shape是[ 1,4, 35, 8]

axis 指的是扩展维度轴的位置

In [103]:a=tf. random. normal([4,35,8])
In [105]: tf. expand_dims(a, axis=0). shape 
Out[105]: TensorShape([1,4,35,8])
In [106]: tf. expand_dims(a, axis=3). shape 
Out[106]: TensorShape([4,35,8,1])
In [107]: tf. expand_dims(a, axis=-1). shape 
Out[107]: Tensor Shape([4,35,8,1])
In [108]: tf. expand_dims(a, axis=-4). shape 
Out[108]: TensorShape([1,4,35,8])

2.4.4 tf.squeeze 压缩维度

默认去掉所有长度是1的维度,也可以通过axis指定某一个维度

In [115]: tf. squeeze(tf. zeros([1,2,1,1,3])). shape 
Out[115]: TensorShape([2,3])
In [116]:a=tf. zeros([1,2,1,3])
In [117]: tf. squeeze(a, axis=0). shape 
Out[117]: TensorShape([2,1,3])
In [118]: tf. squeeze(a, axis=2). shape 
Out[118]: TensorShape([1,2,3])
In [119]: tf. squeeze(a, axis=-2). shape 
Out[119]: TensorShape([1,2,3])
In [120]: tf. squeeze(a, axis=-4). shape 
Out[120]: TensorShape([2,1,3])

2.5 Broadcasting

W3Cschool相关解释

若相加的两个Tensor的维度不一致,则扩展其中一个Tensor的维度与另一个对齐,但内存中并未发生数据复制;
原则:低维度对齐,低维度不同则不同
在实际使用的过程中往往可省略,由解释器自动判断完成
在这里插入图片描述
tf. broadcast_to
场景:一般情况下,高维度比低维度的概念更高层,如[班级,学生,成绩],利用broadcasting把小维度推广到大维度。
作用:简洁、节省内存

In [35]:x. shape Out[35]: TensorShape([4,32,32,3]) 
In [36]:(x+tf. random. normal([4,1,1,1])). shape 
Out[36]: TensorShape([4,32,32,3])
In [37]:b=tf. broadcast_to(tf. random. normal([4,1,1,1]),[4,32,32,3])
In [38]:b. shape 
Out[38]: Tensor Shape([4,32,32,3])

参考:https://www.cnblogs.com/chenhuabin/p/11594239.html#_label3在这里插入图片描述
可以看到,一个一维的张量与一个三维张量进行运算是完全没有问题的,从运算结果上可以看出,相当于是三维张量中的每一行数据与张量a进行运算,为什么可以这样运输呢?这就得益于TensorFlow中的Broadcasting机制。

Broadcasting机制解除了只能维度数和形状相同的张量才能进行运算的限制,当两个数组进行算术运算时,TensorFlow的Broadcasting机制首先对维度较低的张量形状数组填充1,从后向前,逐元素比较两个数组的形状,当逐个比较的元素值(注意,这个元素值是指描述张量形状数组的值,不是张量的值)满足以下条件时,认为满足
Broadcasting 的条件:

(1)相等

(2)其中一个张量形状数组元素值为1。

当不满足时进行运算则会抛出 ValueError: frames are not aligne
异常。算术运算的结果的形状的每一元素,是两个数组形状逐元素比较时的最大值。

回到上面张量a与b相乘的例子,a的形状是(3,),b的形状是(2, 2,
3),在Broadcasting机制工作时,首先比较维度数,因为a的维度为1,小于b的维度3,所以填充1,a的形状就变成了(1,1,3),然后从最后端的形状数组元素依次往前比较,先是就是3与3比,结果是相等,接着1与2相比,因为其中一个为1,所以a的形状变成了(1,2,3),继续1与2比较,因为其中一个为1,所以a的形状变成了(2,2,3),a中的数据每一行都填充a原来的数据,也就是[1,2,3],然后在与b进行运算。

当然,在TensorFlow的Broadcasting机制运行过程中,上述操作只是理论的,并不会真正的将a的形状变成(2,2,3,),更不会将每一行填充[1,2,3],只是虚拟进行操作,真正计算时,依旧是使用原来的张量a。这么做的好处是运算效率更高,也更节省内存。

Broadcast VS Tile(复制)

In [4]:a=tf. ones([3,4])
In [5]: al=tf. broadcast_to(a,[2,3,4])
<tf. Tensor: id=7, shape=(2,3,4), dtype=float32, numpy=
arrayC[[[4.,1.,1.,1.],
		[4.,1.,1.,1.],
		[4.,1.,1.,1.]],

		[[4.,1.,1.,1.],
		[4.,1.,1.,1.],
		[1.,1.,1.,1.]]], dtype=float32)>
In [7]:a2=tf. expand_dims(a, axis=0)
0ut[8]: TensorShape([1,3,4])
In [40]:a2=tf. tile(a2,[2,1,1])
<tf. Tensor: id=12, shape=(2,3,4), dtype=float32, annpyf[[[4.,1.,1.,1.],
														[4.,1.,1.,1.],
														[4.,1.,1.,1.]],

														[[4.,1.,1.,1.],
														[4.,1.,1.,1.],
														[4.,1.,1.,1.]]], dtupe=float32)>

2.6 数学运算

常用的数学运算
可参考【tensorflow 2.0 基础操作 之 数学运算】

+ - * / // %
tf.math.log && tf.exp
pow , sqrt
@ tf.matmul
liner layer

2.6.1 + - * / // %运算

+:对应矩阵元素相加
-:对应矩阵元素相减
*:对应矩阵元素相除
/:对应矩阵元素相除
%:对应矩阵元素求余
//:对应矩阵元素整除

/除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数;
//,称为地板除,两个整数的除法仍然是整数。

基本运算中所有实例都以下面的张量a、b为例进行:

In [2]: a = tf.ones([2,2])#2*2矩阵,全部填充为1                                  

In [3]: b =  tf.fill([2,2],2.)#2*2矩阵,全部填充为2                              

In [4]: a                                                                       
Out[4]: 
<tf.Tensor: id=2, shape=(2, 2), dtype=float32, numpy=
array([[1., 1.],
       [1., 1.]], dtype=float32)>

In [5]: b                                                                       
Out[5]: 
<tf.Tensor: id=5, shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
       [2., 2.]], dtype=float32)>

In [6]: a + b#对应矩阵元素相加                                                  
Out[6]: 
<tf.Tensor: id=8, shape=(2, 2), dtype=float32, numpy=
array([[3., 3.],
       [3., 3.]], dtype=float32)>

In [7]: a - b#对应矩阵元素相减                                                  
Out[7]: 
<tf.Tensor: id=10, shape=(2, 2), dtype=float32, numpy=
array([[-1., -1.],
       [-1., -1.]], dtype=float32)>

In [8]: a * b #对应矩阵元素相乘                                                 
Out[8]: 
<tf.Tensor: id=12, shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
       [2., 2.]], dtype=float32)>

In [9]: a / b#对应矩阵元素相除                                                  
Out[9]: 
<tf.Tensor: id=14, shape=(2, 2), dtype=float32, numpy=
array([[0.5, 0.5],
       [0.5, 0.5]], dtype=float32)>

In [10]: b // a #对应矩阵元素整除                                               
Out[10]: 
<tf.Tensor: id=16, shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
       [2., 2.]], dtype=float32)>

In [11]: b % a #对应矩阵元素求余                                                
Out[11]: 
<tf.Tensor: id=18, shape=(2, 2), dtype=float32, numpy=
array([[0., 0.],
       [0., 0.]], dtype=float32)>

可以看出,对于基本运算加(+)、减(-)、点乘(*)、除(/)、地板除法(//)、取余(%),都是对应元素进行运算。

2.6.2 tf.math.log( ) 和tf.math.exp( ) 函数

tf.math.log( )以e为底求对数
tf.math.exp( n )e的n次方

In [12]: a = tf.ones([2,2])                                                     

In [13]: a                                                                      
Out[13]: 
<tf.Tensor: id=22, shape=(2, 2), dtype=float32, numpy=
array([[1., 1.],
       [1., 1.]], dtype=float32)>

In [14]: tf.math.log(a)#矩阵对应元素取对数                                      
Out[14]: 
<tf.Tensor: id=24, shape=(2, 2), dtype=float32, numpy=
array([[0., 0.],
       [0., 0.]], dtype=float32)>

In [15]: tf.math.exp(a)#矩阵对应元素取指数                                      
Out[15]: 
<tf.Tensor: id=26, shape=(2, 2), dtype=float32, numpy=
array([[2.7182817, 2.7182817],
       [2.7182817, 2.7182817]], dtype=float32)>


log 但是 没有以其他 为底的 API
实现 以2,10 为底
在这里插入图片描述
在这里插入图片描述

In [17]: a = tf.random.normal([2,2])                                            

In [18]: a                                                                      
Out[18]: 
<tf.Tensor: id=38, shape=(2, 2), dtype=float32, numpy=
array([[ 0.12121297, -1.6076226 ],
       [ 1.4407614 ,  0.8430799 ]], dtype=float32)>

In [19]: tf.math.log(a)/tf.math.log(2.)#计算矩阵对应元素以2为底的对数           
Out[19]: 
<tf.Tensor: id=43, shape=(2, 2), dtype=float32, numpy=
array([[-3.044384  ,         nan],
       [ 0.5268315 , -0.24625869]], dtype=float32)>

In [20]: tf.math.log(a)/tf.math.log(10.)#计算矩阵对应元素以10为底的对数         
Out[20]: 
<tf.Tensor: id=48, shape=(2, 2), dtype=float32, numpy=
array([[-0.91645086,         nan],
       [ 0.15859208, -0.07413125]], dtype=float32)>


参考 : https://blog.csdn.net/z_feng12489/article/details/89341002

2.6.3 tf.pow( )和 tf.sqrt( )函数

tf.pow(a,3)矩阵a所有元素取立方
a**3矩阵a所有元素取立方
tf.sqrt(a)矩阵a所有元素开平方

In [2]: a = tf.fill([2,2],2.)                                                   

In [3]: a                                                                       
Out[3]: 
<tf.Tensor: id=2, shape=(2, 2), dtype=float32, numpy=
array([[2., 2.],
       [2., 2.]], dtype=float32)>

In [4]: tf.pow(a,3)#矩阵a所有元素取立方                                         
Out[4]: 
<tf.Tensor: id=5, shape=(2, 2), dtype=float32, numpy=
array([[8., 8.],
       [8., 8.]], dtype=float32)>

In [5]: a**3#矩阵a所有元素取立方                                                
Out[5]: 
<tf.Tensor: id=8, shape=(2, 2), dtype=float32, numpy=
array([[8., 8.],
       [8., 8.]], dtype=float32)>

In [6]: tf.sqrt(a)#矩阵a所有元素开平方                                          
Out[6]: 
<tf.Tensor: id=10, shape=(2, 2), dtype=float32, numpy=
array([[1.4142135, 1.4142135],
       [1.4142135, 1.4142135]], dtype=float32)>


2.6.4 @ matmul 矩阵相乘

@与matmul等价作用

In [7]: a = tf.fill([2,2],1.)                                                   

In [8]: b = tf.fill([2,2],2.)                                                   

In [9]: a,b                                                                     
Out[9]: 
(<tf.Tensor: id=14, shape=(2, 2), dtype=float32, numpy=
 array([[1., 1.],
        [1., 1.]], dtype=float32)>,
 <tf.Tensor: id=17, shape=(2, 2), dtype=float32, numpy=
 array([[2., 2.],
        [2., 2.]], dtype=float32)>)

In [10]: a @ b#矩阵相乘                                                         
Out[10]: 
<tf.Tensor: id=20, shape=(2, 2), dtype=float32, numpy=
array([[4., 4.],
       [4., 4.]], dtype=float32)>

In [11]: tf.matmul(a,b)#矩阵相乘                                                
Out[11]: 
<tf.Tensor: id=22, shape=(2, 2), dtype=float32, numpy=
array([[4., 4.],
       [4., 4.]], dtype=float32)>


In [12]: a = tf.ones([4,2,3])                                                   

In [13]: b = tf.fill([4,3,5],2.)                                                

In [14]: a@b    #[2,3]@[3,5] = [2,5]                                                                
Out[14]: 
<tf.Tensor: id=30, shape=(4, 2, 5), dtype=float32, numpy=
array([[[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]],

       [[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]],

       [[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]],

       [[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]]], dtype=float32)>

In [15]: tf.matmul(a,b)                                                         
Out[15]: 
<tf.Tensor: id=32, shape=(4, 2, 5), dtype=float32, numpy=
array([[[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]],

       [[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]],

       [[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]],

       [[6., 6., 6., 6., 6.],
        [6., 6., 6., 6., 6.]]], dtype=float32)>

With broadcasting

In [164]:a. shape # TensorShape([4,2,3])
In [165]:b. shape # TensorShape([3,5])
In [166]: bb=tf. broadcast_to(b,[4,3,5])
In [167]: adbb
<tf. Tensor: id=516, shape=(4,2,5), dtype=float32, numpy=
array([[[6.,6.,6.,6.,6.],
[6.,6.,6.,6.,6.]],..
[[6.,6.,6.,6.,6.],
[6.,6.,6.,6.,6.]]], dtype=f loat32)>

2.6.5 liner layer

在这里插入图片描述

参考 : https://blog.csdn.net/z_feng12489/article/details/89341002

𝑍 = 𝑌@𝑋 + 𝑏

In [168]:x=tf. ones([4,2]) In [169]:W=tf. ones([2,1])
In [170]:b=tf. constant(0.1)
In [171]: xCW+b
<tf. Tensor: id=526, shape=(4,1), dtype=float32, numpy=
array([[2.1],
[2.1],[2.1],
[2.1]], dtype=float32)>

out = relu(𝑌@𝑋 + 𝑏)

In [171]:x@W+b
<tf. Tensor: id=526, shape=(4,1), dtype=float32, numpy=
array([[2.1],
[2.1],[2.1],
[2.1]], dtype=float32)>
In [172]: out=x@W+b In [173]: out=tf. nn. relu(out)
<tf. Tensor: id=530, shape=(4,1), dtype=float32, numpy=
array([[2.1],
[2.1],[2.1],
[2.1]], dtype=float32)>

2.6.6 运算类型

element-wise (元素相关)
- + - * \
matrix-wise (矩阵相关)
- @ matmul
dim-wise (维度相关)
- reduce_mean/max/min/sum

reduce_mean获得所有元素的均值
max/min 获得最大/小值元素
sum求和

2.6.7 范数

在这里插入图片描述
ord:指定p范数

import tensorflow as tf
a = tf.constant([[1.,2.],[1.,2.]])
tf.norm(a, ord=1)  # 1范数
<tf.Tensor: id=4, shape=(), dtype=float32, numpy=6.0>
tf.norm(a, ord=2)  # 2范数
<tf.Tensor: id=10, shape=(), dtype=float32, numpy=3.1622777>
tf.norm(a)  # ord不指定时,默认是2
<tf.Tensor: id=16, shape=(), dtype=float32, numpy=3.1622777>

我们也可以全手动地实现范数:

tf.sqrt(tf.reduce_sum(tf.square(a)))
<tf.Tensor: id=21, shape=(), dtype=float32, numpy=3.1622777>
# 指定维度求范数:

tf.norm(a, ord=2, axis=0)
<tf.Tensor: id=27, shape=(2,), dtype=float32, numpy=array([1.4142135, 2.828427 ], dtype=float32)>
tf.norm(a, ord=2, axis=1)
<tf.Tensor: id=33, shape=(2,), dtype=float32, numpy=array([2.236068, 2.236068], dtype=float32)>

参考:https://mp.weixin.qq.com/s?__biz=MzA4MjYwMTc5Nw%3D%3D&chksm=87941340b0e39a56e667ba54d9ef8897c41ceaa6ec8be4bacfd77a45743ee27a4db76cd8b7a1&idx=2&mid=2648932714&scene=21&sn=500485be159da8635016331dbbbb5e32#wechat_redirect

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shine.Zhang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值