import tensorflow as tf
维度变化:
不改变内容的情况下改变数据形状:
=tf.reshape(原数据,想变成的形状)
例:
a=tf.random.normal([4,28,28,3])
### a.shape -> [4.28.28.3]
aa=tf.reshape(a,[4,784,3])
### aa.shape -> [4,784,3]
aaa=tf.reshape(a,[4,-1,3])
### aaa.shape -> [4,784,3]
### -1的意思是让系统计算此处应该为多少,仅能使用一次.
对数据进行矩阵转置:
=tf.transpose(原数据,perm=自定义转置)
perm的维度所对应的数是原数据同一维度的索引(有点不好理解,具体看例子)
例:
### a.shape -> [1,2,3,4]
b=tf.transpose(a)
### b.shape -> [4,3,2,1]
c=tf.transpose(a,perm=[0,1,3,2])
### c.shape -> [1,2,4,3]
增加维度:
tf.expand_dims(原数据,axis=维度)
减少维度:(仅当该维度的值为1时才可减少)
tf.squeeze(原数据,axis=维度)
例:
### a.shape -> [4,28,28,3]
b=tf.expand_dims(a,axis=0)
### b.shape -> [1,4,28,28,3]
c=tf.expand_dims(a,axis=4)
### c.shape -> [4,28,28,3,1]
d=tf.squeeze(b,axis=0)
### d.shape -> [4,28,28,3]
e=tf.squeeze(c,axis=-1)
### e.shape -> [4,28,28,3]
数学运算:
求ln a的值:
tf.math.log(x)
若要求logx(y)的值则可:
logx(y)=tf.math.log(y)/tf.math.log(x)
求e的x次方:
tf.exp(x)
求x的y次方:
tf.pow(x,y) == x**y
求x的1/2次方(即开根号):
tf.sqrt(x)
矩阵相乘:
tf.matmul(x,y) == x@y
例:
a.shape=[2,2]
b.shape=[2,2]
c=tf.matumul(a.b)
c.shape=[2,2]
a= A0 A1
A2 A3
b= B0 B1
B2 B3
c= C0 C1
C2 C3
C0=A0*B0+A1*B2
C1=A0*B1+A1*B3
C2=A2*B0+A3*B2
C3=A2*B1+A3*B3
合并与分割:
拼接(不增加维度):
在z维度上合并x和y: tf.concat([x,y],axis=z)
例:
### a.shape -> [4,28,28,3]
### b.shape -> [2,28,28,3]
c=tf.concat([a,b],axis=0)
### c.shape -> [6,28,28,3]
拼接(可增加维度,增加维度时要求其余维度的值都相同):
在z维度上合并x和y: tf.stack([x,y],axis=z)
例:
### a.shape -> [4,28,28,3]
### b.shape -> [4,28,28,3]
c=tf.stack([a,b],axis=0)
### c.shape -> [2,4,28,28,3]
分割(不可指定数量,可能不保留维度):
在y维度上分割x: tf.unstack(x,axis=y)
例:
### c.shape -> [2,4,28,28,3]
a,b=tf.unstack(c,axis=0)
### a.shape -> [4,28,28,3]
### b.shape -> [4,28,28,3]
分割(可指定数量,保留维度):
在y维度上将x分割成z份(可以用列表形式来表示): tf.split(x,axis=y,num_or_size_splits=z)
例:
### c.shape -> [2,4,28,28,3]
a=tf.split(c,axis=0,num_or_size_splits=2)
### len(a) -> 2
### a[0] == a[1]
### a[0].shape -> [1,4,28,28,3]
b=tf.split(c,axis=0,num_or_size_splits=[1,1,2])
### len(b) ->3
### b[0] == b[1]
### b[0].shape -> [2,4,28,28,1]
### b[2].shape -> [2,4,28,28,2]