name_scope,variable_scope作用、tf.truncated_normal()--tensorflow 基础知识

1、首先清楚tf. get_variable()和tf.variable()。因为如果使用Variable 的话每次都会新建变量,但是大多数时候我们是希望一些变量重用的,所以就用到了get_variable()。它会去搜索变量名,然后没有就新建,有就直接用。用到变量名了,就涉及到了名字域的概念。通过不同的域来区别变量名,毕竟让我们给所有变量都直接取不同名字还是有点辛苦的。所以为什么会有scope 的概念;name_scope 作用于操作,variable_scope 可以通过设置reuse 标志以及初始化方式来影响域下的变量。

2、在 tf.name_scope下时,tf.get_variable()创建的变量名不受 name_scope 的影响,而且在未指定共享变量时,如果重名会报错,tf.Variable()会自动检测有没有变量重名,如果有则会自行处理。

 
import tensorflow as tf
with tf.name_scope("hello") as name_scope:
     arr1=tf.get_variable("arr1",shape=[2,10],dtype=tf.float32)
     print(name_scope)
     print(arr1.name)
     print("scope_name:%s"% tf.get_variable_scope().original_name_scope)
运行结果:

hello/
arr1:0
scope_name:

name_scope对get_variable()创建的变量不会有任何影响;

with tf.variable_scope("hello") as variable_scope:
     arr2=tf.get_variable("arr2",shape=[2,10],dtype=tf.float32)
     print(variable_scope)
     print(variable_scope.name)
     print(arr2.name)
     print("variable_name:%s"% tf.get_variable_scope().original_name_scope)
运行结果:

<tensorflow.python.ops.variable_scope.VariableScope object at 0x000000000D9D8780>
hello
hello/arr2:0
variable_name:hello_1/

利用 variable_scope实现对get_variable()创建的变量名字加前缀

3、tf.truncated_normal()表示从截断的正态分布中输出随机值

   参数含义

mean:一个python标量或一个标量张量。要生成的随机值的均值。
stddev:一个python标量或一个标量张量。要生成的随机值的标准偏差。
seed:一个Python整数。用于创建随机种子。查看 tf.set_random_seed 行为。
dtype:数据类型。只支持浮点类型

4、

l2_loss函数

tf.nn.l2_loss(t, name=None)

解释:这个函数的作用是利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半,具体如下:

output = sum(t ** 2) / 2

tensorflow实现

import tensorflow as tf

a=tf.constant([1,2,3],dtype=tf.float32)
b=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32)

with tf.Session() as sess:
    print('a:')
    print(sess.run(tf.nn.l2_loss(a)))
    print('b:')
    print(sess.run(tf.nn.l2_loss(b)))
    sess.close()
结果a=7#(1+4+9)/2=7
b=28 #(2+8+18)/2=14(求解为距离原点的欧式距离)

 5、tf.add_to_collection()

import tensorflow as tf

v1 = tf.get_variable('v1', shape=[1], initializer=tf.ones_initializer())
v2 = tf.get_variable('v2', shape=[1], initializer=tf.zeros_initializer())

tf.add_to_collection('vc', v1)
tf.add_to_collection('vc', v2)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    vc = tf.get_collection('vc')
    print(vc)
    for i in vc:
        print(i)
        print(sess.run(i))
[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>
[ 1.]
<tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>
[ 0.]

 6、tf.nn.conv2d是TensorFlow里面实现卷积的函数,

  参考 http://www.cnblogs.com/welhzh/p/6607581.html 非常详细

原文地址:https://www.cnblogs.com/6530265oule/p/8794290.html