Tensorflow基础知识

TensorFlow基础知识:

• 使用图 (graphs) 来表示计算.

• 在会话 (Session) 中执行图.

• 使用张量 (tensors) 来代表数据.

• 通过变量 (Variables) 维护状态.

• 使用供给 (feeds) 和取回 (fetches) 将数据传入或传出任何操作.

TensorFlow 是一个以图 (graphs) 来表示计算的编程系统, 图中的节点被称之为 op (op- eration 的缩写). 一个 op 获得零或多个张量 (tensors) 执行计算, 产生零或多个张量。张量 是一个按类型划分的多维数组。例如, 你可以将一小组图像集表示为一个四维浮点数数 组, 这四个维度分别是[batch, height, width, channels]。

TensorFlow 的图是一种对计算的抽象描述。在计算开始前, 图必须在 会话 (Session ()) 中被启动. 会话将图的 op 分发到如 CPU 或 GPU 之类的 设备 (Devices()) 上, 同时提供 执行 op 的方法。这些方法执行后, 将产生的张量 (tensor) 返回。在 Python 语言中, 将返 回numpy的ndarray 对象; 在 C 和 C++ 语言中, 将返回tensorflow::Tensor实例。

 

构建图和启动会话

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
创建一个常量op 产生一个1x2的矩阵, 这个op是添加在默认图中的一个节点
 op 构造函数返回代表已被组织好的 op 作为输出对象,这些对象可 以传递给其它 op 构造函数作为输入。
"""
import tensorflow as tf

#通过构造器返回一个输出常量
matrix1 = tf.constant([[3.,3.]])

#创建一个2X1的矩阵
matrix2 = tf.constant([[2.],[2.]])

#创建一个Matmul,用matrix1和matrix2作为输入,返回两个矩阵相乘的结果
product = tf.matmul(matrix1,matrix2)

#默认图现在拥有三个节点,两个constant() op,一个matmul() op. 
#为了真正进行矩 阵乘法运算,得到乘法结果, 你必须在一个会话 (session) 中载入动这个图。
#创建一个 会话对象 (Session object)。会话构建器在未指明参数时会载入默认的图。
sess = tf.Session()

#要运行matmul op 可以运行run()方法
result = sess.run(product)
print result

#关闭会话
sess.close()

"""
会话在完成后必须关闭以释放资源。你也可以使用"with"句块开始一个会话,该会
话将在"with"句块结束时自动关闭。   
  
with tf.Session() as sess: result = sess.run([product])
  print(result)
"""

TensorFlow 事实上通过一个"翻译"过程,将定义的图转化为不同的可用计算资源 间实现分布计算的操作,如 CPU 或是显卡 GPU。通常不需要用户指定具体使用的 CPU 或 GPU,TensorFlow 能自动检测并尽可能的充分利用找到的第一个 GPU 进行运算。

交互式使用

如IPython这样的交互式 Python 环境的易用, 可以使用InteractiveSession 代替Session类, 使用 Tensor.eval()和 Operation.run() 方法代替 Session.run(). 这样可以避免使用一个变量来持有会话.

# Enter an interactive TensorFlow Session.
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.Variable([1.0, 2.0]) a = tf.constant([3.0, 3.0])
# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()
# Add an op to subtract 'a' from 'x'. Run it and print the result
sub = tf.sub(x, a)
                  
print(sub.eval()) # ==> [−2. −1.]
# Close the Session when we're done.
sess.close()

张量(Tensors)

TensorFlow 程序使用 tensor 数据结构来代表所有的数据, 计算图中, 操作间传递的 数据都是 tensor. 你可以把 TensorFlow 的张量看作是一个 n 维的数组或列表. 一个 tensor 包含一个静态类型 rank, 和一个 shape.(可类比spark的RDD进行理解)

 

变量(Variables)

变量维持了图执行过程中的状态信息。

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 12 18:35:43 2017

@author: miao
使用变量实现一个 简单的计数器
"""

import tensorflow as tf

#建立一个变量,用0初始化它的值
state = tf.Variable(0, name= "counter")

#创建一个op one
one = tf.constant(1)
new_value = tf.add(state, one)
#代码中assign()操作是图所描绘的表达式的一部分, 正如add()操作一样. 所以在调 用run()执行表达式之前, 它并不会真正执行赋值操作.
update = tf.assign(state, new_value)

#变量在启动图计算之后必须通过运行'init'来初始化
init_op = tf.initialize_all_variables()

#启动图运行ops
with tf.Session() as sess:
    #先初始化'init'op
    sess.run(init_op)
    #打印state初始化值
    print sess.run(state)
    #运行update
    for _ in range(3):
        sess.run(update)
        print sess.run(state)
#输出:
    0
    1
    2
    3


通常会将一个统计模型中的参数表示为一组变量. 例如, 你可以将一个神经网络的 权重作为某个变量存储在一个 tensor 中. 在训练过程中, 通过重复运行训练图, 更新这个 tensor.

取回(Fetches)

为了取回操作的输出内容, 可以在使用 Session 对象的 run() 调用执行图时, 传入一些 tensor, 这些 tensor 会帮助你取回结果. 在之前的例子里, 我们只取回了单个节点state,但是你也可以取回多个 tensor:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
"""

import tensorflow as tf

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

with tf.Session() as sess:
    result = sess.run([mul, intermed])
    print result

# output:
# [array([ 14.], dtype=float32)]
 

供给(Feeds)

在计算图中引入了 tensor, 以 常量 (Constants) 或 变量 (Variables) 的形式 存储. TensorFlow还提供给(feed)机制,该机制可临时替代图中的任意操作中的tensor 可以对图中任何操作提交补丁, 直接插入一个 tensor.feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为run() 调用的参数.feed 只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为"feed" 操作, 标记的方法是使用tf.placeholder()为这些操作创建占位符.

 

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import tensorflow as tf

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

with tf.Session() as sess:
    #feed_dict是字典形式传值
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
    
 # output:
# [array([ 14.], dtype=float32)]

 

 

原文地址:https://www.cnblogs.com/xmeo/p/7156924.html