当前位置: 代码迷 >> 综合 >> (转载)TensorFlow 学习(三)—— Variables(tf.initialize_all_variables()/tf.global_variables_initializer())
  详细解决方案

(转载)TensorFlow 学习(三)—— Variables(tf.initialize_all_variables()/tf.global_variables_initializer())

热度:95   发布时间:2023-12-18 01:11:19.0

tf.initialize_all_variables()/tf.global_variables_initializer()

What are the differences between tf.initialize_all_variables() and tf.global_variables_initializer()

注意对于 tf.initialize_all_variables() 接口,TensorFlow 文档有一个重要说明:

tf.initialize_all_variables(): THIS FUNCTION IS DEPRECATED. It will be removed after 2017-03-02. Instructions for updating: Use tf.global_variables_initializer instead.

  • tf.initialize_all_variables() 该函数将不再使用,在 2017年3月2号以后;
  • 用 tf.global_variables_initializer() 替代 tf.initialize_all_variables()

1. 变量初始化

变量初始化的标准形式:

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
  • 1
  • 2
  • 3

当然也可简写为:

tf.Session().run(tf.initialize_all_variables())
  • 1

如何有选择地初始化部分变量呢?使用 tf.initialize_variables(),比如要初始化v_6, v_7, v_8三个变量:

init_new_vars_op = tf.initialize_variables([v_6, v_7, v_8])
sess.run(init_new_vars_op)
  • 1
  • 2

2. 识别未被初始化的变量

用 try & except 语句块捕获:

uninit_vars = []
for var in tf.all_variables():try:sess.run(var)except tf.errors.FailedPreconditionError:uninit_vars.append(var)init_new_vars_op = tf.initialize_variables(uninit_vars)
  •  
  • In TensorFlow is there any way to just initialize uninitialised variables?

3. 变量的更新

>> state = tf.Variable(1, name='counter')
>> add_one = tf.add(state, tf.constant(1))
>> update = tf.assign(state, add_one)
>> with tf.Session() as sess:sess.run(tf.gloabl_variables_initializer())sess.run(state)for _ in range(3):sess.run(update)print(sess.run(state))
  相关解决方案