丛零开始

看了一篇入门级的文章 Tensorflow学习笔记2:About Session, Graph, Operation and Tensor,讲的很简单,清楚,如果刚开始接触tensorflow看一下就会很明白怎么去跑一个最简单的网络,如下这种网络。

import tensorflow as tf
a = tf.constant(1)
b = tf.constant(2)
c = tf.constant(3)
d = tf.constant(4)
add1 = tf.add(a, b)
mul1 = tf.mul(b, c)
add2 = tf.add(c, d)
output = tf.add(add1, mul1)
with tf.Session() as sess:
    print sess.run(output)

graph_compute_flow.jpg

tensorflow可以有两种入口的方式

  1. session
  2. tf.app.run

session

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

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

使用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

# Launch the graph in a session.
sess = tf.Session()

# Evaluate the tensor 'c'.
print sess.run(c)
sess.close()

# result: [3., 8.]

上面第二点提到可以创建上下文,这样的方式更有利于自动清理变量

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)

tf.app.run

看到很多源代码中都会出现

if __name__ == "__main__":
    tf.app.run()

这样的代码其实是在执行解析flag后再去执行main函数,源代码如下

# tensorflow/tensorflow/python/platform/default/_app.py  
  
# Copyright 2015 Google Inc. All Rights Reserved.  
#  
# Licensed under the Apache License, Version 2.0 (the "License");  
# you may not use this file except in compliance with the License.  
# You may obtain a copy of the License at  
#  
#     http://www.apache.org/licenses/LICENSE-2.0  
#  
# Unless required by applicable law or agreed to in writing, software  
# distributed under the License is distributed on an "AS IS" BASIS,  
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
# See the License for the specific language governing permissions and  
# limitations under the License.  
# ==============================================================================  
  
"""Generic entry point script."""  
from __future__ import absolute_import  
from __future__ import division  
from __future__ import print_function  
  
import sys  
  
from tensorflow.python.platform import flags  
  
  
def run(main=None):  
  f = flags.FLAGS  
  f._parse_flags()  
  main = main or sys.modules['__main__'].main  
  sys.exit(main(sys.argv))  
  

在同一个python文件下,可以def一个main函数,run的时候就会去找这个main函数执行。

def main(unused_argv):
    test()
    

jasperyang
203 声望58 粉丝

Highest purpose is Hacking...