DL2-TensorFlow2.0编程基础

import tensorflow as tf
tf.__version__
'2.0.0'
tf.__path__
['C:\\Users\\PC\\Anaconda3\\lib\\site-packages\\tensorflow']

1、Tensor张量

node1 = tf.constant([[3.0,1.5],[2.5,6.0]],tf.float32)
node2 = tf.constant([[4.0,1.0],[4.5,4.0]],tf.float32)
node3 = tf.add(node1,node2)

node3#输出一个Tensor张量
<tf.Tensor: id=2, shape=(2, 2), dtype=float32, numpy=
array([[ 7. ,  2.5],
       [ 7. , 10. ]], dtype=float32)>
node1#输出一个Tensor张量
<tf.Tensor: id=0, shape=(2, 2), dtype=float32, numpy=
array([[3. , 1.5],
       [2.5, 6. ]], dtype=float32)>
# 输出运算结果Tensor的值
print(node3.numpy())
[[ 7.   2.5]
 [ 7.  10. ]]

2、TensorFlow的基本概念

(1) TensorFlow 名称的含义

TensorFlow = Tensor + Flow

Tensor 张量

数据结构:多维数组

Flow 流

计算模型:张量之间通过计算而转换的过程

TensorFlow是一个通过 计算图的形式表述计算的编程系统

每一个计算都是计算图上的一个节点

节点之间的边描述了计算之间的关系

(2)张量的概念

在TensorFlow中,所有的数据都通过张量的形式来表示

从功能的角度,张量可以简单理解为多维数组

零阶张量表示 标量(scalar),也就是 一个数;

一阶张量为 向量(vector),也就是 一维数组;

n 阶张量可以理解为一个n n 维数组;

张量并没有真正保存数字,它 保存的是计算过程

(3)张量方法和属性

标识号( id )

系统自动维护的唯一值

形状( shape )

张量的维度信息

类型 ( dtype )

每一个张量会有一个唯一的类型,TensorFlow会对参与运算的所有张量进行类型的检查,发现类型不匹配时会报错

值 ( value )

通过numpy()方法获取,返回Numpy.array类型的数据

print(node3.shape)
print(node3.dtype)
(2, 2)
<dtype: 'float32'>

(4)张量的形状

三个术语描述张量的维度: 阶(rank)、 形状(shape) 、 维数(dimension number)

scalar = tf.constant(100)
vector = tf.constant([1,2,3,4,5])
matrix = tf.constant([[1,2,3], [4,5,6]])
cube_matrix = tf.constant([[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]])

print(scalar.shape)
print(vector.shape)
print(matrix.shape)
print(cube_matrix.get_shape())
#(D0,D1,…,Dn-1) 
#表中D0表示第0维元素的个数,Di表示Di维元素的个数
()
(5,)
(2, 3)
(3, 3, 1)
# 输出张量里某个元素的值
print(cube_matrix.numpy()[1])
print(cube_matrix.numpy()[1,2,0])
[[4]
 [5]
 [6]]
6
# 每一个张量会有一个唯一的类型,TensorFlow会对参与运算的所有张量进行类型的检查,发现类型不匹配时会报错
a = tf.constant([1,2])
b = tf.constant([1.0,2.0])
print(tf.add(a,b))  #运行报错
---------------------------------------------------------------------------

InvalidArgumentError                      Traceback (most recent call last)

<ipython-input-14-3e169da0c1ca> in <module>
      2 a = tf.constant([1,2])
      3 b = tf.constant([1.0,2.0])
----> 4 print(tf.add(a,b))


~\Anaconda3\lib\site-packages\tensorflow_core\python\ops\gen_math_ops.py in add(x, y, name)
    388       else:
    389         message = e.message
--> 390       _six.raise_from(_core._status_to_exception(e.code, message), None)
    391   # Add nodes to the TensorFlow graph.
    392   try:


~\Anaconda3\lib\site-packages\six.py in raise_from(value, from_value)


InvalidArgumentError: cannot compute Add as input #1(zero-based) was expected to be a int32 tensor but is a float tensor [Op:Add]

在TensorFlow中可以通过tf.cast()进行数据类型转换

a = tf.constant([1,2])
b = tf.constant([1.0,2.0])

a = tf.cast(a,tf.float32)   #数据类型转换
print(tf.add(a,b))  
print(tf.add(a,b).numpy())  
tf.Tensor([2. 4.], shape=(2,), dtype=float32)
[2. 4.]

3、TensorFlow2 的常量与变量

(1)常量constant

在运行过程中值不会改变的单元

创建语句:

