zoukankan      html  css  js  c++  java
  • 深度学习TensorFlow2:如何使用Variables创建、使用、跟踪变量?

    创建一个变量

    import tensorflow as tf
    my_var = tf.Variable(tf.ones([2,3]))
    print(my_var)
    try:
        with tf.device("/device:GPU:0"):
            v = tf.Variable(tf.zeros([10, 10]))
            print(v)
    except:
        print('no gpu')
    <tf.Variable 'Variable:0' shape=(2, 3) dtype=float32, numpy=
    array([[1., 1., 1.],
           [1., 1., 1.]], dtype=float32)>
    no gpu

    使用变量

    a = tf.Variable(1.0)
    b = (a+2) *3
    print(b)
    tf.Tensor(9.0, shape=(), dtype=float32)
    a = tf.Variable(1.0)
    b = (a.assign_add(2)) *3
    print(b)
    tf.Tensor(9.0, shape=(), dtype=float32)

    变量跟踪

    class MyModuleOne(tf.Module):
        def __init__(self):
            self.v0 = tf.Variable(1.0)
            self.vs = [tf.Variable(x) for x in range(10)]
    
    class MyOtherModule(tf.Module):
        def __init__(self):
            self.m = MyModuleOne()
            self.v = tf.Variable(10.0)
    
    m = MyOtherModule()
    print(m.variables)
    len(m.variables)
    (<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=10.0>, <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=0>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=2>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=4>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=6>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=7>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=8>, <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=9>)
  • 相关阅读:
    WebClient.UploadData 方法 上载文件数据
    webclient提交并接受返回
    webClient上载下载
    斯特林反演与伯恩赛德引理
    Re0: 从 1 开始的省选前生活
    Windows 8将可能带动触摸屏的发展
    后PC时代的那些事
    关于ASP网页在IIS7.5下访问数失效
    Windows 要终结了?微软要推超级系统?
    未来10年的开放式互联网
  • 原文地址:https://www.cnblogs.com/peijz/p/12840922.html
Copyright © 2011-2022 走看看