Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with Exercise of 01_Simple_Linear_Model #57

Closed
Saqhas opened this issue Dec 26, 2017 · 2 comments
Closed

Problem with Exercise of 01_Simple_Linear_Model #57

Saqhas opened this issue Dec 26, 2017 · 2 comments

Comments

@Saqhas
Copy link

Saqhas commented Dec 26, 2017

This is my Codes that i am using:

`def begin(reg = 0):

x = tf.placeholder(tf.float32, [None, img_size_flat])
y_true = tf.placeholder(tf.float32, [None, num_classes]) # This will store the one-hot encoded labels for the image
y_true_cls = tf.placeholder(tf.int64, [None])
weights = tf.Variable(tf.zeros([img_size_flat, num_classes])) # This when multiply with x will give the probability of the image belonging to a particular class.
biases = tf.Variable(tf.zeros([num_classes]))
logits = tf.matmul(x, weights) + biases
y_pred = tf.nn.softmax(logits)
y_pred_cls = tf.argmax(y_pred, axis=1)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y_true)
loss = tf.reduce_mean(cross_entropy)
regularizer = tf.nn.l2_loss(weights)
cost = tf.reduce_mean(loss + reg * regularizer)
`

`def optimize(num_iterations,batch_size = 100,lr = 0.5,print_loss = False,reg_lambda = 0,beta = 0):

begin(reg_lambda)
correct_prediction = tf.equal(y_pred_cls, y_true_cls)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
eff_loss = []
session = tf.Session()
session.run(tf.global_variables_initializer())
optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(cost)

for i in range(num_iterations):
    # Get a batch of training examples.
    # x_batch now holds a batch of images and
    # y_true_batch are the true labels for those images.
    x_batch, y_true_batch = data.train.next_batch(batch_size) # 
    
    # Put the batch into a dict with the proper names
    # for placeholder variables in the TensorFlow graph.
    # Note that the placeholder for y_true_cls is not set
    # because it is not used during training.
    feed_dict_train = {x: x_batch,
                       y_true: y_true_batch}

    # Run the optimizer using this batch of training data.
    # TensorFlow assigns the variables in feed_dict_train
    # to the placeholder variables and then runs the optimizer.
    session.run(optimizer,feed_dict = feed_dict_train)
    eff_loss.append(loss)
    if print_loss and num_iterations % 10000 == 0:
        #loss = tf.reduce_mean(cross_entropy)
        print('The Loss is :',loss)
feed_dict_test = {x: data.test.images,
            y_true: data.test.labels,
            y_true_cls: data.test.cls}
# Use TensorFlow to compute the accuracy.
acc = session.run(accuracy, feed_dict=feed_dict_test)

# Print the accuracy.
print("Accuracy on test-set: {0:.1%}".format(acc))
plt.plot(np.arange(num_iterations),eff_loss)
plt.show()
session.close()

`

On running the below in jupyter notebook:
optimize(500,batch_size = 100,lr = 0.8,reg_lambda = 2,beta = 0.9)

I get the below error:

`
FailedPreconditionError Traceback (most recent call last)
~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1326 try:
-> 1327 return fn(*args)
1328 except errors.OpError as e:

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
1305 feed_dict, fetch_list, target_list,
-> 1306 status, run_metadata)
1307

~/anaconda3/envs/tensorflow/lib/python3.5/contextlib.py in exit(self, type, value, traceback)
65 try:
---> 66 next(self.gen)
67 except StopIteration:

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
465 compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466 pywrap_tensorflow.TF_GetCode(status))
467 finally:

FailedPreconditionError: Attempting to use uninitialized value beta1_power_7
[[Node: beta1_power_7/read = IdentityT=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

During handling of the above exception, another exception occurred:

FailedPreconditionError Traceback (most recent call last)
in ()
----> 1 optimize(500,batch_size = 100,lr = 0.8,reg_lambda = 2,beta = 0.9)

in optimize(num_iterations, batch_size, lr, print_loss, reg_lambda, beta)
24 # TensorFlow assigns the variables in feed_dict_train
25 # to the placeholder variables and then runs the optimizer.
---> 26 session.run(optimizer,feed_dict = feed_dict_train)
27 eff_loss.append(loss)
28 if print_loss and num_iterations % 10000 == 0:

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
893 try:
894 result = self._run(None, fetches, feed_dict, options_ptr,
--> 895 run_metadata_ptr)
896 if run_metadata:
897 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1122 if final_fetches or final_targets or (handle and feed_dict_tensor):
1123 results = self._do_run(handle, final_targets, final_fetches,
-> 1124 feed_dict_tensor, options, run_metadata)
1125 else:
1126 results = []

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1319 if handle is None:
1320 return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321 options, run_metadata)
1322 else:
1323 return self._do_call(_prun_fn, self._session, handle, feeds, fetches)

~/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
1338 except KeyError:
1339 pass
-> 1340 raise type(e)(node_def, op, message)
1341
1342 def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value beta1_power_7
[[Node: beta1_power_7/read = IdentityT=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Caused by op 'beta1_power_7/read', defined at:
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel_launcher.py", line 16, in
app.launch_new_instance()
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
app.start()
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 478, in start
self.io_loop.start()
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tornado/ioloop.py", line 888, in start
handler_func(fd_obj, events)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 281, in dispatcher
return self.dispatch_shell(stream, msg)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 232, in dispatch_shell
handler(stream, idents, msg)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 397, in execute_request
user_expressions, allow_stdin)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 208, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2728, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2856, in run_ast_nodes
if self.run_code(code, result):
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 1, in
optimize(500,batch_size = 100,lr = 0.8,reg_lambda = 2,beta = 0.9)
File "", line 8, in optimize
optimizer = tf.train.AdamOptimizer(learning_rate=0.5).minimize(cost)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/training/optimizer.py", line 325, in minimize
name=name)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/training/optimizer.py", line 446, in apply_gradients
self._create_slots([_get_variable_for(v) for v in var_list])
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/training/adam.py", line 126, in _create_slots
trainable=False)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 1679, in variable
caching_device=caching_device, name=name, dtype=dtype)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 199, in init
expected_shape=expected_shape)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 330, in _init_from_args
self._snapshot = array_ops.identity(self._variable, name="read")
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1400, in identity
result = _op_def_lib.apply_op("Identity", input=input, name=name)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
op_def=op_def)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2630, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/home/saquib/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1204, in init
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value beta1_power_7
[[Node: beta1_power_7/read = IdentityT=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/cpu:0"]]

`

Thank You for the Help

@Hvass-Labs
Copy link
Owner

This is not the code from my tutorial. This is your own code - perhaps copy-pasted from my tutorial but modified by yourself. It is a bit much to ask me to help you with this. If you look at the view-count of that video it is approaching 100.000 views. Imagine if everybody asked me a question about THEIR code.

If you read the error message you find this: FailedPreconditionError: Attempting to use uninitialized value beta1_power_7 If you do a google search for this, you will probably find that you have made a new variable in the TensorFlow graph which you forgot to initialize.

@Saqhas
Copy link
Author

Saqhas commented Dec 28, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants