美文网首页
TensorFlow简单介绍

TensorFlow简单介绍

作者: UlissesJr | 来源:发表于2018-10-28 22:20 被阅读29次

Tagline:An open-source software library for Machine Intelligence.
Definition:TensorFlowTM is an open source software library for numerical computation using data flow graphs.
GitHub:https://github.com/tensorflow/tensorflow
Website:https://tensorflow.org/ or https://tensorflow.google.cn/


TensorFlow介绍

  • TensorFlowTM 是一个采用数据流图(data flow graphs),用于数值计算的开 源软件库。TensorFlow 最初由Google大脑小组(隶属于Google机器智能研究 机构)的研究员和工程师们开发出来,用于机器学习和深度神经网络方面的研究, 但这个系统的通用性使其也可广泛用于其他计算领域。它是谷歌基于DistBelief 进行研发的第二代人工智能学习系统。2015年11月9日,Google发布人工智能 系统TensorFlow并宣布开源。

  • 其命名来源于本身的原理,Tensor(张量)意味着N维数组,Flow(流)意味 着基于数据流图的计算。Tensorflow运行过程就是张量从图的一端流动到另一端 的计算过程。张量从图中流过的直观图像是其取名为“TensorFlow”的原因

  • TensorFlow的关键点是:“Data Flow Graphs”,表示TensorFlow是一种基 于图的计算框架,其中节点(Nodes)在图中表示数学操作,线(Edges)则表 示在节点间相互联系的多维数据数组,即张量(Tensor),这种基于流的架构让 TensorFlow具有非常高的灵活性,该灵活性也让TensorFlow框架可以在多个平 台上进行计算,例如:台式计算机、服务器、移动设备等。

  • 备注:TensorFlow的开发过程中,重点在于构建执行流图。


什么是数据流图

  • 数据流图使用节点(Node)和线(Edges)的有向图描 述数学计算;节点一般用来表示施加的数学操作,也可以 表示数据输入(feed in)的起点和输出(push out)的终点, 或者是读取/写入持久变量(persistent variable)的终点。 线表示的是节点之间的输入/输出关系,这些线可以输运 “size可动态调整”的多维数组,即张量(Tensor)。

  • 一旦输入端的所有张量准备好,节点将被分配到各种计
    算设备完成异步并行地执行运算。


TensorFlow-GPU安装-CUDA

  • CUDA下载安装链接:https://developer.nvidia.com/cuda-toolkit-archive
    cuDNN下载安装链接:https://developer.nvidia.com/rdp/cudnn-archive
    备注:具体的CUDA版本根据导入tensorflow时提示的异常来选择;即先安装 tensorflow-gpu,然后在python的命令行执行:import tensorflow,会出现 如下异常,则表示我们需要安装的是CUDA 8.0版本,至于cuDNN选择和CUDA 对应版本即可。

  • 除了安装CUDA外,还需要安装对应版本的cuDNN,将cuDNN的压缩包解压, 然后将压缩包中的三个文件夹全部放到CUDA对应的根目录下,根据环境变量找 到对应的根目录:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0;



TensorFlow基本概念

  • 图(Graph):图描述了计算的过程,TensorFlow使用图来表示计算任务。
  • 张量(Tensor):TensorFlow使用tensor表示数据。每个Tensor是一个类型化 的多维数组。
  • 操作(op):图中的节点被称为op(opearation的缩写),一个op获得0个或 多个Tensor,执行计算,产生0个或多个Tensor。
  • 会话(Session):图必须在称之为“会话”的上下文中执行。会话将图的op分 发到诸如CPU或GPU之类的设备上执行。
  • 变量(Variable):运行过程中可以被改变,用于维护状态。
  • TensorFlow的边即有两种连接关系:
    数据依赖
    控制依赖

  • 实线边表示数据依赖,代表数据,即张量。任意维度的数据统称为张量。在机器 学习算法中,张量在数据流图中从前往后流动一遍就完成一次前向传播,而残差 从后向前流动一遍就完成一次反向传播。

  • 虚线边表示控制依赖,可以用于控制操作的运行,这被用来确保happens- before关系,这类边上没有数据流过,但源节点必须在目的节点开始执行前完成。

数据属性

节点

节点又称为算子,它代表一个操作,一般用来表示施加的数字运算,也可以表示数 据输入的起点以及输出的重点,或者是读取/写入持久变量的终点


