tensorflow学习4 --Tensorflow的本身相关及其编程【张量、正态分布的初始化和初等变换】

TensorFlow中的计算图有三种,分别是静态计算图,动态计算图,以及Autograph
目前TensorFlow2默认采用的是动态计算图,即每使用一个算子后,该算子会被动态加入到隐含的默认计算图中立即执行得到结果(在TensorFlow1中,采用的是静态计算图,需要先使用TensorFlow的各种算子创建计算图,然后再开启一个会话Session,显式执行计算图)。
对于动态图的好处显而易见,它方便调试程序,让TensorFlow代码的表现和Python原生代码的表现一样,写起来就像写numpy一样,各种日志打印,控制流全部都是可以使用的,当然,这相对于静态图来讲牺牲了些效率,因为使用动态图会有许多次Python进程和TensorFlow的C++进程之间的通信,而静态计算图构建完成之后几乎全部在TensorFlow内核上使用C++代码执行,效率更高。此外静态图会对计算步骤进行一定的优化,剪去和结果无关的计算步骤。
如何理解TensorFlow计算图?


TF通过计算图将计算的定义和执行分隔开, 这是一种声明式(declaretive)的编程模型. 确实, 这种静态图的执行模式优点很多,但是在debug时确实非常不方便(类似于对编译好的C语言程序调用,此时是我们无法对其进行内部的调试), 因此有了Eager Execution 我们可以不必再等到see.run(*)才能看到执行结果, 可以方便在IDE随时调试代码,查看OPs执行结果.
Tensorflow2——Eager模式简介以及运用
应用Tensorflow2.0的Eager模式快速构建神经网络


TensorFlow2 编程教程

TensorFlow2 编程教程

python的with用法 这个叫上下文管理
with语句后面跟着的语句可以设定初始化执行一些函数,在退出时也可以执行一些函数
with语句后面跟着的as是变量,保存的是初始化后的返回值【没有返回值可以不用as】 with语句最后的冒号下的范围是中间过程执行的语句。
中间的语句执行完之后可以执行退出收尾的一些函数,比如 关闭文件、获取输出信息、获取错误信息。 ```python class Sample:
def enter(self):
print “In enter()”
return “Foo”
def exit(self, type, value, trace):
print “In exit()” def get_sample():
return Sample()

with get_sample() as sample:
print “sample:”, sample ```

输出的是

In enter()
sample: Foo
In exit()

python的with用法

定义常量,普通的tensor

idx = tf.constant(1)
# 输出 tf.Tensor(1, shape=(), dtype=int32)
tf.constant(1.) 
# 输出 tf.Tensor(1.0, shape=(), dtype=float32)
#这是不配拥有维度吗
tf.constant([1])
# 输出 tf.Tensor([1], shape=(1,), dtype=int32)
#这是一维有1个数,下面的例子里有一维里面没有数据tf.Tensor([], shape=(0,), dtype=float32)
tf.constant([True, False]) 
# 输出 tf.Tensor([ True False], shape=(2,), dtype=bool)
tf.constant('hello nick')

在tensorflow中,我们可以使用 tf.device() 指定模型运行的具体设备,可以指定运行在GPU还是CUP上,以及哪块GPU上。


with tf.device('cpu'):
  a = tf.constant([1])
with tf.device('gpu'):
  b = tf.constant([1])
  
a.device # 设备属性
a.gpu()  # cpu转gpu
a.numpy()  # 获取numpy数据类型
a.shape  # 获取a的属性
a.ndim  # 获取维度
tf.rank(a)  # 获取维度
a.name  # 1.+历史遗留问题

数据类型判断


isinstance(a,tf.Tensor) # 判断是否为tensor
tf.is_tensor(a)  # 判断是否为tensor
a.dtype,b.dtype,c.dtype  # 判断数据类型


# tf.Variable
a = tf.range(5)
b = tf.Variable(a, name='input_data') # tensor转为Variable后具有求导的特性,即自动记录a的梯度相关信息
b.name # input_data:0
b.trainable # True
isinstance(b,tf.Tensor)  # False
isinstance(b,tf.Variable)  # True
tf.is_tensor(b)  # True  # 推荐使用

创建Tensor

a = tf.constant([3])
tf.ones_like(a) 
# 输出 tf.Tensor([3], shape=(1,), dtype=int32)

tf.ones(0)
# 输出 tf.Tensor([], shape=(0,), dtype=float32)
tf.zeros(1)
# 输出 tf.Tensor([0.], shape=(1,), dtype=float32)
tf.ones([2])
# 输出 tf.Tensor([1. 1.], shape=(2,), dtype=float32)
# 加不加中括号是一样的。 因为已经限定了矩阵的内容是one 所以输入只能是改矩阵形状

tf.zeros([2,2])
# 输出 
tf.Tensor(
[[0. 0.]
 [0. 0.]], shape=(2, 2), dtype=float32)

tf.fill([2, 2], 0)# 还是这个好用,前面是形状,后面是填充值
# 输出 
tf.Tensor(
[[0 0]
 [0 0]], shape=(2, 2), dtype=int32)