tf.constant(

value,

dtype=None,

shape=None,

name=‘Const’

)

在创建常量时只有value值是必填的,dtype等参数可以缺省,会根据具体的value值设置相应的值
a = tf.constant([1,2])
a
<tf.Tensor: id=22, shape=(2,), dtype=int32, numpy=array([1, 2])>
b = tf.constant([1,2],tf.float32)
b
<tf.Tensor: id=24, shape=(2,), dtype=float32, numpy=array([1., 2.], dtype=float32)>
c = tf.constant([1,2,3,4,5,6],shape = [2,3])
c
<tf.Tensor: id=30, shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]])>

(2)变量Variable

在运行过程中值可以被改变的单元

创建语句:

注意V是 大写字母

tf.Variable (

initial_value,

dtype=None,

shape=None,

trainable =True

name=’Variable’

)

v1 = tf.Variable([1,2])
v2 = tf.Variable([3,4],tf.float32)
v1,v2
# v2的数据类型没有改变:变量在创建时必须确定初始值,可以像定义常量一样
(<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([1, 2])>,
 <tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([3, 4])>)
# 也可以通过张量(常量)给变量赋初值
c = tf.constant(1)
v = tf.Variable(c)
c,v
(<tf.Tensor: id=64, shape=(), dtype=int32, numpy=1>,
 <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>)

在TensorFlow中变量和普通编程语言中的变量有着 较大 区别

TensorFlow中的变量是一种特殊的设计,是可以被机器优化过程中自动改变值的张量,也可以理解为 待优化的张量。

在TensorFlow中变量创建后, 一般无需人工进行赋值,系统会根据算法模型,在训练优化过程中 自动调整变量的值。

在变量的参数中,trainable参数用来表征当前变量是否需要被自动优化,创建变量对象时默认是启用自动优化标志。

(3)变量的赋值

与传统编程语言不同,TensorFlow中的变量定义后,一般 无需人工赋值,

系统会根据算法模型,训练优化过程中 自动调整变量对应的数值

后面在将机器学习模型训练时会更能体会,比如权重Weight变量w,经过多次迭代,会自动调整

特殊情况需要人工更新的,可用变量赋值语句assign()来实现

v = tf.Variable(5)
v.assign(v+1)
v
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=6>

TensorFlow还直接提供了assign_add()、assign_sub()方法来实现变量的加法和减法值更新

v1 = tf.Variable(5)
v2 = tf.Variable(4)
v1.assign_add(v2)
v2.assign_sub(v1)
v1,v2
(<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=9>,
 <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=-5>)

4、TensorFlow型 计算模型 – 计算图

(1)Tensorflow2的运行模式

TensorFlow 2 2代码的执行机制默认采用 Eager Execution(动态图执行机制)

TensorFlow 1.x版本代码的执行主要是基于传统的 Graph Execution(静态图执行)机制,存在着一定弊端,如入门门槛高、调试困难、灵活性差、无法使用 Python 原生控制语句等

静态图执行模式对于即时执行模式效率会更高,所以通常当模型开发调试完成,部署采用图执行模式会有更高运行效率。在TensorFlow 2里也支持已函数方式调用计算图。

TensorFlow 2 中执行或者开发TensorFlow 1.X代码,可以做如下处理:

1. 导入TensorFlow时使用 import tensorflow.compat.v1 as tf 代替import tensorflow as tf;
2. 执行tf.disable_eager_execution() 禁用TensorFlow 2默认的即时执行模式。
# 在TensorFlow2下执行TensorFlow 1.x版本代码
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
node1 = tf.constant(3.0,tf.float32,name="node1")
node2 = tf.constant(4.0,tf.float32,name="node1")
node3 = tf.add(node1,node2)
print(node3)

#由于是图执行模式,这时仅仅是建立了计算图,但它并没有执行
Tensor("Add_1:0", shape=(), dtype=float32)
node1,node2,node3
(<tf.Tensor 'node1_2:0' shape=() dtype=float32>,
 <tf.Tensor 'node1_3:0' shape=() dtype=float32>,
 <tf.Tensor 'Add_1:0' shape=() dtype=float32>)
# 执行计算图
sess = tf.Session() #建立对话并显示运行结果:分配资源
print("运行sess.run(node1)的结果:",sess.run(node1))
print("运行sess.run(node2)的结果:",sess.run(node2))
print("运行sess.run(node3)的结果:",sess.run(node3))
sess.close()# 关闭资源
运行sess.run(node1)的结果: 3.0
运行sess.run(node2)的结果: 4.0
运行sess.run(node3)的结果: 7.0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cheeky_man

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值