TensorFlow基本用法
  • TensorFlow可以认为是一种编程工具,使用TensorFlow来实现具体的业务需求, 所以我们可以认为TensorFlow就是一个“工具箱”,然后我们使用TensorFlow 这个“工具箱”中的各种“工具”(方法/API)来实现各种功能,比如使用 TensorFlow实现基本的数值计算、机器学习、深度学习等;使用TensorFlow必 须理解下列概念:
  • 使用图(graph)来表示计算任务;
  • 在会话(session)的上下文中执行图;
  • 使用tensor表示数据;
  • 通过变量(Variable)来维护状态 ; 使用feed和fetch可以为任意的操作(Operation/op)赋值或者从其中获取数据。
TensorFlow程序结构
  • TensorFlow的程序一般分为两个阶段:构建阶段执行阶段;
  • 构建阶段:op的执行步骤被描述称为一个图,然后使用TensorFlow提供的API 构建这个图。
  • 执行阶段:将构建好的执行图(Operation Graph)在给定的会话中执行,并得到 执行结果。

TensorFlow图

  • TensorFlow编程的重点是根据业务需求,使用TensorFlow的API将业务转换为执行图 (有向无环图);图中的节点是Tensor,节点之间的连线是节点之间的操作,连线前的 节点可以认为是操作的输入,连线后的节点可以认为操作的输出;根据节点的特性(是 否有输入输出),可以将节点分为源节点、中间节点和最终的结果节点。
  • 图构建的第一步就是创建源op(source op); 源op不需要任何的输入。op构造器的返回 值代表被构造出的op的输出,这些返回值可以传递给其它op构造器作为输入或者直接获取结果。
  • TensorFlow库中有一个默认图(default graph),op构造器可以直接为其添加节点,一 般情况下,使用默认的Graph即可完成程序代码的实现。不过TensorFlow也支持通过 Graph类管理多个图。
默认图现在有三个节点,两个constant op和一个matmul op。
不使用默认图(Graph),使用多个图来进行编程;但是注意:操作必须属于同一 个图,不同图中的节点不能相连。
  • tf.constant
    而如果列表大小小于shape大小,则会用列表的最后一项元素填充剩余的张量元素
 # Constant 1-D Tensor populated with value list.
   tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

   # Constant 2-D tensor populated with scalar value -1.
   tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]

  # 2-D tensor `a`
  a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) => [[1. 2. 3.]
                                                        [4. 5. 6.]]
  # 2-D tensor `b`
  b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) => [[7. 8.]
                                                           [9. 10.]
                                                           [11. 12.]]
  # 3-D tensor `a`
  a = tf.constant(np.arange(1, 13, dtype=np.int32),
                  shape=[2, 2, 3])                  => [[[ 1.  2.  3.]
                                                         [ 4.  5.  6.]],
                                                        [[ 7.  8.  9.]
                                                         [10. 11. 12.]]]

  # 3-D tensor `b`
  b = tf.constant(np.arange(13, 25, dtype=np.int32),
                  shape=[2, 3, 2])                    => [[[13. 14.]
                                                          [15. 16.]
                                                          [17. 18.]],
                                                         [[19. 20.]
                                                          [21. 22.]
                                                          [23. 24.]]]

TensorFlow会话

当执行图构建完成后,才能给启动图,进入到执行阶段;启动图的第一步就是创 建一个Session对象,如果无任何参数的情况下,会话构造器将启动默认图。


  • tf.Session在构建会话的时候,如果不给定任何参数,那么构建出来Session对 应的内部的Graph其实就是默认Graph,不过我们可以通过参数给定具体对应的 是那一个Graph以及当前Session对应的配合参数。Session的构造主要有三个参 数,作用如下:
  • target:给定连接的url,只有当分布式运行的时候需要给定(后面分布式运行讲);
  • graph:给定当前Session对应的图,默认为TensorFlow中的默认图;
  • config:给定当前Session的相关参数,参数详见: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/prot obuf/config.proto中[ConfigProto]
  • 通过Session的config参数可以对TensorFlow的应用的执行进行一些优化调整, 主要涉及到的参数如下:


Tensor张量

  • TensorFlow使用Tensor数据结构来代表所有数据,计算图中,操作间传递的数 据都是Tensor。Tensor可以看作是一个n维的数组或者列表,一个Tensor主要由 一个静态数据类型和动态类型的维数(Rank、Shape)组成。Tensor可以在图中的 节点之间流通。


