测试是否安装成功
jupyter里
import tensorflow as tf
tf.__version__
按Ctrl+Enter执行
'1.2.1'
即为成功。
import tensorflow as tf
# 创建一个常量运算, 将作为一个节点加入到默认计算图中
hello = tf.constant("Hello, World!")
# 创建一个TF对话
sess = tf.Session()
# 运行并获得结果
print(sess.run(hello))
b'Hello, World!'
'b’表示Bytes literals(字节文字)
计算图
TensorFlow = Tensor + Flow
Tensor张量
数据结构:多维数组
Flow流
计算模型:张量之间通过计算而转换的过程
TensorFlow是一个通过计算图的形式表述计算的编程系统,每一个计算都是计算图上的一个节点,节点之间的边描述了计算之间的关系。
TensorFlow有两种边:
- 常规边(实线):代表数据依赖关系。一个节点的运算输出成为另一个节点的输入,两个节点之间有tensor流动(值传递)。
- 特殊边(虚线):不携带值,表示两个节点之间的控制相关性。比如,happens-before关系,源节点必须在目的节点执行前完成执行。
张量
import tensorflow as tf
node1 = tf.constant(3.0, tf.float32, name = "node1")
node2 = tf.constant(4.0, tf.float32, name = "node2")
node3 = tf.add(node1, node2)
print(node3)
输出
Tensor("Add_3:0", shape=(), dtype=float32)
# print(node1)
Tensor("node1_4:0", shape=(), dtype=float32)
输出的结果不是一个具体的数字,而是一个张量的结构
创建流图(或计算图)就是建立计算模型,执行对话才能提供数据并获得结果
# 建立对话并显示运行结果
sess = tf.Session()
print(sess.run(node1))
print(sess.run(node3))
# 关闭Session
sess.Close()
输出
3.0
7.0
零阶张量-标量(scalar),一个数
一阶张量-向量(vector),一维数组
n阶张量,n维数组
张量没有真正保存数字,它保存的是计算过程
Tensor("Add:0", shape=(), dtype=float32)
“node:src_output”:node节点名称,src_output来自节点的第几个输出
张量的维度信息,shape=(),表示是标量
Tensorflow会对参与运算的所有张量进行类型的检查,发现类型不匹配时会报错
三个术语描述张量的维度:阶(rank)、形状(shape)、维数(dimension number)
import tensorflow as tf
tens1 = tf.constant([[[1,2,3],[4,5,6]],
[[7,8,9],[0,9,8]],
[[7,6,5],[4,3,2]],
[[1,0,1],[2,1,2]]],name="tens1")
# 语句中包含 [], {} 或 ()括号中间 换行的不需要使用多行连接符
print(tens1)
Tensor("tens1_1:0", shape=(4, 2, 3), dtype=int32)
import tensorflow as tf
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.get_shape())
print(vector.get_shape())
print(matrix.get_shape())
print(cube_matrix.get_shape())
()
(5,)
(2, 3)
(3, 3, 1)
import tensorflow as tf
tens1 = tf.constant([[[1,2],[2,3]],[[3,4],[5,6]]])
sess = tf.Session()
print(sess.run(tens1)[1,1,0])
sess.close()
5
类型
TensorFlow支持14种不同类型
实数 tf.float32, tf.float64
整数 tf.int8, tf.int16, tf.int32, tf.int64, tf.uint8
布尔 tf.bool
复数 tf.complex64, tf.complex128
默认类型:
不带小数点的数默认为int32
带小数点的数默认为float32
操作
计算图中的节点就是操作(Operation)
一次加法(或乘法)就是一个操作
构建一些变量的初始值也是一个操作
每个运算操作都有属性,在构建图时确定
操作可以和计算设备绑定,制定操作在某个设备上执行
操作之间存在顺序关系,这些操作之间的依赖是“边”
若操作A的输入是操作B执行的结果,那么这个操作A就依赖于操作B
import tensorflow as tf
tf.reset_default_gragh()#清除default graph和不断增加的节点
a = tf.Variable(1, name="a")
b = tf.add(a, 1, name="b")
c = tf.multiply(b, 4, name="c")
d = tf.substract(c, b, name="d")
logdir = 'D:/log'
#生成一个写日志的writer,并将当前的TensorFlow计算图写入日志
writer = tf.summary.FileWriter(logdir,tf.get_default_graph())
writer.close()
运行模型
会话(session)
会话拥有并管理TensorFlow程序运行时的所有资源
当所有计算完成之后需要关闭会话帮助系统回收资源
模式1
import tensorflow as tf
# 定义计算图
tens1 = tf.constant([1,2,3])
# 创建一个会话
sess = tf.Session()
# 使用这个创建好的会话来得到关心的运算的结果
print(sess.run(tens1))
# 关闭会话使得资源释放
sess.close()
[1 2 3]
放在try-catch异常里
import tensorflow as tf
# 定义计算图
tens1 = tf.constant([1,2,3])
# 创建一个会话
sess = tf.Session()
try:
# 使用这个创建好的会话来得到关心的运算的结果
print(sess.run(tens1))
except:
print("Exception!")
finally:
# 关闭会话使得资源释放
sess.close()
```
## 模式2
```py
import tensorflow as tf
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函数来计算一个张量的取值
import tensorflow as tf
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
交互式环境下,Python脚本或Jupyter编辑器下,通过设置默认会话来获取张量的取值更方便
tf.InteractiveSession使用这个函数会自动将生成的会话注册为默认会话
import tensorflow as tf
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
常量与变量
常量l
constant_name = tf.constant(value)
变量
name_variable = tf.Variable(value, name)
个别变量初始化
init_op = name_variable.initializer()
所有变量初始化
init_op = tf.global_variables_initializer()
import tensorflow as tf
node1 = tf.constant(3.0, tf.float32, name = "node1")
node2 = tf.constant(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))
sess.close()
7.0
增加了一个init初始化变量,并调用会话的run命令对参数进行初始化
赋值
epoch = tf.Variable(0,name='epoch',trainable=False)
特殊情况需人工更新的,可用变量赋值语句
update_op = tf.assign(variable_to_be_updated, new_value)
# 通过变量赋值输出1、2、3...10
import tensorflow as tf
value = tf.Variable(0, name="value")
one = tf.constant(1)
new_value = tf.add(value, one)
update_value = tf.assign(value, new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(10):
sess.run(update_value)
print(sess.run(value))
1
2
3
4
5
6
7
8
9
10
占位符
Variable变量类型,在定义时需初始化又不知道其值,真正运行程序时从外部输入
tf.placeholder
类似动态变量,函数的参数、或者C语言或者Python语言中格式化输出时的"%"占位符
tf.placeholder(dtype, shape=None, name=None)
x = tf.placeholder(tf.float32, [2, 3], name='tx')
Feed提交数据和Fetch提取数据
import tensorflow as tf
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)
报错:
AttributeError: module 'tensorflow' has no attribute 'placeholder'
因为在tf2下使用了tf1的API。
将
import tensorflow as tf
改为
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
28.0
多个操作可通过一次Feed完成执行
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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:[1.0,2.0,3.0], b:[2.0,3.0,4.0]})
print(result)
print(result[0])
[array([ 2., 6., 12.], dtype=float32), array([-1., -1., -1.], dtype=float32)]
[ 2. 6. 12.]
TensorBoard可视化
TensorBoard和TensorFlow程序跑在不同的进程中
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
#清楚default graph和不断增加的节点
tf.reset_default_graph()
logdir = 'D:/log'
#定义一个简单的计算图,实现向量加法
input1 = tf.constant([1.0, 2.0, 3.0], name="input1")
input2 = tf.Variable(tf.random_uniform([3]), name="input2")
output = tf.add_n([input1, input2], name="add")
#生成一个写日志的writer,并将当前的Tensorflow计算图写入日志
writer = tf.summary.FileWriter(logdir,tf.get_default_graph())
writer.close()
在Anaconda Prompt中先进入日志存放的目录再运行TensorBoard,并将日志的地址指向程序日志输出的地址
命令:tensorboard --logdir=/path/log
tensorboard --logdir=D:/log
默认端口6006,使用--port
参数可修改。
Jupyter技巧
Tab键代码补齐
help(plt.plot)