tensowFlow基础语法

一、基本数据类型

(1)定义

tf.Tensor
scalar:1.1 标量
vector:[1.1],[1.1,2.2,…] 向量
matric:[[1.1,2.2],[3.3,4.4]…] 矩阵
tensor:rank >2

(2)特点

支持自动求导

(3)支持类型

int,float,double
bool
string

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'    #这句话是tensorflow少打印出一些信息
# tf.test.is_gpu_available()  #查看tensorflow-gpu安装是否成功
# a = tf.constant(1.0)+tf.constant(2.0)   #查看tensorflow-cpu安装是否成功
a = tf.constant(1)  #创建一个常量,常量是什么类型返回的tensor就是什么类型,比如1是int32,1.1是float32
print(a)
b = tf.constant(1.,dtype = tf.double)    #将自己创建的常量设置为float64,如果类型转换错误会报错
print(b)
c = tf.constant("hellow world",dtype = tf.string)
print(c)
d = tf.constant([True,False])   #bool值的创建

(4)属性

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'    #这句话是tensorflow少打印出一些信息

with tf.device('cpu'):  #将a存放在cpu上
    a = tf.constant([1])

with tf.device('gpu'):  #将b存放在gpu上
    b = tf.range(4)
print(a.device)
print(b.device)

aa = a.gpu()    #将a转换到gpu上
bb = b.cpu()    #将b转换到cpu上
print(aa.device)

bb = b.numpy()  #将b转换成numpy类型
print(b.shape)  #查看b的形状
print(b.ndim)   #查看b的维度,1.1是0维,[1.1]是一维

print(tf.is_tensor(b))  #判断b是否是一个tensor
print(a.dtype)  #返回a的数据类型

(5)数据类型转换

import tensorflow as tf
import os
import numpy as np

a = np.arrane(5)    #=array((0,1,2,3,4)]
aa = tf.convert_to_tensor(a)    #将a转换成tensor
#aa = tf.convert_to_tensor(a,dtype=tf.int32) #将a转换为指定tensor的数据类型
tf.cast(aa, dtype=tf.float32)   #cast为类型转换工具,将整型转换为浮点型
aaa = tf.cast(aa, dtype=tf.double)
tf.cast(aaa,dtype=tf.int32) #任意数据类型可以相互转换

#tensor => numpy
a.numpy()   #将a转换成numpy
int(a)  #将a转换成numpy的第二种方法
float(a)    #将a转换成numpy的第二种方法

(六)tf.Variable()方法

#tf.Variable
a = tf.range(5)
b = tf.Variable(a, name='input_data')   #用Variable这个方法包了一下后,b将可以自动求导,并且拥有name和trainable两个属性
b.name
b.trainable #可以训练,就是会记录梯度

二、创建tensor

(一)从numpy或list转换得到

tf.convert_to_tensor(np.ones[2,3]) #创造一个全1的tensor
tf.convert_to_tensor(np.zeros[2,3]) #创造一个全0的tensor
tf.convert_to_tensor([1,2])

(二)tf.zeros() 里面的参数表示形状

tf.zeros([]) —— 0.0
tf.zeros([1]) —— [0.]
tf.zeros([2,2]) —— [[0.,0.],
[0.,0.]]

(三)tf.fill([],0)

第一个参数是填充的形状,第二个参数表示填充的数值

(四)正态分布:tf.random.normal([2,2],mean=1,stdddev=1)

第一个参数是填充的形状,第二个参数是均值,第三个参数是方差

(五)均匀分布:tf.random.uniform([2,2],minval=0,maxval=1)

第一个参数是填充的形状,第二个是采样的起始值,第三个参数是采样的终止值

三、tensor的维度

Single task:[b,h,w,3] b表示有多少张图片;h,w表示图片大小;3表示图片的颜色
meta-learning:[task_b,b,h,w,3]

四、tensor的索引与切片

索引

直接索引:a [0][0][0][0] —— 不建议使用
类似numpy方式索引:a[0,0,0,0]

切片

::的用法

切片返回的是一个vector
a[-1:]
start: end:step —— 每隔step进行采样
::step —— 从开始到结尾隔step采样
::-1 —— 表示倒着采样,每次采一个
::-2 —— 表示倒着采样,每隔2个采一次
2::-2 —— 表示从第三个元素开始倒着采到第一个元素,每隔两个采一次

… 的用法

…可以表示任意行,也就是任意个冒号的省略
a[0,:,:,:] —— 可以表示为a[0,…]
a[:,:,:,0] —— 可以表示为a[…,0]

tf.gather()

tf.gather_nd()
aa = tf.gather()
今后补充

五、维度变化

(1)维度变化

view改变

