python - tensorflow: initialization of variables inside function -
newbee tensorflow. i'm trying write simple net following code:
import tensorflow tf import tensorflow.contrib tfc import tensorflow.contrib.layers tfcl def generator_deconv(z, kernel): tf.variable_scope("generator", reuse=true): weights = tf.get_variable("weights") biases = tf.get_variable("biases") result = tf.matmul(z, weights) result = tf.add(result, biases) result = tf.reshape(result, tf.stack([tf.shape(result)[0],13,4,1])) result = tf.nn.conv2d_transpose(result, kernel, output_shape=[tf.shape(result)[0],25,8,1], strides=[1,2,2,1], padding="same") result = tf.nn.conv2d_transpose(result, kernel, output_shape=[tf.shape(result)[0],50,15,1], strides=[1,2,2,1], padding="same") result = tf.nn.conv2d_transpose(result, kernel, output_shape=[tf.shape(result)[0],100,30,1], strides=[1,2,2,1], padding="same") return result kernel = tf.constant(1.0, shape=[4,4,1,1]) protype = tf.constant(1.0, shape=[3,4]) init = tf.global_variables_initializer() config = tf.configproto() config.gpu_options.allocator_type = 'bfc' config.gpu_options.allow_growth=true tf.variable_scope("generator"): t1 = tf.get_variable("weights",shape=[4,52]) t2 = tf.get_variable("biases", shape=[52]) test = generator_deconv(protype,kernel) tf.session(config=config) sess: sess.run(init) sess.run(tf.shape(t1)) sess.run(tf.shape(t2)) sess.run(tf.shape(test))
but got error:
tensorflow.python.framework.errors_impl.failedpreconditionerror: attempting use uninitialized value generator/weights
for last line
sess.run(tf.shape(test))
checked official api of tensorflow still don't know what's wrong code.
================================update==========================
found 2 ways fix it
1.if replace
sess.run(init)
by
sess.run(tf.global_variables_initializer())
then whole code works.
or
2.run
init = tf.global_variables_initializer() tf.session(config=config) sess: sess.run(init) sess.run(tf.shape(t1)) sess.run(tf.shape(t2)) sess.run(tf.shape(test))
again works.
but don't understand why
i removed parts of code you:
init = tf.global_variables_initializer() tf.variable_scope("generator"): t1 = tf.get_variable("weights",shape=[4,52]) t2 = tf.get_variable("biases", shape=[52]) tf.session(config=config) sess: sess.run(init) sess.run(tf.shape(t1))
you add variables graph after saved result of calling global_variables_initializer(). in fix call function after added variables want initialize graph, , initialized.
hope helps!
Comments
Post a Comment