zoukankan      html  css  js  c++  java
  • Tensorflow基本操作理解

    1. TensorsTensorFlow的数据中央控制单元是tensor(张量),一个tensor由一系列的原始值组成,这些值被形成一个任意维数的数组。一个tensor的列就是它的维度。
    2. The Computational Graph TensorFlow核心程序由2个独立部分组成:
        a:Building the computational graph构建计算图
        b:Running the computational graph运行计算图
    一个computational graph(计算图)是一系列的TensorFlow操作排列成一个节点图。
    node1 = tf.constant(3.0, dtype=tf.float32)  
    node2 = tf.constant(4.0)# also tf.float32 implicitly  
    print(node1, node2)  

    最后打印结果是:

    Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0",shape=(), dtype=float32)  

    要想打印最终结果,我们必须用到session:一个session封装了TensorFlow运行时的控制和状态

    sess = tf.Session()  
    print(sess.run([node1, node2]))  

    我们可以组合Tensor节点操作(操作仍然是一个节点)来构造更加复杂的计算,

    node3 = tf.add(node1, node2)  
    print("node3:", node3)  
    print("sess.run(node3):", sess.run(node3))  

    打印结果是:

    node3:Tensor("Add:0", shape=(), dtype=float32)  
    sess.run(node3):7.0  

    3. TensorFlow提供一个统一的调用称之为TensorBoard,它能展示一个计算图的图片;如下面这个截图就展示了这个计算图

    4 一个计算图可以参数化的接收外部的输入,作为一个placeholders(占位符),一个占位符是允许后面提供一个值的。

    a = tf.placeholder(tf.float32)  
    b = tf.placeholder(tf.float32)  
    adder_node = a + b  # + provides a shortcut for tf.add(a, b)  
    这里有点像一个function (函数)或者lambda表达式,我们定义了2个输入参数a和b,然后提供一个在它们之上的操作。我们可以使用feed_dict(传递字典)参数传递具体的值到run方法的占位符来进行多个输入,从而来计算这个图。
    print(sess.run(adder_node, {a:3, b:4.5}))  
    print(sess.run(adder_node, {a: [1,3], b: [2,4]}))  

    结果是:

    7.5  
    [3.  7.]  

    在TensorBoard,计算图类似于这样:

    我们可以增加另外的操作来让计算图更加复杂,比如

    add_and_triple = adder_node *3.  
    print(sess.run(add_and_triple, {a:3, b:4.5}))  
    输出结果是:  
    22.5  

    5 要实现初始化所有全局变量的TensorFlow子图的的处理是很重要的,直到我们调用sess.run,这些变量都是未被初始化的。既然x是一个占位符,我们就可以同时地对多个x的值进行求值linear_model,例如:

    W = tf.Variable([.3], dtype=tf.float32)  
    b = tf.Variable([-.3], dtype=tf.float32)  
    x = tf.placeholder(tf.float32)  
    linear_model = W*x + b  
    init = tf.global_variables_initializer()  
    sess.run(init)  
    print(sess.run(linear_model, {x: [1,2,3,4]}))  
    求值linear_model   
    输出为  
    [0.  0.30000001  0.60000002  0.90000004]  
  • 相关阅读:
    Apache Shiro和Spring Security的详细对比
    Oauth2.0 用Spring-security-oauth2 来实现
    引入AOP 报错 error at ::0 formal unbound in pointcut
    日记网站收藏
    Spring 在web 容器中的启动过程
    knockoutjs如何动态加载外部的file作为component中的template数据源
    ORACLE触发器详解
    浅谈数据库分表
    HTTP协议详解(真的很经典)
    ThinkPHP的四种URL模式 URL_MODEL
  • 原文地址:https://www.cnblogs.com/chaofn/p/8962338.html
Copyright © 2011-2022 走看看