TensorFlow基础入门

TensorFlow基础入门

总结TensorFlow基础入门的相关知识点,原谅博主很菜,真的很基础。。。。

TensorFlow构建数据流图

结合对数据流图的讲解和基础的python代码,来简单入门我们会用到的数据流图

  1. 简单数据流图简单数据流图
    数据从左侧进入,所以我们从左向右看
    1)最开始时,可看到两个值5和3流入该数据流图。它们可能来自另一个数据流图,也可能读取自某个文件,或是由客户直接输入。
    2)这些初始值被分别传入两个明确的“input”节点(图中分别以a、b标识)。这些“input”节点的作用仅仅是传递它们的输入值—(节点a接收到输入值5)后,将同样的数值输出给节点c和节点d,节点b对其输入值3也完成同样的动作。
    3)节点c代表乘法运算。它分别从节点a和b接收输入值5和3,并将运算结果15输出到节点e。与此同时,节点d对相同的两个输入执行加法运算,并将计算结果8传递给节点e。
    4)最后,该数据流图的终点(节点e是另一个“add”节点)。它接收输入值15和8,将两者相加,然后输出该数据流图的最终结果23。
    直接上代码:
import tensorflow as tf
# Build our graph nodes, starting from the inputs
	a = tf.constant(5, name="input_a")
	b = tf.constant(3, name="input_b")
	c = tf.multiply(a,b, name="mul_c")
	d = tf.add(a,b, name="add_d")
	e = tf.add(c,d, name="add_e")
# Open up a TensorFlow Session
	sess = tf.Session()

# Execute our output node, using our Session
	output = sess.run(e)

# Open a TensorFlow SummaryWriter to write our graph to disk
	writer = tf.summary.FileWriter('./my_graph', sess.graph)

# Close our SummaryWriter and Session objects
	writer.close()
	sess.close()

# To start TensorBoard after running this file, execute the following command:
# $ tensorboard --logdir='./my_graph'

  1. 张量思维思考问题
    简单数据流图张量表示图
    现在不再使用两个独立的输入节点,而是换成了一个可接收向量(或1阶张量)的节点。与之前的版本相比,这个新的流图有如下优点:
    1)客户只需将输入送给单个节点,简化了流图的使用。
    2)那些直接依赖于输入的节点现在只需追踪一个依赖节点,而非两个。
    3)这个版本的流图可接收任意长度的向量,从而使其灵活性大大增强,我们还可对这个流图施加一条严格的约束。(如要求输入的长度必须为2)
import tensorflow as tf
	a = tf.constant([5,3],name  = "input_a")
	b = tf.reduce_prod(a,name = "prod_b")
	c = tf.reduce_sum(a,name = "sum_c")
	d = tf.add(c,d,name = "add_d")
  1. 运算符 一元运算符
    二元运算符

  2. TensorFlow的一些对象
    1)Graph
    创建新的数据流图,将默认数据流图忽略
    code1
    获取默认数据流图的句柄
    code2
    一定不要将默认数据流图和用户创建的数据流图混合使用!

    2)Session
    Session基本用法
    fetches参数
    fetches参数接收任意的数据流图元素(Op或Tensor对象),后者指定了用户希望执行的对象。如果请求对象为Tensor对象,则run()的输出将为一NumPy数组;如果请求对象为一个Op,则输出将为None

    feed_dict参数
    参数feed_dict用于覆盖数据流图中的Tensor对象值,它需要Python字典对象作为输入。字典中的“键”为指向应当被覆盖的Tensor对象的句柄,而字典的“值”可以是 数字、字符串、列表或NumPy数组(之前介绍过)。这些“值”的类型必须与Tensor的“键”相同,或能够转换为相同的类型。下面通过一些代码来展示如何利用 feed_dict重写之前的数据流图中a的值:
    feed_dict参数
    Session的关闭
    Session 的关闭

    3)利用占位节点添加输入
    placeholder用法
    placeholder用法

    4)Variable对象
    创建Variable对象
    创建Variable对象
    Variables对象的初值通常是全0、全1或用随机数填充的阶数较高的张量。为使创建具有这些常见类型初值的张量更加容易,TensorFlow提供了大量辅助Op,如 tf.zeros()、tf.ones()、tf.random_normal()和tf.random_uniform(),每个Op都接收一个shape参数,以指定所创建的Tensor对象的形状:
    创建Variable对象
    Variable对象初始化
    Variable对象初始化
    如果只需要对数据流图中定义的一个Variable对象子集初始化,可使用tf.initialize_variables()。该函数可接收一个要进行初始化的Variable对象列表:
    Variable对象初始化
    Variable对象修改
    要修改Variable对象的值,可使用Variable.assign()方法。该方法的作用是为Variable对象赋予新值。请注意Variable.assign()是一个Op,要使其生效必须在一 个Session对象中运行。

    5)通过名字作用域组织数据流图
    通过名字作用域组织数据流图

  3. 练习:综合运用各种组件

