TensorFlow say Hello!

作者: SpikeKing | 来源:发表于2017-05-17 12:04 被阅读322次

    欢迎Follow我的GitHub, 关注我的简书.

    TensorFlow是Google开源的机器智能(Machine Intelligence)库, 集成大量的机器学习算法, 基于C++后端高效地执行计算, 使用Python接口开发.

    下载及安装(本文使用Python 2.7版本)

    TensorFlow

    安装成功后, 在Python文件中导入tensorflow库.

    import tensorflow as tf
    

    Pycharm IDE支持使用File Template简化文件的创建, 设置Tensor Flow模板, 默认添加中文支持, 警告抑制, tensorflow库, numpy库等.

    File Template

    Session

    TensorFlow使用计算图(Computational Graph)模式构建算法, 通过Session(会话)执行算法. 调用tf#Session获取Session对象, 调用Session#run执行算法.

    node1 = tf.constant(3.0, tf.float32)
    node2 = tf.constant(4.0)
    print (node1, node2)  # 只打印结点信息
    
    sess = tf.Session()
    print (sess.run([node1, node2])) # 运行结点
    

    输出. 只打印结点时, 显示结点的类型信息; Session执行后打印结点, 才会显示具体数据.

    (<tf.Tensor 'Const:0' shape=() dtype=float32>, <tf.Tensor 'Const_1:0' shape=() dtype=float32>)
    [3.0, 4.0]
    

    TensorFlow也提供InteractiveSession(交互式会话)模式, 在运行计算图时, 默认Session执行算法. 在交互式环境(如IPython)中便于使用, 计算图始终存在默认的Session, 避免通过变量传递当前Session.

    使用Session模式, 必须在构建整个计算图后才能执行, 每个方法都需要在Session#run中执行; 而使用InteractiveSession模式, 创建默认Session, 仅需调用所需执行方法run方法即可

    例如在执行global_variables_initializer(全局变量初始化)方法时, 两者的区别.

    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    
    sess = tf.InteractiveSession()
    tf.global_variables_initializer().run()
    

    Session模式, 如果直接调用所需执行方法run方法, 则提示错误: 没有默认Session被注册(No default session is registered).

    类型

    TensorFlow包含三种重要类型: constant(常量), placeholder(占位量), Variable(变量).

    1. 常量(constant)同其他语言的常量, 在赋值后不可修改.
    2. 占位量(placeholder)同其他语言的方法的参数, 在执行方法时设置.
    3. 变量(Variable)比较特殊, 机器学习特有属性. 对于常规的算法而言, 在输入值已知的情况下, 优化变量(参数)使损失函数的值达到最小. 因而在含有优化器(Optimizer)的算法中, 变量是动态计算(变化)的. 如果在未使用优化器时, 变量仍作为普通变量. 注意: 在使用变量之前, 需要执行初始化方法, 系统才会为其赋值.
    # 常量
    node1 = tf.constant(3.0, tf.float32)
    node2 = tf.constant(4.0)
    print (node1, node2)  # 只打印结点信息
    
    # 占位量
    a = tf.placeholder(tf.float32)
    b = tf.placeholder(tf.float32)
    adder_node = a + b  # 与调用add方法类似
    print (sess.run(adder_node, {a: 3, b: 4.5}))
    print (sess.run(adder_node, {a: [1, 3], b: [2, 4]}))
    
    # 变量
    W = tf.Variable([.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    x = tf.placeholder(tf.float32)
    linear_model = W * x + b
    sess.run(tf.global_variables_initializer())
    print ("linear_model: ", sess.run(linear_model, {x: [1, 2, 3, 4]}))
    

    Session的变量初始化方法, 即tf#global_variables_initializer.

    如果在使用变量(Variable)时, 未提前执行初始化方法, 则提示错误: "试图使用未初始化的值(Attempting to use uninitialized value)".

    实例

    非常简单的线性回归算法, 最终结果: 参数W是1, 参数b是1, 损失函数loss是0.

    TensorFlow的计算结果是近似值(无限趋近), 这与选择优化器(optimizer)有关.

    # -*-coding: utf-8-*-#
    
    # 线性回归
    # Created by C.L.Wang
    
    import os  # 避免Warning
    
    import tensorflow as tf
    
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    
    W = tf.Variable([.3], tf.float32)
    b = tf.Variable([-.3], tf.float32)
    x = tf.placeholder(tf.float32)
    
    linear_mode = W * x + b
    y = tf.placeholder(tf.float32)
    
    loss = tf.reduce_sum(tf.square(linear_mode - y))
    
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(loss)
    
    x_train = [1, 2, 3, 4]
    y_train = [0, -1, -2, -3]
    
    init = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init)
    
    for i in range(1000):
        sess.run(train, {x: x_train, y: y_train})
    
    curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
    print ("W: %s, b: %s, loss: %s" % (curr_W, curr_b, curr_loss))
    

    OK, that's all! Enjoy it!

    相关文章

      网友评论

        本文标题:TensorFlow say Hello!

        本文链接:https://www.haomeiwen.com/subject/jcalxxtx.html