tensorflow入门1


tensorlow是Google开发的深度学习计算框架,tensor指张量,flow指张量在计算中的流动。

tensorflow的基本思路是先构建图,再通过开启Session会话计算图。

构建图阶段:

  1.构建输入:

    1.1构建变量:x = tf.Variable(tf.random_uniform([2,1], -1.0,1.0), dtype = tf.float32, name = 'x')

    1.2.构建常量:a = tf.constant(3.0, name='a')

    1.3.构建placeholder: y = tf.placeholder(shape=(None, 3), dtype = tf.float32, name = 'y')

   区别:在执行计算时,每执行一次计算,常量都要调用一次,执行完马上释放;变量在整个计算会话中,都会保存,但是变量需要一直持有;placeholder开始可以不用输入,在执行每次计算时,再传入对应的张量。

 2.构建计算:

   根据需要逐步构建计算逻辑,如:f = x*a+y

计算图阶段:

  1.执行计算图之前先要做变量的初始化,可以在会话前做全局初始化:init = tf.global_variables_initializer();也可以在会话开始,逐个对变量初始化。

  2. 在会话的with块中执行会话:

     with tf.Session():

          init.run()

         result =  f.eval(feed_dict = {y:[[1, 2, 3]]}) #placeholder必须在计算时指定

         print(result)

3.其他:

 3.1构建图阶段,可以指定运行的GPU,with tf.device('/GPU:0'),在计算会话时,可以查看运行的GPU,with Session(config = tf.ConfigProto(log_device_placement = True))。

 3.2默认会话,sess = InteractiveSession(),则计算在默认会话中国执行,一般只有一个会话时,可以这样操作;

 3.3创建节点加入指定图中,with graph.as_default():,在这个with块下的节点将被默认在新的图graph中,而不是默认图tf.get_default_graph中。

一个简单的代码实现:

import tensorflow as tf
with tf.device('/CPU:0'):
  x = tf.Variable(tf.random_uniform([2,1], -1.0,1.0), dtype = tf.float32, name = 'x')
a = tf.constant(3.0, name='a')
y = tf.placeholder(shape=(None, 3), dtype = tf.float32, name = 'y')
f = x*a+y

init = tf.global_variables_initializer()
with tf.Session(config = tf.ConfigProto(log_device_placement = True)):  

  init.run()
  result = f.eval(feed_dict={y: [[1, 2, 3]]})
  print(result)