TensorFlow变量

  • 变量(Variables)是维护图执行过程中的状态信息。在训练模型过程中,可以通过 变量来存储和更新参数。变量包含张量(Tensor)存放于内存的缓存区。建模的时 候变量必须被明确的初始化,模型训练后变量必须被存储到磁盘。这些变量的值 可以在之后的模型训练和分析中被加载。
  • 在构建变量的时候,必须将一个张量或者可以转化为张量的Python对象作为初 始值传入构造函数Variable中。
  • 特别注意:变量的全局初始化(tf.initialize_all_variables())是并行执行的,如果 存在变量之间的依赖关系的时候,再进行初始化的时候要特别注意。
一个简单的使用变量的案例
进行变量依赖的案例创建
屏幕快照 2018-10-29 下午7.52.40.png

TensorFlow Fetch

  • 为了取回操作的输出内容,可以在使用Session对象的run方法调用执行图的时 候,传入一些tensor,通过run方法就可以获取这些tensor对应的结果值。
  • 如果需要获取多个tensor的值,那么尽量一次运行就获取所有的结果值,而不是 采用逐个获取的方式。


TensorFlow Feed

  • Tensorflow还提供了填充机制(feed),可以在构建图时使用placeholder类型的 API临时替代任意操作的张量(占位符),在调用Session对象的run()方法去执行图 时,使用填充数据作为调用的参数,调用结束后,填充数据就消失了。
  • feed使用一个tensor值临时替换一个操作的输出结果,在获取数据的时候必须 给定对应的feed数据作为参数。feed只有在调用它的方法内有效,方法结束, feed就消失了。
  • feed可以使用placeholder类型的API创建占位符,常见API:tf.placeholder、 tf.placeholder_with_default



# -- encoding:utf-8 --

import tensorflow as tf

# 1. 定义常量矩阵a和矩阵b
# name属性只是给定这个操作一个名称而已
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)
d = tf.constant([3,3],shape=(1,2))
print(d)

# 3. 以a和c作为输入,进行矩阵的相加操作
g = tf.add(a, c, name='add')
print(type(g))
print(g)

# 4. 添加减法
h = tf.subtract(b, a, name='b-a')
l = tf.matmul(h, c)
r = tf.add(g, l)

print("变量a是否在默认图中:{}".format(a.graph is tf.get_default_graph()))

# 使用新的构建的图
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)
    print("变量e是否在新图g2中:{}".format(e.graph is g2))

# 这段代码是错误的用法,记住:不能使用两个图中的变量进行操作,只能对同一个图中的变量对象(张量)进行操作(op)
# f = tf.add(d, e)


#会话构建&启动(默认情况下(不给定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()

# 当一个会话关闭后,不能再使用了,所以下面两行代码错误
# result2 = sess.run(c)
# print(result2)

# 使用with语句块,会在with语句块执行完成后,自动的关闭session
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess2:
    print(sess2)
    # 获取张量c的结果: 通过Session的run方法获取
    print("sess2 run:{}".format(sess2.run(c)))
    # 获取张量r的结果:通过张量对象的eval方法获取,和Session的run方法一致
    print("c eval:{}".format(r.eval()))

# 交互式会话构建
sess3 = tf.InteractiveSession()
print(r.eval())

# 1. 定义一个变量,必须给定初始值(图的构建,没有运行)
a = tf.Variable(initial_value=3.0, dtype=tf.float32)

# 2. 定义一个张量
b = tf.constant(value=2.0, dtype=tf.float32)
c = tf.add(a, b)

# 3. 进行初始化操作(推荐:使用全局所有变量初始化API)
# 相当于在图中加入一个初始化全局变量的操作
init_op = tf.global_variables_initializer()
print(type(init_op))

# 3. 图的运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 运行init op进行变量初始化,一定要放到所有运行操作之前
    sess.run(init_op)
    # init_op.run() # 这行代码也是初始化运行操作,但是要求明确给定当前代码块对应的默认session(tf.get_default_session())是哪个,底层使用默认session来运行
    # 获取操作的结果
    print("result:{}".format(sess.run(c)))
    print("result:{}".format(c.eval()))

# 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')

# 3. 进行初始化操作(推荐:使用全局所有变量初始化API)
# 相当于在图中加入一个初始化全局变量的操作
init_op = tf.global_variables_initializer()
print(type(init_op))

# 3. 图的运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_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()))

# 构建一个矩阵的乘法,但是矩阵在运行的时候给定
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]]})))


# -- encoding:utf-8 --
import tensorflow as tf

# 需求一
# 1. 定义一个变量
x = tf.Variable(1, dtype=tf.int32, name='v_x')

# 2. 变量的更新
assign_op = tf.assign(ref=x, value=x + 1)

# 3. 变量初始化操作
x_init_op = tf.global_variables_initializer()

