DL3-TensorFlow(1.x)入门

1、TensorFlow 的Hello World

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

# 创建一个常量运算,将其作为一个节点加入到默认计算图中
hello = tf.constant("Hello World")

# 创建一个对话
sess = tf.Session()

#运行并获得结果
print(sess.run(hello))
b'Hello World'

输出前面的’b’ 表示Bytes literals(字节文字)

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

TensorFlow = Tensor + Flow

Tensor 张量

数据结构:多维数组

Flow 流

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

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

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

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

计算图是一个有向图,由以下内容构成:

• 一组节点,每个 节点都代表一个 操作,是一种 运算

• 一组有向边,每条 边代表节点之间的 关系(数据传递和控制依赖)

TensorFlow有两种边:

• 常规边(实线):代表数据依赖关系。一个节点的运算输出成为另一个节点的输入,两个节点之间有tensor流动( 值传递)

• 特殊边(虚线):不携带值,表示两个节点之间的 控制相关性。比如, happens- - before 关系,源节点必须在目的节点执行前完成执行

node1 = tf.constant(3.0,tf.float32,name="node1")
node2 = tf.constant(4.0,tf.float32,name="node1")
node3 = tf.add(node1,node2)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u14X61zp-1588692296058)(attachment:image.png)]

print(node3)
# 输出的结果不是一个具体的数字,而是一个张量的结构
Tensor("Add_1:0", shape=(), dtype=float32)

创建计算图只是建立静态计算模型

执行对话才能提供数据并获得结果

# 建立对话并显示运行结果
sess = tf.Session()
print("运行sess.run(node1)的结果:",sess.run(node1))
运行sess.run(node1)的结果: 3.0
# 更新变量并返回计算结果
print("运行sess.run(node13)的结果:",sess.run(node3))

# 关闭session
sess.close()
运行sess.run(node13)的结果: 7.0

3、张量

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

Tensor(“Add:0”, shape=(), dtype=float32)

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

获取张量的元素

tens1 = tf.constant([[[1,2],[2,3]],[[3,4],[5,6]]])
sess = tf.Session()
print(sess.run(tens1)[1,1,0])
print(sess.run(tens1)[1,0])
sess.close()
5
[3 4]

4、Operation 操作

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

tf.reset_default_graph()   #清除default graph和不断增加的节点


a = tf.Variable(1, name="a")# a
b = tf.add(a,1,name="b")# b=a+1
c = tf.multiply(b,4,name="c")#c=b*4
d = tf.subtract(c,b,name="d")#d=c-b

#logdir改为自己机器上的合适路径
logdir = 'D:/log'

#生成一个写日志的writer,并将当前的TensorFlow计算图写入日志
writer = tf.summary.FileWriter(logdir,tf.get_default_graph())
writer.close()
WARNING:tensorflow:From C:\Users\PC\Anaconda3\lib\site-packages\tensorflow_core\python\ops\resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.

5、Session 会话

会话拥有并管理TensorFlow程序运行时的所有 资源

当所有计算完成之后需要 关闭会话帮助系统

(1)会话的模式1

# 定义计算图
tens1 = tf.constant([1,2,3])

#创建一个会话
sess = tf.Session()

#使用这个创建好的会话得到关心的运算的结果,比如可以调用sess.run(result)
#来得到张量result的取值
print(sess.run(tens1))

# 关闭会话使得本次运行使用到的资源可以被释放
sess.close()
[1 2 3]

需要明确调用 Session.close()函数来关闭会话并释放资源

当程序因为异常退出时,关闭会话函数可能就不会被执行从而导致资源泄漏

# 定义计算图
tens1 = tf.constant([1,2,3])

#创建一个会话
sess = tf.Session()

try:
    #使用这个创建好的会话得到关心的运算的结果,比如可以调用sess.run(result)
    #来得到张量result的取值
    print(sess.run(tens1))

except:
    print("Exception")
    
finally:    
# 关闭会话使得本次运行使用到的资源可以被释放
    sess.close()
[1 2 3]

(2)会话的模式2

node1 = tf.constant(3.0,tf.float32,name="node1")
node2 = tf.constant(4.0,tf.float32,name="node2")
result = tf.add(node1,node2)

#创建一个会话,并通过Python中的上下文管理器来管理这个会话
with tf.Session() as sess:
    #使用这创建好的会话来计算关心的结果
    print(sess.run(result))
    