import tensorflow as tf
import numpy as np

# Explicitly create a Graph object
graph = tf.Graph()

with graph.as_default():
    
    with tf.name_scope("variables"):
        # Variable to keep track of how many times the graph has been run
        global_step = tf.Variable(0, dtype=tf.int32, name="global_step")
        
        # Variable that keeps track of the sum of all output values over time:
        total_output = tf.Variable(0.0, dtype=tf.float32, name="total_output")
    
    # Primary transformation Operations
    with tf.name_scope("transformation"):
        
        # Separate input layer
        with tf.name_scope("input"):
            # Create input placeholder- takes in a Vector 
            a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")
    
        # Separate middle layer
        with tf.name_scope("intermediate_layer"):
            b = tf.reduce_prod(a, name="product_b")
            c = tf.reduce_sum(a, name="sum_c")
        
        # Separate output layer
        with tf.name_scope("output"):
            output = tf.add(b, c, name="output")
        
    with tf.name_scope("update"):
        # Increments the total_output Variable by the latest output
        update_total = total_output.assign_add(output)
        
        # Increments the above `global_step` Variable, should be run whenever the graph is run
        increment_step = global_step.assign_add(1)
    
    # Summary Operations
    with tf.name_scope("summaries"):
        avg = tf.div(update_total, tf.cast(increment_step, tf.float32), name="average")
        
        # Creates summaries for output node
        tf.scalar_summary(b'Output', output, name="output_summary")
        tf.scalar_summary(b'Sum of outputs over time', update_total, name="total_summary")
        tf.scalar_summary(b'Average of outputs over time', avg, name="average_summary")
    
    # Global Variables and Operations
    with tf.name_scope("global_ops"):
        # Initialization Op
        init = tf.initialize_all_variables()    
        # Merge all summaries into one Operation
        merged_summaries = tf.merge_all_summaries()

# Start a Session, using the explicitly created Graph
sess = tf.Session(graph=graph)

# Open a SummaryWriter to save summaries
writer = tf.train.SummaryWriter('./improved_graph', graph)

# Initialize Variables
sess.run(init)
def run_graph(input_tensor):
    """
    Helper function; runs the graph with given input tensor and saves summaries
    """
    feed_dict = {a: input_tensor}
    out, step, summary = sess.run([output, increment_step, merged_summaries], feed_dict=feed_dict)
    writer.add_summary(summary, global_step=step)

运行练习

# Run the graph with various inputs
run_graph([2,8])
run_graph([3,1,3,3])
run_graph([8])
run_graph([1,2,3])
run_graph([11,4])
run_graph([4,1])
run_graph([7,3,1])
run_graph([6,3])
run_graph([0,2])
run_graph([4,5,6])

保存结果

# Write the summaries to disk
writer.flush()

# Close the SummaryWriter
writer.close()

# Close the session
sess.close()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值