zoukankan      html  css  js  c++  java
  • 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

    作者相关推荐

  • 相关阅读:
    EM
    解决使用bootstrap modal时,icon-picker组件被遮挡问题
    记一次cpu100%问题排查过程
    docker安装nexus搭建maven私库
    记一次bootstrap table使用中的遭遇
    数据的逻辑结构与存储结构的基本概念(数据结构巩固一)
    前端js函数中直接获取springmvc后台model中传值
    springboot+vue部署后提示找不到css
    将springboot的jar包添加到windows服务及遇到的问题及其解决思路
    springboot打包jar后读取资源文件
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/13569193.html
Copyright © 2011-2022 走看看