创建数据分布

# 正态分布,均值为0,方差为0.5
tf.random.normal([2, 2], mean=0, stddev=0.5)
# 输出 
tf.Tensor(
[[ 0.26348853  0.92483073]
 [ 0.81219316 -0.52944314]], shape=(2, 2), dtype=float32)

# 均匀分布
tf.random.uniform([2, 2], minval=0, maxval=100, dtype=tf.int32)
# 输出 
tf.Tensor(
[[73 14]
 [84 77]], shape=(2, 2), dtype=int32)

a=tf.range(10)
# 输出 tf.Tensor([0 1 2 3 4 5 6 7 8 9], shape=(10,), dtype=int32)
idx = tf.random.shuffle(a) #将序列的所有元素随机排序
# 输出 tf.Tensor([4 2 0 5 1 8 9 6 3 7], shape=(10,), dtype=int32)

# 把0,1,2,3换成独热码
y = tf.range(4)
y = tf.one_hot(y, depth=10)
# 输出 
tf.Tensor(
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]], shape=(4, 10), dtype=float32)

# 计算标签和预测之间的均方误差。
out = tf.random.uniform([4, 10])
y = tf.range(4,8)
y = tf.one_hot(y, depth=10)
loss = tf.keras.losses.mse(y, out)
loss = tf.reduce_mean(loss)

高维数据选择

a = tf.ones([2, 3, 4, 6])
# 输出 倒数两个永远是行和列,然后限于输出形式,高维都是复制分组 很简单的
tf.Tensor(
[[[[1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]]

  [[1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]]

  [[1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]]]


 [[[1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]]

  [[1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]]

  [[1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]
   [1. 1. 1. 1. 1. 1.]]]], shape=(2, 3, 4, 6), dtype=float32)

print(a[0][1])
tf.Tensor(
[[1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1.]], shape=(4, 6), dtype=float32)

print(a[0].shape)
# 输出 (3, 4, 6)
print(a[0, ...].shape)	# 省略号
# 输出 (3, 4, 6)
print(a[0, ..., 2].shape)
# 输出 (3, 4)
print(a[:, 0, :, :] .shape)
# 输出 (2, 4, 6)
print(a[:, :, :-1, :3] .shape)
# 输出 (2, 3, 3, 3)
print(a[:, :, ::2, 0:6:2] .shape) # 起点:终点:步长
# 输出 (2, 3, 2, 3)

步长和倒序

a = tf.range(4)
[0, 1, 2, 3]
a[::-1]	#先取出全部数据再倒过来挨个输出
[3, 2, 1, 0]
a[::-2] #先取出全部数据再倒过来再隔一个输出
[3, 1]
a[2::-2]  #range(9)也是[2, 0] 
[2, 0]
a = tf.range(9)
print(a[3::-2])
[3 1]
a = tf.range(9)
print(a[4::-2])
[4 2 0]
a = tf.range(9)
print(a[::-2])
[8 6 4 2 0]
a = tf.range(9)
print(a[:2:-2])
[8 6 4]

在这里插入图片描述

reshape 重组数据

a = tf.random.normal([4, 28, 28, 3])   # a保存了4张图片,每张28行,28列,1个通道
tf.reshape(a, [4, -1, 3]).shape  # 4*(-1)*3 = 4*28*28*3
#输出 TensorShape([4, 784, 3])  # 把行和列的数据混在一起了
tf.reshape(a, [4, -1]).shape
#输出 TensorShape([4, 2352])
tf.reshape(tf.reshape(a, [4, -1]), [4, 14, 56, 3]).shape
#输出 TensorShape([4, 14, 56, 3]) # 随便重塑形状了就

# 转置
a = tf.random.normal((4, 3, 2, 1))
tf.transpose(a).shape
#输出 TensorShape([1, 2, 3, 4])
tf.transpose(a, perm=[0, 1, 3, 2]).shape  # 按照索引替换维度
#输出 TensorShape([4, 3, 1, 2])



Expand_dims(增加维度)

小贴士:
[1, 4, 35, 8] + [1, 4, 35, 8] = [2, 4, 35, 8]

a = tf.random.normal([4, 25, 8])
tf.expand_dims(a, axis=0).shape  # 索引0前
#输出 TensorShape([1, 4, 25, 8])
tf.expand_dims(a, axis=3).shape  # 索引3前
#输出 TensorShape([4, 25, 8, 1])

Squeeze(挤压维度)

小贴士:只删除维度为1的维度

tf.squeeze(tf.zeros([1,2,1,1,3])).shape
#输出 TensorShape([2, 3])
a = tf.zeros([1,2,1,3])
tf.squeeze(a,axis=0).shape
#输出 TensorShape([2, 1, 3])
tf.squeeze(a,axis=2).shape
#输出 TensorShape([1, 2, 3])

TensorFlow之设备(device)详解
浅谈keras中的目标函数和优化函数MSE用法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值