# 不需要再调用 Session.close()函数来关闭会话
# 当上下文退出时会话关闭和资源释放也自动完成了
7.0

TensorFlow不会自动生成默认的会话,需要手动指定

当默认的会话被指定之后可以通过 tf.Tensor.eval 函数来计算一个张量的取值

node1 = tf.constant(3.0,tf.float32,name="node1")
node2 = tf.constant(4.0,tf.float32,name="node2")
result = tf.add(node1,node2)

sess = tf.Session()
with sess.as_default():
    print(result.eval())
7.0
sess = tf.Session()
print(sess.run(result))
print(result.eval(session=sess))
7.0
7.0

(3)交互式环境下设置默认会话

在交互式环境下,Python脚本或者Jupyter编辑器下,通过设置默认会话来获取张量的取值更加方便

tf.InteractiveSession 使用这个函数会自动将生成的会话注册为默认会话

node1 = tf.constant(3.0,tf.float32,name="node1")
node2 = tf.constant(4.0,tf.float32,name="node2")
result = tf.add(node1,node2)

sess = tf.InteractiveSession()

print(result.eval())
sess.close()
7.0

6、常量与变量

(1) 常量

在运行过程中值不会改变的单元,在TensorFlow中无须进行初始化操作

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

a = tf.constant(1)
b = tf.constant(2)
c = tf.add(a,b)
sess = tf.Session()
c =sess.run(c)
print(c)
sess.close()


3

(2) 变量

在运行过程中值会改变的单元,在TensorFlow中须进行初始化操作

创建语句:

name_variable = tf.Variable

个别变量初始化:

init_op = name_variable.initializer ()

所有变量初始化:

init_op = tf.global_variables_initializer
node1 = tf.Variable(3.0,tf.float32,name="node1")
node2 = tf.Variable(4.0,tf.float32,name="node2")
result = tf.add(node1,node2,name="add")

sess = tf.Session()

# 变量初始化:定义
init = tf.global_variables_initializer()
#执行
sess.run(init)

print(sess.run(result))

7.0

(3) 变量的赋值

TensorFlow中的变量定义后,一般 无需人工赋值,系统会根据算法模型,训练优化过程中 自动调整变量对应的数值

epoch = tf.Variable(0,name=‘epoch’,trainable=False)

特殊情况需要人工更新的,可用变量赋值语句

变量更新语句:
update_op = tf.assign(variable_to_be_updated, new_value)
# 通过变量赋值输出1、2、3...10
# 并求和
import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

value = tf.Variable(0,name="value")
sum_value = tf.Variable(0,name="sum_value")
one = tf.constant(1)
new_value = tf.add(value,one)# new_value = value + one
update_value = tf.assign(value,new_value)# 这个节点:value = new_value

# 变量初始化:定义
init = tf.global_variables_initializer()

# 上下文执行方式
with tf.Session() as sess:
    sess.run(init)
    for i in range(10):
        sess.run(update_value)
        print(sess.run(value))
        sum_value = sum_value + sess.run(value) 
    print(sess.run(sum_value))


1
2
3
4
5
6
7
8
9
10
55

7、占位符 placeholder

TensorFlow中的 Variable 变量类型,在定义时需要初始化,但有些变量定义时并不知道其数值,只有当真正开始运行程序时,才由外部输入,

比如训练数据,这时候需要用到 占位符

• tf.placeholder 占位符,是TensorFlow中特有的一种数据结构,类似动态变量,函数的参数、或者C语言或者Python语言中格式化输出时的“%”占位符

TensorFlow占位符Placeholder,先定义一种数据,其参数为数据的Type和Shape

占位符Placeholder的函数接口如下:

tf.placeholder(dtype, shape=None, name=None)
x = tf.placeholder(tf.float32,[2,3],name = "tx")
# 此代码生成一个2x3的二维数组,矩阵中每个元素的类型都是tf.float32,内部对应的符号名称是txt

(1) Feed 提交数据和 Fetch 提取数据

如果构建了一个包含placeholder操作的计算图,当在session中调用run方法时,placeholder占用的变量必须通过 feed_dict参数传递进去,否则报错

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

