zoukankan      html  css  js  c++  java
  • TensorFlow3学习笔记1

    1.简单实例:向量相加

    下面我们通过两个向量相加的简单例子来看一下Tensorflow的基本用法。

    [1. 1. 1. 1.] + [2. 2. 2. 2.] = [3. 3. 3. 3.]
    import tensorflow as tf
    with tf.Session():
      input1 = tf.constant([1.0 1.0 1.0 1.0])
      input2 = tf.constant([2.0 2.0 2.0 2.0])
      output = tf.add(input1, input2)
      result = output.eval()
      print result

    结果:

    两个tf.constant() 语句向计算图中创建了两个Tensor。调用tf.constant()就是创建两个指定维度的Tensor,并对其初始化

    tf.add()语句向计算图中添加了一个add操作,但不会立即执行

    最后调用output.eval()时,会触发Tensorflow执行计算图,从而获取output计算结点的结果(可与spark进行类比)

    2.Variable(变量)的使用

    import tensorflow as tf
    
    with tf.Session() as sess:
        # Set up two variables, total and weights, that we'll change repeatedly.
        total = tf.Variable(tf.zeros([1, 2]))
        weights = tf.Variable(tf.random_uniform([1, 2]))
    
        # Initialize the variables we defined above.
        tf.global_variables_initializer().run()
    
        # This only adds the operators to the graph right now. The assignment
        # and addition operations are not performed yet.
        update_weights = tf.assign(weights, tf.random_uniform([1, 2], -1.0, 1.0))
        update_total = tf.assign(total, tf.add(total, weights))
    
        for _ in range(5):
            # Actually run the operation graph, so randomly generate weights and then
            # add them into the total. Order does matter here. We need to update
            # the weights before updating the total.
            sess.run(update_weights)
            sess.run(update_total)
    
            print(weights.eval(), total.eval())

    结果:

    创建了两个变量total和weights(都是1维的tensor),total所有元素初始化为0,而weights的元素则用-1到1之间的随机数进行初始化。然后在某个迭代中,使用-1到1之间的随机数来更新变量weights的元素,然后添加到变量total中。

    所有变量都需要在开始执行图计算之前进行初始化。调用tf.initialize_all_variables().run()来对所有变量进行初始化。

    3.Session

    Session提供了Operation执行和Tensor求值的环境。

    import tensorflow as tf
    
    # Build a graph.
    a = tf.constant([1.0, 2.0])
    b = tf.constant([3.0, 4.0])
    c = a * b
    
    # Launch the graph in a session.
    sess = tf.Session()
    
    # Evaluate the tensor 'c'.
    print (sess.run(c))
    sess.close()

    一个Session可能会拥有一些资源,例如Variable或者Queue。当我们不再需要该session的时候,需要将这些资源进行释放。有两种方式,

    1. 调用session.close()方法;
    2. 使用with tf.Session()创建上下文(Context)来执行,当上下文退出时自动释放。

    上面的例子可以写成:

    import tensorflow as tf
    
    # Build a graph.
    a = tf.constant([1.0, 2.0])
    b = tf.constant([3.0, 4.0])
    c = a * b
    
    with tf.Session() as sess:
        print (sess.run(c))

    Session类的构造函数如下所示:

    tf.Session.__init__(target='', graph=None, config=None)

    如果在创建Session时没有指定Graph,则该Session会加载默认Graph。如果在一个进程中创建了多个Graph,则需要创建不同的Session来加载每个Graph,而每个Graph则可以加载在多个Session中进行计算。

    执行Operation或者求值Tensor有两种方式:

    1. 调用Session.run()方法: 该方法的定义如下所示,参数fetches便是一个或者多个Operation或者Tensor。

      tf.Session.run(fetches, feed_dict=None)

    2. 调用Operation.run()或则Tensor.eval()方法: 这两个方法都接收参数session,用于指定在哪个session中计算。但该参数是可选的,默认为None,此时表示在进程默认session中计算。

    那如何设置一个Session为默认的Session呢?有两种方式:

    1. 在with语句中定义的Session,在该上下文中便成为默认session;上面的例子可以修改成:

    import tensorflow as tf
    
    # Build a graph.
    a = tf.constant([1.0, 2.0])
    b = tf.constant([3.0, 4.0])
    c = a * b
    
    with tf.Session():
       print (c.eval())

    2. 在with语句中调用Session.as_default()方法。 上面的例子可以修改成:

    import tensorflow as tf
    
    # Build a graph.
    a = tf.constant([1.0, 2.0])
    b = tf.constant([3.0, 4.0])
    c = a * b
    sess = tf.Session()
    with sess.as_default():
        print (c.eval())
    sess.close()

    4.Graph

    Tensorflow中使用tf.Graph类表示可计算的图。图是由操作Operation和张量Tensor来构成,其中Operation表示图的节点(即计算单元),而Tensor则表示图的边(即Operation之间流动的数据单元)。

    tf.Graph.__init__()

    创建一个新的空Graph

    在Tensorflow中,始终存在一个默认的Graph。如果要将Operation添加到默认Graph中,只需要调用定义Operation的函数(例如tf.add())。如果我们需要定义多个Graph,则需要在with语句中调用Graph.as_default()方法将某个graph设置成默认Graph,于是with语句块中调用的Operation或Tensor将会添加到该Graph中。

    import tensorflow as tf
    g1 = tf.Graph()
    with g1.as_default():
        c1 = tf.constant([1.0])
    with tf.Graph().as_default() as g2:
        c2 = tf.constant([2.0])
    
    with tf.Session(graph=g1) as sess1:
        print sess1.run(c1)
    with tf.Session(graph=g2) as sess2:
        print sess2.run(c2)

    如果将上面例子的sess1.run(c1)和sess2.run(c2)中的c1和c2交换一下位置,运行会报错。因为sess1加载的g1中没有c2这个Tensor,同样地,sess2加载的g2中也没有c1这个Tensor。

    5.Operation

    一个Operation就是Tensorflow Graph中的一个计算节点。其接收零个或者多个Tensor对象作为输入,然后产生零个或者多个Tensor对象作为输出。Operation对象的创建是通过直接调用Python operation方法(例如tf.matmul())或者Graph.create_op()。

    例如c = tf.matmul(a, b)表示创建了一个类型为MatMul的Operation,该Operation接收Tensor a和Tensor b作为输入,而产生Tensor c作为输出。

    当一个Graph加载到一个Session中,则可以调用Session.run(op)来执行op,或者调用op.run()来执行(op.run()是tf.get_default_session().run()的缩写)。

    6.Tensor

    Tensor(张量)表示的是Operation的输出结果。不过,Tensor只是一个符号句柄,其并没有保存Operation输出结果的值。通过调用Session.run(tensor)或者tensor.eval()方可获取该Tensor的值。一个张量中主要保存了三个属性:名字(name),维度(shape),类型(type)

    import tensorflow as tf
    with tf.Session():
        a = tf.constant([1.0, 2.0], name="a1")
        b = tf.constant([3.0, 4.0], name="b1")
        result = tf.add(a, b, name="add1")
        print(result)

    1>张量的命名可以通过"node:src_output"的形式给出。node为节点的名称,src_output表示当前张量来自节点的第几个输出。add1:0说明了result这个张量是计算节点“add”输出的第一个结果(编号从0开始)

    2>shape=(2,)说明了张量result是一个以为数组,这个数组的长度为2

    3>每个张量都有一个唯一的类型,类型不匹配时会报错,例如:

  • 相关阅读:
    fn project 试用之后的几个问题的解答
    fn project 扩展
    fn project 生产环境使用
    fn project 对象模型
    fn project AWS Lambda 格式 functions
    fn project 打包Function
    fn project Function files 说明
    fn project hot functions 说明
    fn project k8s 集成
    fn project 私有镜像发布
  • 原文地址:https://www.cnblogs.com/feiyumo/p/7891232.html
Copyright © 2011-2022 走看看