tensorflow关于共享变量的理解

变量名、共享变量、变量空间的相关关系

相关函数

  • 几点说明
    1. tf.name_scope() 主要管理op的命名空间的函数,也可以对变量进行命名
    2. tf.variable_scope 主要管理变量空间的函数
    3. get_variable和Variable 中的name指的计算图中的name,与程序中的变量名无关
    4. tf.get_variable()创建的变量名不受tf.name_scope的影响,即创建的变量的name没有name_scope定义的前缀,
    5. tf.get_variable() 在未指定共享变量时,如果重名会报错
    6. tf.Variable()会自动检测有没有变量重名,一律创建新的变量,如果有则会自行处理,即在name后面加上_+处理
    7. tf.Variable()受到tf.name_scope的影响
    8. 用tf.name_scope创建相同的域名的时候,会自动对重复的域名进行处理
    9. 用tf.variable_scope创建相同的域名的时候,会自动对重复的域名进行处理
    10. 指定共享变量的方式:2种with tf.variable_scope(scope_name,reuse=True),
      tf.get_variable_scope().reuse_variables()
    11. 共享变量主要与tf.get_variable()和tf.variable_scope有关

以上的几点是自己总结的根据下面的代码

import tensorflow as tf 
import numpy as np 
import matplotlib.pyplot as plt
import os

def add_layer(inputs,in_size,out_size,n_layer,activation_funtion=None):
    layer_name='layer%s'%n_layer
    with tf.name_scope('layer'):
        with tf.name_scope('weight'):
           

            Weights=tf.Variable(tf.random_normal([in_size,out_size]),name='W')
            if activation_funtion==None:
                Weights_test=tf.Variable(tf.random_normal([in_size,out_size]),name='W')
                print(Weights_test.name) 
            print(Weights.name)
                       
            tf.summary.histogram(layer_name+'/Weights',Weights)  #各层网络权重,偏置的分布,用histogram_summary函数
        with tf.name_scope('biases'):
            biases=tf.Variable(tf.zeros([1,out_size])+0.1,name='b')
            tf.summary.histogram(layer_name+'/biases',biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b=tf.matmul(inputs,Weights)+biases  #inputs与weight 顺序不能换
        if activation_funtion is None:
            output=Wx_plus_b
        else:
            output=activation_funtion(Wx_plus_b)
        tf.summary.histogram(layer_name+'/output',output)
    return output
 
x_data = np.linspace(-1,1,300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise
with tf.name_scope('inputs'):
    xs=tf.placeholder(tf.float32,[None,1],name='x_in')
    ys=tf.placeholder(tf.float32,[None,1],name='y_in')
 
l1=add_layer(xs,1,10,n_layer=1,activation_funtion=tf.nn.relu)
prediction=add_layer(l1,10,1,n_layer=2,activation_funtion=None)
 
# loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),
#                     reduction_indices=[1]))
with tf.name_scope('loss'):
    loss=tf.reduce_mean(tf.square(ys-prediction))
    tf.summary.scalar('loss',loss)  #数值如学习率,损失函数用scalar_summary函数,tf.scalar_summary(节点名称,获取的数据)
optimizer=tf.train.GradientDescentOptimizer(0.1)
with tf.name_scope('train'):
    train=optimizer.minimize(loss)
 
init = tf.global_variables_initializer()  # 替换成这样就好
sess=tf.Session()
sess.run(init)
#整个图经常需要检测许许多多的值,也就是许多值需要summary operation,一个个去run来启动太麻烦了,所以就合并所有获得的值
merged=tf.summary.merge_all()#合并所有的summary data的获取函数,merge_all 可以将所有summary全部保存到磁盘,以便tensorboard显示。如果没有特殊要求,一般用这一句就可一显示训练时的各种信息了。
writer=tf.summary.FileWriter("logs/",sess.graph)#把图保存到一个路径,FileWriter从tensorflow获取summary data,然后保存到指定路径的日志文件中
for i in range(1000):
    sess.run(train,feed_dict={xs:x_data,ys:y_data})
    if i+1%50==0:
        #summary的操作对于整个图来说相当于是外设,因为tensorflow是由结果驱动的,而图的结果并不依赖于summary操作,所以summary操作需要被run
        rs=sess.run(merged,feed_dict={xs:x_data,ys:y_data})#运行所有合并所有的图,获取summary data函数节点和graph是独立的,调用的时候也需要运行session
        writer.add_summary(rs,i)#把数据添加到文件中,每一次run的信息和得到的数据加到writer里面,主要是描述数据变化,所以要这样,若是只有流图,就不需要这样
 
        # print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
with tf.variable_scope("a_variable_scope") as scope:
    initializer = tf.constant_initializer(value=3)
    var2 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
    #scope.reuse_variables()  # 声明前面出现的变量为共享变量
    var21=tf.get_variable(name='wangjuin',shape=[1])
    var3_reuse = tf.get_variable(name='var2', shape=[1])

    var4 = tf.get_variable(name='var4', shape=[1])
    scope.reuse_variables()
    var4_reuse = tf.get_variable(name='var4',  shape=[1])
    vartest = tf.Variable(name='var5',initial_value=[4], dtype=tf.float32)
    var5 = tf.Variable(name='vartest',initial_value=[4], dtype=tf.float32)
with tf.name_scope('layer_junjun'):
    initializer = tf.constant_initializer(value=3)
    var210=tf.Variable(name='ddddd',initial_value=[4], dtype=tf.float32)

with tf.name_scope('layer_junjun'):
    initializer = tf.constant_initializer(value=3)
    var211=tf.Variable(name='ddddd',initial_value=[4], dtype=tf.float32)
    test_reuse = tf.get_variable(name='var4',  shape=[1])

with tf.variable_scope("scope_junjun") as scope:
    initializer = tf.constant_initializer(value=3)
    var110=tf.Variable(name='ddddd',initial_value=[4], dtype=tf.float32)

with tf.variable_scope("scope_junjun") as scope:
    initializer = tf.constant_initializer(value=3)
    var120=tf.Variable(name='ddddd',initial_value=[4], dtype=tf.float32)


with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(var2.name)  # a_variable_scope/var3:0
    print(var21.name)
    print(sess.run(var2))  # [ 3.]
    print(var3_reuse.name)  # a_variable_scope/var3:0
    print(sess.run(var3_reuse))  # [ 3.]
    print(var4.name)  # a_variable_scope/var4:0
    print(sess.run(var4))  # [ 4.]
    print(var4_reuse.name)  # a_variable_scope/var4_1:0
    print(sess.run(var4_reuse))
    print(vartest.name)
    print(var5.name)
    print(var210.name)
    print(var211.name)
    print(test_reuse.name)
    print(var110.name)
    print(var120.name)

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值