Reputation: 23
X=tf.placeholder(tf.float32,[None,32,32,3])
y=tf.placeholder(tf.int64,[None])
is_training=tf.placeholder(tf.bool)
def simple_model(X,y):
Wconv1=tf.get_variable("Wconv1",shape=[7,7,3,32],use_resource=True)
bconv1=tf.get_variable('bconv1',shape=[32])
W1=tf.get_variable('W1',shape=[5408,10])
b1=tf.get_variable('b1',shape=[10])
a1=tf.nn.conv2d(X,Wconv1,[1,2,2,1],'VALID')+bconv1
h1=tf.nn.relu(a1)
h1_flat=tf.reshape(h1,[-1,5408])
y_out=tf.matmul(h1_flat,W1)+b1
return y_out
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
sess.run(simple_model(X,y),feed_dict={X:X_train,y:y_train})
error is
PreconditionError Attempting to use uninitialized variable
Wconv1
I dont know what wrong with code?
Upvotes: 2
Views: 33
Reputation: 59681
tf.global_variables_initializer
makes an initialization op for all the global variables created up to that point. This means that if you create other variables later, they will not be initialized by the operation. This is because variable initializers just hold a list of the variables they have to initialize, and this does not change as you add more variables (in fact, tf.global_variables_initializer()
is just a shortcut for tf.variables_initializer(tf.global_variables())
or tf.variables_initializer(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES))
). In your case, the variables are being created in the second call to sess.run
, after you create init
earlier. You need to create the initialization operation after you have created your model with the variables:
X=tf.placeholder(tf.float32,[None,32,32,3])
y=tf.placeholder(tf.int64,[None])
is_training=tf.placeholder(tf.bool)
def simple_model(X,y):
Wconv1=tf.get_variable("Wconv1",shape=[7,7,3,32],use_resource=True)
bconv1=tf.get_variable('bconv1',shape=[32])
W1=tf.get_variable('W1',shape=[5408,10])
b1=tf.get_variable('b1',shape=[10])
a1=tf.nn.conv2d(X,Wconv1,[1,2,2,1],'VALID')+bconv1
h1=tf.nn.relu(a1)
h1_flat=tf.reshape(h1,[-1,5408])
y_out=tf.matmul(h1_flat,W1)+b1
return y_out
my_model = simple_model(X,y)
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
sess.run(my_model, feed_dict={X:X_train,y:y_train})
Upvotes: 1