Tensorflow的基础用法

简介

Tensorflow是一个深度学习框架,它使用图(graph)来表示计算任务,使用tensor(张量)表示数据,图中的节点称为OP,在一个会话(Session)的上下文中执行运算,最终产生tensor。

之所以用计算图来表示计算任务,Tensorflow的官网的一张图片就能很好的说明。

tensor在数学中称为张量,表示空间,在计算图模型中就是基本的数据类型,如同我们在sklearn等机器学习框架中使用numpy的矩阵作为基本运算的数据类型一样,无论几维的矩阵都是一个张量

这里写图片描述
神经网络的前向传播本质上就是一张计算图进行计算。相比其他术语,也许计算图能更好的说明机器学习的本质。

Tensorflow的基本变量

  • tensor计算图谱的基本类型

    • tensor 张量
      • Variable 变量
      • Constant 常量
      • Placeholder 占位符
    • Graph 图
    • Session 会话

    Constant常量

    
    #tf.constant(value, dtype=None, shape=None,name="const")
    
    tf.constant(10)

    Variable变量

    import tensorflow as tf
    tf.varialbe(tf.zeros([1]))

    故名思意这个量在图的运算中可以发生改变
    文档中的一个例子

state = tf.Variable(0, name="counter")

# 创建一个 op, 其作用是使 state 增加 1

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init_op = tf.initialize_all_variables()

# 启动图, 运行 op
with tf.Session() as sess:
  # 运行 'init' op
  sess.run(init_op)
  # 打印 'state' 的初始值
  print sess.run(state)
  # 运行 op, 更新 'state', 并打印 'state'
  for _ in range(3):
    sess.run(update)
    print sess.run(state)

 # 输出:

 # 0
 # 1
 # 2
 # 3

Placeholder

这个是暂时未定义的一个tensor
在计算图运行时给予,类似函数的参数。
python
input1 = tf.placeholder(tf.float32)

计算图

Tensorflow的程序一般分为两个阶段,构建阶段和执行极端。一般,构建阶段会创建一个图,来表示神经网络,在执行阶段在反复执行训练图。
可以把图的构建看成定义一个复杂的函数。

构建图

import tensorflow as tf
matrix1 = tf.Constant([[3.,3]])

matrix2 = tf.Constant([[2.],[2.]])

product = tf.matmul(matrix1,matrix2)

启动图

python
sess = tf.Session()
result = sess.run(product)
# 运行图定义的product运算
print(result)
sess.close
#执行完毕后关闭会话

还有另一种方法会使用python的特性
python
with tf.Session() as sess:
result = sess.run([product])
print(result)

补充

Fetch取回

在sess的运算中不仅可以取回结果,还可以取回多个tensor,在神经网络中,我们可以取回中间层的结果

 input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session() as sess:
  result = sess.run([mul, intermed])
  print result
# 输出:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

sess.run()接受的参数是个列表,输出会输出这个列表中的值

Feed供给

有时训练过程中我们会执行增量训练,这时就会使用前面介绍的Placeholder()

input1 = tf.placeholder(tf.float32)
input2 = tf.plaeholder(tf.float32)
output = tf.mul(input1, input2)

with tf.Session() as sess:
    print(sess.run([ouput], feed_dict={input1:[7:],input2:[2.]})

参考资料:

TF-girls修炼指南
Tensorflow官方文档

原文地址:https://www.cnblogs.com/lynsyklate/p/6443405.html