实际需要 global_variables_initializer() 时 [英] When global_variables_initializer() is actually required

查看:53
本文介绍了实际需要 global_variables_initializer() 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import tensorflow as tf
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
# model = tf.global_variables_initializer()
with tf.Session() as session:
        print("x = ", session.run(x)) 
        # session.run(model)
        print("y = ", session.run(y))

我无法理解何时实际需要 global_variables_initializer().在上面的代码中,如果我们取消注释第 4 行 &7、我可以执行代码并查看值.如果我按原样运行,我会看到崩溃.

I was not able to understand when global_variables_initializer() is actually required. In the above code, if we uncomment lines 4 & 7, I can execute the code and see the values. If I run as-is, I see a crash.

我的问题是它正在初始化哪些变量.x 是一个不需要初始化的常量,y 是一个没有被初始化但用作算术运算的变量.

My question is which variables it is initializing. x is a constant which does not need initialization and y is variable which is not being initialized but is used as an arithmetic operation.

推荐答案

tf.global_variables_initializer 是初始化所有全局变量的快捷方式.它不是必需的,您可以使用其他方法来初始化变量,或者在简单脚本的情况下,有时您根本不需要初始化它们.

tf.global_variables_initializer is a shortcut to initialize all global variables. It is not required, and you can use other ways to initialize your variables or in case of easy scripts sometimes you do not need to initialize them at all.

除了变量之外的所有东西都不需要初始化(常量和占位符).但是每个使用的变量(即使它是一个常量)都应该被初始化.这会给你一个错误,尽管 z 只是一个只有一个数字的 0-d 张量.

Everything except of variables do not require initialization (constants and placeholders). But every used variable (even if it is a constant) should be initialized. This will give you an error, although z is just 0-d tensor with only one number.

import tensorflow as tf
z = tf.Variable(4)
with tf.Session() as session:
        print(session.run(z)) 

我突出显示了所使用的词,因为如果您只有未运行的变量(或非运行依赖于它们),则不需要初始化它们.

I highlighted the word used, because if you just have variables which are not run (or non of the runs depends on them) you do not need to initialize them.

例如,此代码将毫无问题地执行,但它有 2 个变量和一个依赖于它们的操作.但是运行不需要它们.

For example this code will execute without any problems, nonetheless it has 2 variables and one operation which depends on them. But the run does not require them.

import tensorflow as tf
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
z = tf.Variable(4)
a = y + z
with tf.Session() as session:
        print("x = ", session.run(x)) 

这篇关于实际需要 global_variables_initializer() 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