第一节:tensorflow 数据类型-1
- list
- np.array,问题:不支持gpu计算和自动求导
- tf.tensor, 偏重深度网络的计算
what is tensor
代表deep learning中所有数据类型,tensor经过各种运算在nn中流动
tensor的数据类型
- int,float,double
- bool
- string
创建数据
创建常量
tf.constant(1.,dtype=tf.int32)
tf.constant([True,Flase])
tensor property
with tf.device("cpu")
a=tf.constant([1])
with tf.device("gpu")
b=tf.range(4)
# cpu和gpu的护转移
bb=b.cpu()
aa=a.gpu()
#会自动根据数据类型选择cpu和gpu,numpy只能在cpu中使用
#把tensor转为numpy
b.numpy()
#查看tensor的shape
b.shape
b.ndim#输出维度
tf.rank(b)#返回tensor,内容为dimension
check tensor type
a=tf.constant([1.])
b=tf.constant([True,False])
c=tf.constant("hello world")
d=np.arrange(4)
isinstance(a,tf.Tensor)
tf.is_tensor(b)
a.dtype,b.dtype
a.dtype==tf.float32
convert
a=np.arange(5)
aa=tf.convert_to_tensor(a)
aa=tf.convert_to_tensor(a,dtype=tf.int32)
tf.cast(aa,dtype=tf.float32) #指定cast的dtype就可以
bool和int
b=tf.constant([0,1])
tf.cast(b,dtype=tf.bool) #0转为false,1转为true
bb=tf.cast(b,dtype=tf.bool)
tf.Variable
a=tf.range(5)
b=tf.Variable(a)
b=tf.Variable(a,name="input_data")
b.trainable#True
isinstance(b,tf.Tensor)#False
isinstance(b,tf.variable)#True
tf.is_tensor(b)#True
变量可以用来自动求导
to numpy
a=tf.ones([])
a.numpy
int(a)#直接把tensor转为scalar
float(a)#直接把tensor转为scalar
第二节:创建tensor
- from numpy ,list
- zeros,ones
- fill
- random
- constant
- application
1、from numpy , list
tf.convert_to_tensor(np.ones([2,3])) #numpy转换
tf.conver_to_tensor([[1],[2.]]) #如果有一个为浮点型,那么默认为浮点型,list转换
2、tf.zeros
tf.zeros([])
tf.zeros([2,2])#[2,2]理解为一个shape
tf.zeros([2,3,3])#shape=(2,3,3)
tf.zeros_like
根据输入的shape创造一个全为0的tensor
a=tf.zeros([2,3,3])
tf.zeros(a.shape)
3、tf.ones
tf.ones([])#创建一个标量,数值为1
one_like和ones的使用和zeros相同
对于线性回归,初始化w为1,b为0比较好
4、fill
填充任意元素的值,但只有一个
tf.fill([2,2],0)
5、Normal
tf.random.normal([2,2],mean=1,stddev=1)
tf.random.normal([2,2]) #不指定生成N(0,1),两行两列
tf.random.trunacated_normal([2,2],mean=0,stddev=1) #截断正态分布,
梯度接近于0时叫做梯度消失,为了避免这个现象,使用truncated
6、uniform
tf.random.uniform([2,2],minval=0,maxval=1)#也可以指定dtype
random permutation
- 生成0,63的索引
- 使用shuffle乱序
a=tf.gather(a,idx)
7、tf.constant 与convert的功能相同
tf.constant(1)
tf.constant([1,2.],[2,4.])
2、typical dim data
scalar,标量
- []
- loss
- accuracy
loss 计算例子:
tf.one_hot(y,depth=10)#one-hot encoding
tf.keras.losses.mse(y,out)#compute mse
loss=tf.reduce_mean(loss)求loss平均
vector 向量
net=layer.Dense(10)
net.build((4,8)) #升维,8->10
net.kernel
net.bias#shape=(10,0)
matrix 矩阵
将[4,784]输入一个10维的nn,降维后变为[4,10], w 的shape为[784,10]