原
tensorflow学习笔记:sess.run(tf.global_variables_initializer()) 做了什么?
一步步看源代码:(代码在后面)
global_variables_initializer
返回一个用来初始化 计算图中 所有global variable
的op
。
- 这个
op
到底是啥,还不清楚。 - 函数中调用了
variable_initializer()
和global_variables()
- 这个
global_variables()
返回一个Variable list
,里面保存的是gloabal variables
。variable_initializer()
将Variable list
中的所有Variable
取出来,将其variable.initializer
属性做成一个op group
。- 然后看
Variable
类的源码可以发现,variable.initializer
就是一个assign op
。
所以: sess.run(tf.global_variables_initializer())
就是 run
了 所有global Variable
的 assign op
,这就是初始化参数的本来面目。
def global_variables_initializer():
"""Returns an Op that initializes global variables.
Returns:
An Op that initializes global variables in the graph.
"""
return variables_initializer(global_variables())
def global_variables():
"""Returns global variables.
Returns:
A list of `Variable` objects.
"""
return ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
def variables_initializer(var_list, name="init"):
"""Returns an Op that initializes a list of variables.
Args:
var_list: List of `Variable` objects to initialize.
name: Optional name for the returned operation.
Returns:
An Op that run the initializers of all the specified variables.
"""
if var_list:
return control_flow_ops.group(*[v.initializer for v in var_list], name=name)
return control_flow_ops.no_op(name=name)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
class Variable(object):
def _init_from_args(self, ...):
self._initializer_op = state_ops.assign(
self._variable, self._initial_value,
validate_shape=validate_shape).op
@property
def initializer(self):
"""The initializer operation for this variable."""
return self._initializer_op
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-8cccb36679.css" rel="stylesheet">
</div>
<script>
(function(){
function setArticleH(btnReadmore,posi){
var winH = $(window).height();
var articleBox = $("div.article_content");
var artH = articleBox.height();
if(artH > winH*posi){
articleBox.css({
'height':winH*posi+'px',
'overflow':'hidden'
})
btnReadmore.click(function(){
articleBox.removeAttr("style");
$(this).parent().remove();
})
}else{
btnReadmore.parent().remove();
}
}
var btnReadmore = $("#btn-readmore");
if(btnReadmore.length>0){
if(currentUserName){
setArticleH(btnReadmore,3);
}else{
setArticleH(btnReadmore,1.2);
}
}
})()
</script>
</article>