a = tf.random.normal([4,28,28,3])
tf.reshape(a,[4,-1]) —— 将a打平
tf.reshape(tf.reshape(a,[4,-1]
,[4,14,56,33]
).shape
—— TensorShape([4,14,56,3])

content改变

【h,w】——》【w,h】
a = tf.random.normal((4,3,2,1))
a.shape —— TensorShape([4,3,2,1])
tf.transpose(a).shape —— TensorShape([1,2,3,4])
指定维度content交换:tf.transpose(a,perm=[0,1,3,2]).shape —— TensorShape([4,3,1,2]),perm[0,1,3,2]就是指定放原维度的下标

(2)增加维度

a = tf.random.normal([4,35,8])
tf.expand_dims(a,axis=0).shape —— TensorShape([1,4,35,8])
tf.expand_dims(a,axis=3).shape —— TensorShape([4,35,8,1])
axis参数表示在a的第几个维度增加,axis为负数,在负数的后面增加

(3)减小维度

仅当shape = 1时
b = tf.zeros([1,2,1,1,3])
tf.squeeze(a).shape —— TensorShape([2,3)]
tf.squeeze(a,axis=-2).shape —— TensorShape([2,1,1,3)]
tf.squeeze(a).shape —— TensorShape([1,2,1,3)]

(4)维度扩张

broadcast

功能:a和b的维度不一致,就在不足的维度增加维度;a和b维度不一致的话不能broadcast;默认先从右边对齐
a——[4,32,14,14]
b——[14]
broadcast步骤:1、b变成[1,1,1,14];2、b变成[4,32,14,14]
如果不能按照上面的步骤,就不能broadcast
注意:维度是1才能扩展,比如b是[2,32,14,14]就不能和a进行运算
相当于为高纬度增加低纬度的值

broadcast的实现
#自动调用tf.braodcast
x=tf.random.normal([4,32,32,3])
(x + tf.random.normal([3])).shape   #TensorShape([4,32,32,3]) 自动进行broadcast

(x+tf.random.normal([32,32,1])).shape		#TensorShape([4,32,32,3]) 自动进行broadcast

#手动调用broadcast
b = tf.broadcast_to(tf.random.normal([4,1,1,1]),[4,32,32,3])
b.shape		#TensorShape([4,32,32,3])
利用其它函数实现broadccast
#此总方法耗费内存更大
a=tf.ones([3,4])
a2 = tf.expand_dim(a,axis=0)
a2.shape 	#TensorShape([1,3,4])
a2 = tf.tile(a2,[2,1,1])	#复制,2表示复制2次,1表示复制一次
a2.shape 	#TensorShape([2,3,4])

不同矩阵间的数学运算

+、-、*、/

对应元素加减乘除

**(多少次方)、pow(多少次方)、square(平方)

b的三次方:b**3 或者tf.pow(b,3)

sqrt(开平方)
//(整除)、%(取余)
exp、log

exp、log表示以自然常数e为底的指数函数

@、matmul——矩阵乘法

[b,3,4]@[b,4,5]
得到[b,3,5] —— 表示对b个矩阵进行乘法
a和b都是[2,2]
a@b或者tf.matul(a,b) —— 表示a乘以b

reduce_mean/max/min/sum

对某个维度求值

(5)、维度合并

1、 concat —— 在原来维度上相加

要求:除了要拼接的维度不等,其它维度的数值都要相等
a = tf.ones([4,35,8]
b = tf.ones([2,35,8]
c = tf.concat([a,b],axis = 0) —— TensorShape([6,35,8)]表示维度的合并,axis表示在第几维合并

2、stack —— 创建新的维度

要求:所有维度的数值都要相等
a = tf.ones([4,35,8]
b = tf.ones([4,35,8]
tf.stack([a,b], axis=0).shape —— TensorShape([2,4,35,8]),axis表示在第几维创造维度
tf.stack([a,b], axis=3).shape —— TensorShape([4,35,8,2])

3、unstack切割维度

与stack正好相反,要拆分的维度数值是多少就拆分成多少个
c.shape —— TensorShape([2,4,35,8])
aa,bb = tf,unstack(c, axis = 0)
aa.shape —— TensorShape([4,35,8])
bb.shape —— TensorShape([4,35,8])

res = tf.unstack(c, axis = 3)
res[0].shape —— TensorShape([2,4,35)]
res[7].shape —— TensorShape([2,4,35)]

4、split 打散

可以指定拆分成组
c.shape —— TensorShape([2,4,35,8])
res = tf.split( c ,axis =3 , num_or_size_splits = 2)
len(res) —— 2
res[0].shape —— TensorShape([[2,4,35,4])

c.shape —— TensorShape([2,4,35,8])
res = tf.split( c ,axis =3 , num_or_size_splits = [2,2,4])
len(res) —— 3
res[0].shape —— TensorShape([[2,4,35,2])
res[2].shape —— TensorShape([[2,4,35,4])

六、数据统计

tf.norm()

a = tf.ones([2,2])
tf.norm(a) —— 2 其实就是tf.sqrt( tf.reduce_sum( tf.square(a))) 的值
b = tf.ones([4,28,28,3])
tf.norm(b) —— 96.99484其实就是tf.sqrt( tf.reduce_sum( tf.square(b))) 的值

tf.reduce_min()/max()/mean()

a = tf.random.normal([4,10])
tf.reduce_min(a) —— 求出举证a里最小的值
tf.reduce_min(a, axis = 1)—— 求出每一行的最小值

argmax()/argmin()

得到最大值和该最大值元素的所在位置
a.shape —— TensorShape([4,10])
tf.argmax(a ) —— array([0,0,2,3,1,3,0,1,2,0]),不填默认axis = 0
tf.argmax(a,axis = 1 ) —— array([0,0,2,3])

tf.equal()

a = tf.constant([1,2,3,4,5])
b = tf.range(5)
res = tf.equal(a,b) —— array([False,False,False,False,False])
rr = tf.cast(res, dtype = tf.int32) —— 将res转换成整型
tf.reduce_sum(rr) —— 将结果求和

tf.unique()

剔除重复项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值