# 3. 运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 变量初始化
    sess.run(x_init_op)

    # 模拟迭代更新累加器
    for i in range(5):
        # 执行更新操作
        sess.run(assign_op)
        r_x = sess.run(x)
        print(r_x)

# 需求二
# 1. 定义一个不定形状的变量
x = tf.Variable(
    initial_value=[],  # 给定一个空值
    dtype=tf.float32,
    trainable=False,
    validate_shape=False  # 设置为True,表示在变量更新的时候,进行shape的检查,默认为True
)

# 2. 变量更改
concat = tf.concat([x, [0.0, 0.0]], axis=0)
assign_op = tf.assign(x, concat, validate_shape=False)

# 3. 变量初始化操作
x_init_op = tf.global_variables_initializer()

# 3. 运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 变量初始化
    sess.run(x_init_op)

    # 模拟迭代更新累加器
    for i in range(5):
        # 执行更新操作
        sess.run(assign_op)
        r_x = sess.run(x)
        print(r_x)

# 需求三
# 1. 定义一个变量
sum = tf.Variable(1, dtype=tf.int32)
# 2. 定义一个占位符
i = tf.placeholder(dtype=tf.int32)

# 3. 更新操作
tmp_sum = sum * i
# tmp_sum = tf.multiply(sum, i)
assign_op = tf.assign(sum, tmp_sum)
with tf.control_dependencies([assign_op]):
    # 如果需要执行这个代码块中的内容,必须先执行control_dependencies中给定的操作/tensor
    sum = tf.Print(sum, data=[sum, sum.read_value()], message='sum:')

# 4. 变量初始化操作
x_init_op = tf.global_variables_initializer()

# 5. 运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 变量初始化
    sess.run(x_init_op)

    # 模拟迭代更新累加器
    for j in range(1, 6):
        # 执行更新操作
        # sess.run(assign_op, feed_dict={i: j})
        # 通过control_dependencies可以指定依赖关系,这样的话,就不用管内部的更新操作了
        r = sess.run(sum, feed_dict={i: j})

    print("5!={}".format(r))


# -- encoding:utf-8 --
import tensorflow as tf

with tf.device('/cpu:0'):
    # 这个代码块中定义的操作,会在tf.device给定的设备上运行
    # 有一些操作,是不会再GPU上运行的(一定要注意)
    # 如果按照的tensorflow cpu版本,没法指定运行环境的
    a = tf.Variable([1, 2, 3], dtype=tf.int32, name='a')
    b = tf.constant(2, dtype=tf.int32, name='b')
    c = tf.add(a, b, name='ab')

with tf.device('/gpu:0'):
    # 这个代码块中定义的操作,会在tf.device给定的设备上运行
    # 有一些操作,是不会再GPU上运行的(一定要注意)
    # 如果按照的tensorflow cpu版本,没法指定运行环境的
    d = tf.Variable([2, 8, 13], dtype=tf.int32, name='d')
    e = tf.constant(2, dtype=tf.int32, name='e')
    f = d + e

g = c + f

with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 初始化
    tf.global_variables_initializer().run()
    # 执行结果
    print(g.eval())

# 方式一
def my_func(x):
    w1 = tf.Variable(tf.random_normal([1]))[0]
    b1 = tf.Variable(tf.random_normal([1]))[0]
    r1 = w1 * x + b1

    w2 = tf.Variable(tf.random_normal([1]))[0]
    b2 = tf.Variable(tf.random_normal([1]))[0]
    r2 = w2 * r1 + b2

    return r1, w1, b1, r2, w2, b2


# 下面两行代码还是属于图的构建
x = tf.constant(3, dtype=tf.float32)
r = my_func(x)

with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 初始化
    tf.global_variables_initializer().run()
    # 执行结果
    print(sess.run(r))

# 方式二
def my_func(x):
    # initializer:初始化器
    # w = tf.Variable(tf.random_normal([1]), name='w')[0]
    # b = tf.Variable(tf.random_normal([1]), name='b')[0]
    w = tf.get_variable(name='w', shape=[1], initializer=tf.random_normal_initializer())[0]
    b = tf.get_variable(name='b', shape=[1], initializer=tf.random_normal_initializer())[0]
    r = w * x + b

    return r, w, b


def func(x):
    with tf.variable_scope('op1', reuse=tf.AUTO_REUSE):
        r1 = my_func(x)
    with tf.variable_scope('op2', reuse=tf.AUTO_REUSE):
        r2 = my_func(r1[0])
    return r1, r2


