二、tensorflow基础

(一) 数据类型

  • 标量
  • 向量
  • 矩阵
  • 张量
    维度大于2,统称为张量。
tf.constant([List],[],...)
  • 字符串
tf.constant('strings')
tf.strings.lower()
tf.strings.join()
tf.strings.length()
tf.strings.split()
  • 布尔
tf.constant(True)
tf.constant([True,False])
# tensorflow的布尔类型与python中的不对等。

(二) 数值精度

# 1.读取精度
a = tf.constant([1.,2.],dtype=tf.float32)
print(a.dtype)
# 2.精度类型转换
tf.cast(a,dtype=tf.int32)
# 3.布尔类型与整型转换
b = tf.constant([True,True,False])
tf.cast(b,dtype=tf.int32)
# 在tensorflow中将非0数字都作为True

(三) 待优化张量

# tf.Variable()能够将普通张量转化为待优化张量
a = tf.constant([1,2,3,4])
aa = tf.Variable(a)
print(a.name,a.trainable)
# or
a = tf.Variable([1,2,3,4],[4,5,6,7])

(四) 创建张量

  • 从numpy、list中创建
tf.convert_to_tensor([1,2.])
tf.convert_to_tensor(np.array([[2,3],[4,5]]))
  • 常见全0全1张量
tf.zeros([]);tf.ones([])
# []为张量shape
a = tf.zeros([2,3])
b = tf.ones([3,3])
tf.zeros_like(a)
tf.ones_like(b)
  • 创建自定义张量
# tf.fill(shape,value)
tf.fill([2,3],10)
  • 创建已知分布的张量
# 1.高斯分布或正态分布
tf.random.normal(shape,mean,stddev)
# 2.创建均匀分布
tf.random.uniform(shape,minval,maxval,dtype=tf.float32)
# 3.创建整型的均匀分布,必须指定maxval,通知dtype=tf.int32
tf.random.uniform([2,2],maxval=10,dtype=tf.int32)
  • 创建序列
tf.range(a,b,delta=1)

(五) 索引和切片

  • 索引
a = tf.random.normal([4,32,32,3])
# a 代表有4张大小为32*32的图片,通道为3,即色彩RGB
# 1.取第1张图片
a[0]
# 2.取第1张图片的第2行
a[0][1]
# 3.取第1张图片的第2行第3列像素
a[0][1][2]
# 4.取第2张图片的第3行第4列的像素,B通道
a[1][2][3][2]
# 5.更简单的方法是
a[1,2,3,2]
  • 切片
    start : end : step
# 1.读取第2,3张图片
a[1:3]
# 2.读取所有图片,隔行隔列采样,所有通道信息
a[:,0:28:2,0:28:2,:]

(六) 维度变换

基本的维度变化包含以下:
1.改变视图 : reshape
2.出入新维度:expand_dims
3.删除维度:squeeze
4.交换维度:transpose
5.赋值数据:tile

  • reshape
x = tf.range(10)
x = tf.reshape(x,[1,5,2,1])
x = tf.reshape(x,[2,-1])
# -1表示当前轴上长度需要根据视图种元素不变的法则自动推导,从而方便书写。比如上面的-1可以推导为:1*5*2*1/2=5
  • 增删维度
x = tf.random.uniform([28,28],maxval=10,dtype=tf.int32)
# 1.tf.expand_dims(x,axis)可以增加维度
tf.expand_dims(x,axis=0)
# 2.tf.squeeze(x,axis=1)
  • 交换维度
# tf.transpose(x,perm),perm表示新维度的顺序List.
  • 数据复制
# 数据复制,tf.tile(x,multiples)

(七) Broadcasting

  • Broadcasting
# tf.broadcast_to(x,new_shape)

(八) 数学运算

  • 加减乘除

tf.add, tf.subtract, tf.multiply, tf.divide
也可直接+ - * /

  • 乘方
# tf.pow(x,a)
  • 指数对数

换底公式
l o g a x = l o g e x l o g e a log_ax = \frac{log_ex}{log_ea} logax=logealogex

x = tf.constant([1,2,3])
tf.pow(a,x)
x = tf.exp(x) #以e为底数
tf.math.log(x) # 它是以e为底数
# 如何希望用其他底数,需要用到换底公式
  • 矩阵相乘
tf.matmul(a,b)
# 其中,a的最后一个维度必须等于b的最后第二个维度
# 矩阵相乘支持Broadcasting机制
a = tf.random.normal([2,32,16])
b = tf.random.normal([32,8])
c = tf.matmul(a,b)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值