2017-12-11 3 views
1

sess.run(init)がforループにあるかどうかにかかわらず、結果は同じです。なぜこれが当てはまるのか誰にも分かりませんか?初期化はテンソルフローで実際に何をしますか?tf.global_variables_initializer()を複数回実行すると結果が変わらないのはなぜですか?

==> main.py <== 
#!/usr/bin/env python 
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: 

import tensorflow as tf 

x = tf.Variable(1) 
init = tf.global_variables_initializer() 

with tf.Session() as sess: 
    sess.run(init) 
    for i in xrange(5): 
     x = x + 1 
     print(x.eval()) 

==> main_rep.py <== 
#!/usr/bin/env python 
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: 

import tensorflow as tf 

x = tf.Variable(1) 
init = tf.global_variables_initializer() 

with tf.Session() as sess: 
    for i in xrange(5): 
     sess.run(init) 
     x = x + 1 
     print(x.eval()) 

答えて

0

は問題が、あなたは基本的にあなたの変数xを上書きしているxという名前の新しいテンソルを作成している

x = x + 1

sess.run(init)ではありませんが、この文に存在しています。あなたはの出力を取得します

import tensorflow as tf 

x = tf.Variable(1) 
init = tf.global_variables_initializer() 

with tf.Session() as sess: 
    for i in xrange(5): 
     sess.run(init) 
     x = x + 1 
     print(x.eval()) 
     print(x) 

2 
Tensor("add:0", shape=(), dtype=int32) 
3 
Tensor("add_1:0", shape=(), dtype=int32) 
4 
Tensor("add_2:0", shape=(), dtype=int32) 
5 
Tensor("add_3:0", shape=(), dtype=int32) 
6 
Tensor("add_4:0", shape=(), dtype=int32) 

あなたが見ることができるように、新しいテンソルが作成たびを取得してその実行にこのコードを確認するには。 xが確実に初期値を取得したい場合は、変数の再作成を行わなくてはなりません。あなたができる方法の1つは、loadの操作を利用することです。

2 
<tf.Variable 'Variable:0' shape=() dtype=int32_ref> 
2 
<tf.Variable 'Variable:0' shape=() dtype=int32_ref> 
2 
<tf.Variable 'Variable:0' shape=() dtype=int32_ref> 
2 
<tf.Variable 'Variable:0' shape=() dtype=int32_ref> 
2 
<tf.Variable 'Variable:0' shape=() dtype=int32_ref> 
:あなたはの出力が得られます

y = tf.Variable(1) 
init = tf.global_variables_initializer() 

with tf.Session() as sess: 
    for i in xrange(5): 
     sess.run(init) 
     y.load(y.eval() + 1) 
     print(y.eval()) 
     print(y) 

:この例を考えてみましょう

関連する問題