TensorFlow可以认为是一种编程工具,使用TensorFlow来实现具体的业务需求,所以我们可以认为TensorFlow就是一个“工具箱”,然后我们使用TensorFlow这个“工具箱”中的各种“工具”(方法/API)来实现各种功能,比如使用TensorFlow实现基本的数值计算、机器学习、深度学习等。
首先得熟悉以下五个概念:
在默认图上定义两个constant节点(op),一个matmul节点(op):
import tensorflow as tf
# 1、定义常量矩阵a、b
a = tf.constant([[1,2],[3,4]], dtype=tf.int32, name='a')
print(a)
b = tf.constant([5, 6, 7, 8], dtype=tf.int32, shape=[2, 2])
print(b)
# 2、以a、b为输入,进行矩阵乘法操作
c = tf.matmul(a,b)
print(c)
输出:
注意:(一般做深度学习模型构建时最好在一张图中构建计算过程,不要使用多个图)
TensorFlow编程时可以不使用默认图(Graph),使用多个图来进行编程;但是注意:操作必须属于同一个图,不同图中的节点不能相连。
import tensorflow as tf
# 定义一个常量
a = tf.constant([[1,2],[3,4]], dtype=tf.int32, name='a')
print(a)
## 使用新的构建的图
graph = tf.Graph()
with graph.as_default():
# 此时在这个代码块中,使用的就是新的定义的图graph(相当于把默认图换成了graph)
d = tf.constant(5.0, name='d')
print("变量d是否在新图graph中:{}".format(d.graph is graph))
# 另一种写法
with tf.Graph().as_default() as g2:
e = tf.constant(6.0, name='e')
print("变量e是否在新图g2中:{}".format(e.graph is g2))
print("变量a是否在默认图中:{}".format(a.graph is g2))
输出:
import tensorflow as tf
# 1、定义常量矩阵a、b
a = tf.constant([[1,2],[3,4]], dtype=tf.int32, name='a')
print(a)
b = tf.constant([5, 6, 7, 8], dtype=tf.int32, shape=[2, 2], name='b')
print(b)
# 2、以a、b为输入,进行矩阵乘法操作
c = tf.matmul(a, b, name='matmul')
print(c)
# 3、以a、b为输入,进行矩阵加法操作
g = tf.add(a, b, name='add')
print(g, type(g))
# 4、
h = tf.subtract(b, a, name='b-a')
l = tf.matmul(h, c)
r = tf.add(g, l)
# 会话构建&启动(默认情况下(不给定Session的graph参数的情况下),创建的Session属于默认的图)
sess = tf.Session()
print(sess)
# 调用sess的run方法来执行矩阵的乘法,得到c的结果值(所以将c作为参数传递进去)
# 不需要考虑图中间的运算,在运行的时候只需要关注最终结果对应的对象以及所需要的输入数据值
# 只需要传递进去所需要得到的结果对象,会自动的根据图中的依赖关系触发所有相关的OP操作的执行
# 如果op之间没有依赖关系,tensorflow底层会并行的执行op(有资源) --> 自动进行
# 如果传递的fetches是一个列表,那么返回值是一个list集合
# fetches:表示获取那个op操作的结果值
result = sess.run(fetches=[r, c])
print("type:{}, value:\n{}".format(type(result), result))
# 会话关闭,当一个会话关闭后,不能再使用了
sess.close()
## 推荐使用的会话方式:
# 使用with语句块,会在with语句块执行完成后,自动的关闭session
with tf.Session() as sess2:
print(sess2)
# 获取张量c的结果: 通过Session的run方法获取
print("sess2 run:{}".format(sess2.run(c)))
# 获取张量r的结果:通过张量对象的eval方法获取,和Session的run方法一致
print("c eval:{}".format(r.eval()))
输出:
以上程序的所构建的图:
通过Session的config参数可以对TensorFlow的应用的执行进行一些优化调整,主要涉及到的参数如下:
# # 交互式会话构建
sess3 = tf.InteractiveSession()
print(r.eval())
TensorFlow使用张量(Tensor)数据结构来代表所有数据,计算图中,操作间传递的数据都是Tensor。Tensor可以看作是一个n维的数组或者列表,一个Tensor主要由一个静态数据类型和动态类型的维数(Rank、Shape)组成。Tensor可以在图中的节点之间流通。
import tensorflow as tf
# 1. 定义变量,常量
w1 = tf.Variable(tf.random_normal(shape=[10], stddev=0.5, seed=28, dtype=tf.float32), name='w1')
a = tf.constant(value=2.0, dtype=tf.float32)
w2 = tf.Variable(w1.initialized_value() * a, name='w2')
# 2. 进行初始化操作(推荐:使用全局所有变量初始化API)
# 相当于在图中加入一个初始化全局变量的操作
init_op = tf.global_variables_initializer()
print(type(init_op))
# 3. 图的运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True) as sess:
# 运行init op进行变量初始化,一定要放到所有运行操作之前
sess.run(init_op)
# init_op.run() # 这行代码也是初始化运行操作,但是要求明确给定当前代码块对应的默认session(tf.get_default_session())是哪个,底层使用默认session来运行
# 获取操作的结果
print("result:{}".format(sess.run(w1)))
print("result:{}".format(w2.eval()))
输出:
import tensorflow as tf
# 1. 定义变量,常量
w1 = tf.Variable(tf.random_normal(shape=[10], stddev=0.5, seed=28, dtype=tf.float32), name='w1')
a = tf.constant(value=2.0, dtype=tf.float32)
w2 = tf.Variable(w1.initialized_value() * a, name='w2')
# 2. 进行初始化操作(推荐:使用全局所有变量初始化API)
# 相当于在图中加入一个初始化全局变量的操作
init_op = tf.global_variables_initializer()
print(type(init_op))
# 启动图
with tf.Session() as sess:
# 变量初始化
sess.run(init_op)
#
results = sess.run([w1, w2])
print("w1:{}\nw2:{}".format(results[0], results[1]))
输出:
import tensorflow as tf
# 构建一个矩阵的乘法,但是矩阵在运行的时候给定
m1 = tf.placeholder(dtype=tf.float32, shape=[2, 3], name='placeholder_1')
m2 = tf.placeholder(dtype=tf.float32, shape=[3, 2], name='placeholder_2')
m3 = tf.matmul(m1, m2)
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
print("result:\n{}".format(
sess.run(fetches=m3, feed_dict={m1: [[1, 2, 3], [4, 5, 6]], m2: [[9, 8], [7, 6], [5, 4]]})))
print("result:\n{}".format(m3.eval(feed_dict={m1: [[1, 2, 3], [4, 5, 6]], m2: [[9, 8], [7, 6], [5, 4]]})))
输出: