TensorFlow尝试使用tensorFlow代码运行两个Jupyter笔记本时出错

时间:2017-04-26 10:31:44

标签: python tensorflow jupyter-notebook jupyter conda

我试图在Windows上使用TensorFlow代码运行两个Jupyter笔记本。当我运行第一台笔记本电脑时,它运行成功,但是当我尝试运行第二台笔记本电脑而没有关闭第一台笔记本电脑时,它会抛出错误。尝试运行第二台笔记本时,第一台笔记本中没有运行代码。

我通过激活Conda中的Tensorflow环境打开Jupyter笔记本,然后调用jupyter笔记本。

运行#Cell 4#代码时出错,如果第一台笔记本电脑关闭 然后第二个笔记本运行没有任何错误,但#Cell 3#需要再次运行才能执行出现错误的单元格(单元格4)

            WARNING:tensorflow:From <ipython-input-6-0702350d4d1b>:4: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
            Instructions for updating:
            Use `tf.global_variables_initializer` instead.
            Initialized
            ---------------------------------------------------------------------------
            InternalError                             Traceback (most recent call last)
            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
               1021     try:
            -> 1022       return fn(*args)
               1023     except errors.OpError as e:

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
               1003                                  feed_dict, fetch_list, target_list,
            -> 1004                                  status, run_metadata)
               1005 

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\contextlib.py in __exit__(self, type, value, traceback)
                 65             try:
            ---> 66                 next(self.gen)
                 67             except StopIteration:

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\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:

            InternalError: Blas SGEMM launch failed : a.shape=(128, 784), b.shape=(784, 1024), m=128, n=1024, k=784
                 [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_13, Variable/read)]]
                 [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_55_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

            During handling of the above exception, another exception occurred:

            InternalError                             Traceback (most recent call last)
            <ipython-input-6-0702350d4d1b> in <module>()
                 15         # and the value is the numpy array to feed to it.
                 16         feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
            ---> 17         _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)
                 18         if (step % 500 == 0):
                 19             print("Minibatch loss at step {}: {}".format(step, l))

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
                765     try:
                766       result = self._run(None, fetches, feed_dict, options_ptr,
            --> 767                          run_metadata_ptr)
                768       if run_metadata:
                769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
                963     if final_fetches or final_targets:
                964       results = self._do_run(handle, final_targets, final_fetches,
            --> 965                              feed_dict_string, options, run_metadata)
                966     else:
                967       results = []

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
               1013     if handle is None:
               1014       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
            -> 1015                            target_list, options, run_metadata)
               1016     else:
               1017       return self._do_call(_prun_fn, self._session, handle, feed_dict,

            C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
               1033         except KeyError:
               1034           pass
            -> 1035       raise type(e)(node_def, op, message)
               1036 
               1037   def _extend_graph(self):

            InternalError: Blas SGEMM launch failed : a.shape=(128, 784), b.shape=(784, 1024), m=128, n=1024, k=784
                 [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_13, Variable/read)]]
                 [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_55_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

            Caused by op 'MatMul', defined at:
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\runpy.py", line 184, in _run_module_as_main
                "__main__", mod_spec)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\runpy.py", line 85, in _run_code
                exec(code, run_globals)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
                app.launch_new_instance()
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
                app.start()
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
                ioloop.IOLoop.instance().start()
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
                super(ZMQIOLoop, self).start()
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tornado\ioloop.py", line 888, in start
                handler_func(fd_obj, events)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
                return fn(*args, **kwargs)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
                self._handle_recv()
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
                self._run_callback(callback, msg)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
                callback(*args, **kwargs)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
                return fn(*args, **kwargs)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
                return self.dispatch_shell(stream, msg)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell
                handler(stream, idents, msg)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
                user_expressions, allow_stdin)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
                res = shell.run_cell(code, store_history=store_history, silent=silent)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
                return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2683, in run_cell
                interactivity=interactivity, compiler=compiler, result=result)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2787, in run_ast_nodes
                if self.run_code(code, result):
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2847, in run_code
                exec(code_obj, self.user_global_ns, self.user_ns)
              File "<ipython-input-5-356ef7c4c4f2>", line 21, in <module>
                logits_1 = tf.matmul(tf_train_dataset, weights_1) + biases_1
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\ops\math_ops.py", line 1765, in matmul
                a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 1454, in _mat_mul
                transpose_b=transpose_b, name=name)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 763, in apply_op
                op_def=op_def)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2327, in create_op
                original_op=self._default_original_op, op_def=op_def)
              File "C:\Users\Auro\AppData\Local\Continuum\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 1226, in __init__
                self._traceback = _extract_stack()

            InternalError (see above for traceback): Blas SGEMM launch failed : a.shape=(128, 784), b.shape=(784, 1024), m=128, n=1024, k=784
                 [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_13, Variable/read)]]
                 [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_55_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

以下是代码:

            # These are all the modules we'll be using later. Make sure you can import them
            # before proceeding further.

            #CELL 1#
            from __future__ import print_function
            import numpy as np
            import tensorflow as tf
            from six.moves import cPickle as pickle
            from six.moves import range

            pickle_file = 'notMNIST.pickle'

            with open(pickle_file, 'rb') as f:
              save = pickle.load(f)
              train_dataset = save['train_dataset']
              train_labels = save['train_labels']
              valid_dataset = save['valid_dataset']
              valid_labels = save['valid_labels']
              test_dataset = save['test_dataset']
              test_labels = save['test_labels']
              del save  # hint to help gc free up memory
              print('Training set', train_dataset.shape, train_labels.shape)
              print('Validation set', valid_dataset.shape, valid_labels.shape)
              print('Test set', test_dataset.shape, test_labels.shape)

            image_size = 28
            num_labels = 10

            #CELL 2#

            def reformat(dataset, labels):
              dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
              # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
              labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
              return dataset, labels
            train_dataset, train_labels = reformat(train_dataset, train_labels)
            valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
            test_dataset, test_labels = reformat(test_dataset, test_labels)
            print('Training set', train_dataset.shape, train_labels.shape)
            print('Validation set', valid_dataset.shape, valid_labels.shape)
            print('Test set', test_dataset.shape, test_labels.shape)

            def accuracy(predictions, labels):
                return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
                        / predictions.shape[0])





            #CELL 3#

            num_nodes= 1024
            batch_size = 128


            graph = tf.Graph()
            with graph.as_default():

                # Input data. For the training data, we use a placeholder that will be fed
                # at run time with a training minibatch.
                tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size))
                tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
                tf_valid_dataset = tf.constant(valid_dataset)
                tf_test_dataset = tf.constant(test_dataset)

                # Variables.
                weights_1 = tf.Variable(tf.truncated_normal([image_size * image_size, num_nodes]))
                biases_1 = tf.Variable(tf.zeros([num_nodes]))
                weights_2 = tf.Variable(tf.truncated_normal([num_nodes, num_labels]))
                biases_2 = tf.Variable(tf.zeros([num_labels]))

                # Training computation.
                logits_1 = tf.matmul(tf_train_dataset, weights_1) + biases_1
                relu_layer= tf.nn.relu(logits_1)
                logits_2 = tf.matmul(relu_layer, weights_2) + biases_2
                loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits_2, labels=tf_train_labels))

                # Optimizer.
                optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

                # Predictions for the training
                train_prediction = tf.nn.softmax(logits_2)

                # Predictions for validation 
                logits_1 = tf.matmul(tf_valid_dataset, weights_1) + biases_1
                relu_layer= tf.nn.relu(logits_1)
                logits_2 = tf.matmul(relu_layer, weights_2) + biases_2

                valid_prediction = tf.nn.softmax(logits_2)

                # Predictions for test
                logits_1 = tf.matmul(tf_test_dataset, weights_1) + biases_1
                relu_layer= tf.nn.relu(logits_1)
                logits_2 = tf.matmul(relu_layer, weights_2) + biases_2

                test_prediction =  tf.nn.softmax(logits_2)



            #CELL 4#

            num_steps = 3001

            with tf.Session(graph=graph) as session:
                tf.initialize_all_variables().run()
                print("Initialized")
                for step in range(num_steps):
                    # Pick an offset within the training data, which has been randomized.
                    # Note: we could use better randomization across epochs.
                    offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
                    # Generate a minibatch.
                    batch_data = train_dataset[offset:(offset + batch_size), :]
                    batch_labels = train_labels[offset:(offset + batch_size), :]
                    # Prepare a dictionary telling the session where to feed the minibatch.
                    # The key of the dictionary is the placeholder node of the graph to be fed,
                    # and the value is the numpy array to feed to it.
                    feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
                    _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)
                    if (step % 500 == 0):
                        print("Minibatch loss at step {}: {}".format(step, l))
                        print("Minibatch accuracy: {:.1f}".format(accuracy(predictions, batch_labels)))
                        print("Validation accuracy: {:.1f}".format(accuracy(valid_prediction.eval(), valid_labels)))
                print("Test accuracy: {:.1f}".format(accuracy(test_prediction.eval(), test_labels)))

0 个答案:

没有答案