• Tensorflow2(预课程)---1.4.1、自动计算梯度


    Tensorflow2(预课程)---1.4.1、自动计算梯度

    一、总结

    一句话总结:

    将变量指定为Variable,就不需要tape.watch([a, b, c])步骤了,tensorflow自动给你做了
    import tensorflow as tf 
    
    x = tf.constant(1.)
    a = tf.constant(2.)
    b = tf.constant(3.)
    c = tf.constant(4.)
    
    
    with tf.GradientTape() as tape:
        tape.watch([a, b, c])
        y = a**2 * x + b * x + c
    
    
    [dy_da, dy_db, dy_dc] = tape.gradient(y, [a, b, c])
    
    print(dy_da)
    print(dy_db)
    print(dy_dc)
    
    
    tf.Tensor(4.0, shape=(), dtype=float32)
    tf.Tensor(1.0, shape=(), dtype=float32)
    tf.Tensor(1.0, shape=(), dtype=float32)

    1、计算梯度的数据要是浮点类型,如何指定?

    x = tf.Variable(1.)

    二、1.4.1、自动计算梯度

    博客对应课程的视频位置:

    import tensorflow as tf 
    
    x = tf.constant(1.)
    a = tf.constant(2.)
    b = tf.constant(3.)
    c = tf.constant(4.)
    
    
    with tf.GradientTape() as tape:
    	tape.watch([a, b, c])
    	y = a**2 * x + b * x + c
    
    
    [dy_da, dy_db, dy_dc] = tape.gradient(y, [a, b, c])
    
    print(dy_da)
    print(dy_db)
    print(dy_dc)
    
    tf.Tensor(4.0, shape=(), dtype=float32)
    tf.Tensor(1.0, shape=(), dtype=float32)
    tf.Tensor(1.0, shape=(), dtype=float32)
    

    自己试下auto gradient:Variable

    In [1]:
    import tensorflow as tf 
    
    # 将变量指定为Variable,就不需要tape.watch([a, b, c])步骤了,tensorflow自动给你做了
    x = tf.Variable(1.)
    a = tf.Variable(2.)
    b = tf.Variable(3.)
    c = tf.Variable(4.)
    print(x)
    
    <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
    
    In [2]:
    with tf.GradientTape() as tape:
    	y = a**2 * x + b * x + c
    
    [dy_da, dy_db, dy_dc] = tape.gradient(y, [a, b, c])
    
    print(dy_da)
    print(dy_db)
    print(dy_dc)  
    
    tf.Tensor(4.0, shape=(), dtype=float32)
    tf.Tensor(1.0, shape=(), dtype=float32)
    tf.Tensor(1.0, shape=(), dtype=float32)
    
    In [ ]:
     
     
    将变量指定为Variable,就不需要tape.watch([a, b, c])步骤了,tensorflow自动给你做了
    我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站: fanrenyi.com;有各种前端、后端、算法、大数据、人工智能等课程。
    博主25岁,前端后端算法大数据人工智能都有兴趣。
    大家有啥都可以加博主联系方式(qq404006308,微信fan404006308)互相交流。工作、生活、心境,可以互相启迪。
    聊技术,交朋友,修心境,qq404006308,微信fan404006308
    26岁,真心找女朋友,非诚勿扰,微信fan404006308,qq404006308
    人工智能群:939687837

    作者相关推荐

  • 相关阅读:
    OpenCascade Ray Tracing Rendering
    Create New Commands in Tcl
    OpenCascade Modeling Algorithms Fillets and Chamfers
    OpenCascade Modeling Algorithms Boolean Operations
    Construction of Primitives in Open Cascade
    Open Cascade Data Exchange STL
    Tcl Tk Introduction
    Open Cascade DataExchange IGES
    Netgen mesh library : nglib
    Hello Netgen
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/13569193.html
Copyright © 2020-2023  润新知