# 下面两行代码还是属于图的构建
x1 = tf.constant(3, dtype=tf.float32, name='x1')
x2 = tf.constant(4, dtype=tf.float32, name='x2')
with tf.variable_scope('func1'):
    r1 = func(x1)
with tf.variable_scope('func2'):
    r2 = func(x2)

with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # 初始化
    tf.global_variables_initializer().run()
    # 执行结果
    print(sess.run([r1, r2]))


with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    with tf.variable_scope('foo', initializer=tf.constant_initializer(4.0)) as foo:
        v = tf.get_variable("v", [1])
        w = tf.get_variable("w", [1], initializer=tf.constant_initializer(3.0))
        with tf.variable_scope('bar'):
            l = tf.get_variable("l", [1])

            with tf.variable_scope(foo):
                h = tf.get_variable('h', [1])
                g = v + w + l + h

    with tf.variable_scope('abc'):
        a = tf.get_variable('a', [1], initializer=tf.constant_initializer(5.0))
        b = a + g

    sess.run(tf.global_variables_initializer())
    print("{},{}".format(v.name, v.eval()))
    print("{},{}".format(w.name, w.eval()))
    print("{},{}".format(l.name, l.eval()))
    print("{},{}".format(h.name, h.eval()))
    print("{},{}".format(g.name, g.eval()))
    print("{},{}".format(a.name, a.eval()))
    print("{},{}".format(b.name, b.eval()))


# 可视化
with tf.variable_scope("foo"):
    with tf.device("/cpu:0"):
        x_init1 = tf.get_variable('init_x', [10], tf.float32, initializer=tf.random_normal_initializer())[0]
        x = tf.Variable(initial_value=x_init1, name='x')
        y = tf.placeholder(dtype=tf.float32, name='y')
        z = x + y

    # update x
    assign_op = tf.assign(x, x + 1)
    with tf.control_dependencies([assign_op]):
        with tf.device('/gpu:0'):
            out = x * y

with tf.device('/cpu:0'):
    with tf.variable_scope("bar"):
        a = tf.constant(3.0) + 4.0
    w = z * a

# 开始记录信息(需要展示的信息的输出)
tf.summary.scalar('scalar_init_x', x_init1)
tf.summary.scalar(name='scalar_x', tensor=x)
tf.summary.scalar('scalar_y', y)
tf.summary.scalar('scalar_z', z)
tf.summary.scalar('scala_w', w)
tf.summary.scalar('scala_out', out)

with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)) as sess:
    # merge all summary
    merged_summary = tf.summary.merge_all()
    # 得到输出到文件的对象
    writer = tf.summary.FileWriter('./result', sess.graph)

    # 初始化
    sess.run(tf.global_variables_initializer())
    # print
    for i in range(1, 5):
        summary, r_out, r_x, r_w = sess.run([merged_summary, out, x, w], feed_dict={y: i})
        writer.add_summary(summary, i)
        print("{},{},{}".format(r_out, r_x, r_w))

    # 关闭操作
    writer.close()

# 模型保存
v1 = tf.Variable(tf.constant(3.0), name='v1')
v2 = tf.Variable(tf.constant(4.0), name='v2')
result = v1 + v2

saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(result)
    # 模型保存到model文件夹下,文件前缀为:model.ckpt
    saver.save(sess, './model/model.ckpt')

# 模型的提取(完整提取:需要完整恢复保存之前的数据格式)
v1 = tf.Variable(tf.constant(1.0), name='v1')
v2 = tf.Variable(tf.constant(4.0), name='v2')
result = v1 + v2

saver = tf.train.Saver()
with tf.Session() as sess:
    # 会从对应的文件夹中加载变量、图等相关信息
    saver.restore(sess, './model/model.ckpt')
    print(sess.run([result]))

# 直接加载图,不需要定义变量了
saver = tf.train.import_meta_graph('./model/model.ckpt.meta')

with tf.Session() as sess:
    saver.restore(sess, './model/model.ckpt')
    print(sess.run(tf.get_default_graph().get_tensor_by_name("add:0")))

# 模型的提取(给定映射关系)
a = tf.Variable(tf.constant(1.0), name='a')
b = tf.Variable(tf.constant(2.0), name='b')
result = a + b

saver = tf.train.Saver({"v1": a, "v2": b})
with tf.Session() as sess:
    # 会从对应的文件夹中加载变量、图等相关信息
    saver.restore(sess, './model/model.ckpt')
    print(sess.run([result]))

相关文章

网友评论

      本文标题:TensorFlow简单介绍

      本文链接:https://www.haomeiwen.com/subject/npzptqtx.html