美文网首页
tensorflow 入门笔记

tensorflow 入门笔记

作者: luckriver | 来源:发表于2021-10-12 17:54 被阅读0次

    简介

    tensorflow 是谷歌于2015年11月开源的通用计算框架,由谷歌大脑团队基于谷歌内部第一代深度学习框架 DistBelief 改进而来。虽然 DistBelief 已经被谷歌内部很多产品使用,但他过于依赖谷歌内部的系统架构,较难对外开源。谷歌大脑团队对其进行了改造,使得 tensorflow 的计算模型更加通过,计算速度更快、支持平台更多等。

    2019年10月 tensorflow 2.0 正式版发布,新版本加入了提升易用性的诸多新特性,例如以 tf.keras 为核心的统一高层 API、使用 tf.function 构建图模型、默认使用即时执行模式等。 TensorFlow 已经形成了一个拥有庞大版图的生态系统。TensorFlow Lite、TensorFlow.js、TensorFlow for Swift、TPU 等各种组件日益成熟。

    安装

    从 tensorflow 2.0 开始不再支持 Python 2,最终支持版本到1.15

    # tensorflow 2.0 只需要安装一次
    pip install tensorflow
    

    GPU版本的安装(仅对1.x版本)

    pip install tensorflow-gpu
    

    基础概念

    tensorflow 采用了计算图模型,hw = h + w 仅是定义了相加的操作,不会真正执行计算。计算的执行需要放在 session 当中。

    张量

    TensorFlow 使用 张量 (Tensor)作为数据的基本单位。TensorFlow 的张量在概念上等同于多维数组,我们可以使用它来描述数学中的标量(0 维数组)、向量(1 维数组)、矩阵(2 维数组)等各种量

    # 定义一个常数(标量)
    c = tf.constant(4.0)
    
    # 定义一个有2个元素的零向量
    zero_vector = tf.zeros(shape=(2))
    
    # 定义两个2×2的常量矩阵
    A = tf.constant([[1., 2.], [3., 4.]])
    B = tf.constant([[5., 6.], [7., 8.]])
    

    张量的重要属性是其名字、形状和类型。可以通过张量的 name、 shape 和 dtype 属性 方法获得。例如:

    # 查看矩阵A的形状、类型和值
    print(A.shape)      # 输出(2, 2),即矩阵的长和宽均为2
    print(A.dtype)      # 输出<dtype: 'float32'>
    print(A.name)       # 输出[[1. 2.]
                        #      [3. 4.]]
    

    计算图

    tensorflow 的计算都是通过计算图的形式进行的,tensorflow 程序基本可以分解位两个阶段:构造计算图;执行计算图

    图的节点代表了 tensorflow 当中的操作(如加、减、常亮等),而边则代表了节点之间的依赖关系。

    比如下面这段代码

    import tensorflow as tf
    
    a = tf.constant(5)
    b = tf.constant(2)
    c = tf.constant(3)
    d = tf.multiply(a,b)
    e = tf.add(c,b)
    f = tf.subtract(d,e)
    

    可以用如下的图来表示


    计算图

    这就构造了一个计算图,如果要获得计算结果,还需要运行计算图

    with tf.Session() as sess:
        result = sess.run(f)
    

    从我们引入 tensorflow 的包开始,就已经默认给我们创建了一个图

    import tensorflow as tf
    print(tf.get_default_graph())
    
    g = tf.Graph()
    print(g)
    
    Out:
    <tensorflow.python.framework.ops.Graph object at 0x7fd88c3c07d0>
    <tensorflow.python.framework.ops.Graph object at 0x7fd88c3c03d0>
    

    会话

    会话 (session) 用于执行构造好的计算图。会话拥有并管理 tensorflow 程序运行时的所有资源,计算完成后会话关闭时会回收系统资源。计算结果只能在会话中获得

    命名空间

    with tf.name_scope('inference') as scope:
        w = tf.constant([[0,0,0]],dtype=tf.float32,name='weights')
    
    print(w)
    >>>Tensor("inference/weights:0", shape=(1, 3), dtype=float32)
    
    • tf.name_scope()指定的区域中定义的对象,他们的“name”属性上会增加该命名区的区域名,用以区别对象属于哪个区域
    • name_scope只决定对象属于哪个范围,并不会对作用域产生影响

    其他

    • Placeholders 存放输入数据。可以看做是一个空的变量,在执行计算图的时候赋予具体的数值。一般用于定义输入参数
    • 变量(Variables) 在数据流图中对于普通Tensor来说,经过一次操作之后,就会转化为另一个Tensor。当前一个Tensor的使命完成之后就会被系统回收。- Variable 可以看作是是一个常驻内存,不会被轻易回收的张量。可以通过 tf.Variable 创建变量
    • 优化器 最优化模型预测值和真实值差异的算法策略

    工作流程

    • 创建测试数据
    import numpy as np
    x_data = np.random.randn(2000,3)
    w_real = [0.3,0.5,0.1]
    b_real = -0.2
    noise = np.random.randn(1,2000)*0.1
    y_data = np.matmul(w_real,x_data.T) + b_real + noise
    
    测试数据
    • 线性回归模型
    # 迭代计算次数
    NUM_STEPS = 10
    
    g = tf.Graph()
    wb_ = []
    with g.as_default():
        # placeholder定义输入输出参数
        x = tf.placeholder(tf.float32,shape=[None,3])
        y_true = tf.placeholder(tf.float32,shape=None)
    
        with tf.name_scope('inference') as scope:
            # Variable定义模型参数
            w = tf.Variable([[0,0,0]],dtype=tf.float32,name='weights')
            b = tf.Variable(0,dtype=tf.float32,name='bias')
            y_pred = tf.matmul(w,tf.transpose(x)) + b
    
    • 定义损失函数

    损失函数用于衡量模型预测值和真实值之间的差异,一般是通过最小化损失函数来达到优化模型参数的目的。常见的损失函数有均方差(MSE) 和 交叉熵

    这里选择 MSE 作为损失函数

    MSE
    with tf.name_scope('loss') as scope:
        loss = tf.reduce_mean(tf.square(y_true-y_pred))
    
    • 定义优化器

    优化器用来为损失函数寻找最小值,最常用的优化器是梯度下降。参数会沿着梯度下降的方法进行迭代直到达到最优值或者设定的迭代阈值。

    with tf.name_scope('train') as scope:
        learning_rate = 0.5
        optimizer = tf.train.GradientDescentOptimizer(learning_rate)
        train = optimizer.minimize(loss)
    
    • 会话中运行
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)      
        for step in range(NUM_STEPS):
            sess.run(train,{x: x_data, y_true: y_data})
            if (step % 5 == 0):
                print(step, sess.run([w,b])) 
                wb_.append(sess.run([w,b]))
    
        print(10, sess.run([w,b]))
    

    输出结果

    output

    和之前定义的参数 w = [0.3,0.5,0.1] 和 b = -0.2 已经比较接近了

    相关文章

      网友评论

          本文标题:tensorflow 入门笔记

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