a = tf.placeholder(tf.float32,name = "a")
b = tf.placeholder(tf.float32,name = "b")
c = tf.multiply(a,b,name="c")

#init = tf.global_variables_initializer()
with tf.Session() as sess:
#    sess.run(init)
    
    #通过feed_dict的参数传值,按字典格式
    result = sess.run(c,feed_dict={a:8.0,b:3.5})
    
    print(result)
28.0

多个操作可以通过一次Feed完成执行

a = tf.placeholder(tf.float32,name = "a")
b = tf.placeholder(tf.float32,name = "b")
c = tf.multiply(a,b,name="c")
d = tf.subtract(a,b,name="d")
#init = tf.global_variables_initializer()
with tf.Session() as sess:
#    sess.run(init)
    
    #通过feed_dict的参数传值,按字典格式
    result = sess.run([c,d],feed_dict={a:[3,4,5],b:[1,2,3]})    # [] 表示列表
    print(result)
    print(result[0])
    print(result[1])
[array([ 3.,  8., 15.], dtype=float32), array([2., 2., 2.], dtype=float32)]
[ 3.  8. 15.]
[2. 2. 2.]
# 分开赋值
a = tf.placeholder(tf.float32,name = "a")
b = tf.placeholder(tf.float32,name = "b")
c = tf.multiply(a,b,name="c")
d = tf.subtract(a,b,name="d")

with tf.Session() as sess:
    
    #通过feed_dict的参数传值,按字典格式
    rc,rd = sess.run([c,d],feed_dict={a:[3,4,5],b:[1,2,3]})    # [] 表示列表
    print("Value of ‘+’ = ",rc,"Value of ‘-’ = ",rd)
Value of ‘+’ =  [ 3.  8. 15.] Value of ‘-’ =  [2. 2. 2.]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这段代码看起来像是C语言编写的,主要是针对DL645B协议进行数据处理的。下面是对代码的分析: 1. if((DITemp==0xFE0001)||(DITemp==0xFE0002)||(DITemp==0xFE0003)):如果DITemp等于0xFE0001或者0xFE0002或者0xFE0003,则执行if语句中的代码。 2. if(RxFrm->Len != (12 + 5*sizeof(u16))) return(DL645B_ERRINFO_DATA):如果接收到的数据帧长度不等于12加上5个u16数据类型所占的长度,则返回数据错误。 3. fnDl645File_Write(Dl645FileId_GeneralPara, Dl645FileItemInfoOffAddr_GeneralPara_OutputPara + 16 + (5*sizeof(u16)) * (RxFrm->UDat.DI0 - 1), &RxFrm->UDat.Dat[8], 5*sizeof(u16)):将接收到的数据帧中的8号字节之后的5个u16数据类型写入到某个文件中的指定位置。 4. memset(&Dl645Output.PriPara, 0, sizeof(Dl645Output.PriPara) - 2):将Dl645Output.PriPara结构体中的所有成员变量都清零,但是最后两个字节不清零。 5. return(DL645B_ERRINFO_OK):返回数据处理成功。 6. if(DITemp==0x00f91201):如果DITemp等于0x00f91201,则执行if语句中的代码。 7. if((RxFrm->UDat.Dat[0] == 0x03)&&(RxFrm->UDat.Dat[1] == 0x43)&&(RxFrm->UDat.Dat[2] == 0x56)&&(RxFrm->UDat.Dat[3] == 0x98));如果接收到的数据帧中的第0、1、2、3个字节分别等于0x03、0x43、0x56、0x98,则不做处理;否则返回密码错误。 8. else if(DITemp==0x001503);如果DITemp等于0x001503,则不做处理。 9. else:如果DITemp既不等于0x00f91201,也不等于0x001503,则执行else语句中的代码。 10. if(!(Dl645Bkgrd.PubData.MtSta.MtSta3.StaBit.PrgEnable)) return(DL645B_ERRINFO_PSW):如果某个条件不成立,则返回密码错误。 11. err = fnDl645Secret_Verify(0x04, RxFrm->UDat.Dat[0], &RxFrm->UDat.Dat[1]):调用fnDl645Secret_Verify函数进行密码验证。 12. if(err != SUCCESS) return(DL645B_ERRINFO_PSW):如果密码验证失败,则返回密码错误。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Cheeky_man

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

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

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

打赏作者

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

抵扣说明:

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

余额充值