简体   繁体   English

Kernel 在运行示例 python 代码时死机

[英]Kernel dies when running sample python code

I was trying to run this code from https://keras.io/examples/cifar10_cnn/ .我试图从https://keras.io/examples/cifar10_cnn/运行这段代码。 Initially, it spat out errors regarding tensorflow and keras and cuda.最初,它吐出有关 tensorflow 和 keras 和 cuda 的错误。 I solved that by updating and all.我通过更新和所有解决了这个问题。 Now when I run this code in Jupyter Notebooks, my kernel dies almost instantly.现在,当我在 Jupyter Notebooks 中运行此代码时,我的 kernel 几乎立即死亡。 Mind you I am not intentionally using cuda, It just gave some error and I was surprised cause I didn't even program it to use that or whatever.请注意,我不是故意使用 cuda,它只是给出了一些错误,我很惊讶,因为我什至没有对其进行编程以使用它或其他任何东西。

from __future__ import print_function
import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
import os

batch_size = 32
num_classes = 10
epochs = 100
data_augmentation = True
num_predictions = 20
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'

# The data, split between train and test sets:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same',
                 input_shape=x_train.shape[1:]))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))

# initiate RMSprop optimizer
opt = keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6)

# Let's train the model using RMSprop
model.compile(loss='categorical_crossentropy',
              optimizer=opt,
              metrics=['accuracy'])

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

if not data_augmentation:
    print('Not using data augmentation.')
    model.fit(x_train, y_train,
              batch_size=batch_size,
              epochs=epochs,
              validation_data=(x_test, y_test),
              shuffle=True)
else:
    print('Using real-time data augmentation.')
    # This will do preprocessing and realtime data augmentation:
    datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        zca_epsilon=1e-06,  # epsilon for ZCA whitening
        rotation_range=0,  # randomly rotate images in the range (degrees, 0 to 180)
        # randomly shift images horizontally (fraction of total width)
        width_shift_range=0.1,
        # randomly shift images vertically (fraction of total height)
        height_shift_range=0.1,
        shear_range=0.,  # set range for random shear
        zoom_range=0.,  # set range for random zoom
        channel_shift_range=0.,  # set range for random channel shifts
        # set mode for filling points outside the input boundaries
        fill_mode='nearest',
        cval=0.,  # value used for fill_mode = "constant"
        horizontal_flip=True,  # randomly flip images
        vertical_flip=False,  # randomly flip images
        # set rescaling factor (applied before any other transformation)
        rescale=None,
        # set function that will be applied on each input
        preprocessing_function=None,
        # image data format, either "channels_first" or "channels_last"
        data_format=None,
        # fraction of images reserved for validation (strictly between 0 and 1)
        validation_split=0.0)

    # Compute quantities required for feature-wise normalization
    # (std, mean, and principal components if ZCA whitening is applied).
    datagen.fit(x_train)

    # Fit the model on the batches generated by datagen.flow().
    model.fit_generator(datagen.flow(x_train, y_train,
                                     batch_size=batch_size),
                        epochs=epochs,
                        validation_data=(x_test, y_test),
                        workers=4)

# Save model and weights
if not os.path.isdir(save_dir):
    os.makedirs(save_dir)
model_path = os.path.join(save_dir, model_name)
model.save(model_path)
print('Saved trained model at %s ' % model_path)

# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])

Error Stack:错误堆栈:

ImportError                               Traceback (most recent call last)
~\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     57 
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59   from tensorflow.python.pywrap_tensorflow_internal import __version__

~\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in <module>
     27             return _mod
---> 28     _pywrap_tensorflow_internal = swig_import_helper()
     29     del swig_import_helper

~\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in swig_import_helper()
     23             try:
---> 24                 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
     25             finally:

~\Anaconda3\envs\cv_course\lib\imp.py in load_module(name, file, filename, details)
    242         else:
--> 243             return load_dynamic(name, filename, file)
    244     elif type_ == PKG_DIRECTORY:

~\Anaconda3\envs\cv_course\lib\imp.py in load_dynamic(name, path, file)
    342             name=name, loader=loader, origin=path)
--> 343         return _load(spec)
    344 

ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-1-429941c8ff8d> in <module>
      1 from __future__ import print_function
----> 2 import keras
      3 from keras.datasets import cifar10
      4 from keras.preprocessing.image import ImageDataGenerator
      5 from keras.models import Sequential

~\Anaconda3\envs\cv_course\lib\site-packages\keras\__init__.py in <module>
      1 from __future__ import absolute_import
      2 
----> 3 from . import utils
      4 from . import activations
      5 from . import applications

~\Anaconda3\envs\cv_course\lib\site-packages\keras\utils\__init__.py in <module>
      4 from . import data_utils
      5 from . import io_utils
----> 6 from . import conv_utils
      7 
      8 # Globally-importable utils.

~\Anaconda3\envs\cv_course\lib\site-packages\keras\utils\conv_utils.py in <module>
      7 from six.moves import range
      8 import numpy as np
----> 9 from .. import backend as K
     10 
     11 

~\Anaconda3\envs\cv_course\lib\site-packages\keras\backend\__init__.py in <module>
     87 elif _BACKEND == 'tensorflow':
     88     sys.stderr.write('Using TensorFlow backend.\n')
---> 89     from .tensorflow_backend import *
     90 else:
     91     # Try and load external backend.

~\Anaconda3\envs\cv_course\lib\site-packages\keras\backend\tensorflow_backend.py in <module>
      3 from __future__ import print_function
      4 
----> 5 import tensorflow as tf
      6 from tensorflow.python.framework import ops as tf_ops
      7 from tensorflow.python.training import moving_averages

~\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\__init__.py in <module>
     32 
     33 # pylint: disable=g-bad-import-order
---> 34 from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
     35 from tensorflow.python.tools import module_util as _module_util
     36 

~\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\__init__.py in <module>
     47 import numpy as np
     48 
---> 49 from tensorflow.python import pywrap_tensorflow
     50 
     51 # Protocol buffers

~\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     72 for some common reasons and solutions.  Include the entire stack trace
     73 above this error message when asking for help.""" % traceback.format_exc()
---> 74   raise ImportError(msg)
     75 
     76 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "C:\Users\Hamza\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\Hamza\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\Hamza\Anaconda3\envs\cv_course\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\Hamza\Anaconda3\envs\cv_course\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\Hamza\Anaconda3\envs\cv_course\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.


Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Even though I have installed all the relevant packages, and they have been working like a clock before.尽管我已经安装了所有相关的软件包,而且它们以前一直像时钟一样工作。

When I ran this on another machine it just simply started downloading Cifar10, but that was at uni.当我在另一台机器上运行它时,它只是开始下载 Cifar10,但那是在 uni。 I need to complete my work on the home pc and wat to know how to fix it.我需要在家用电脑上完成我的工作,并且知道如何修复它。 How can I successfully execute it?我怎样才能成功执行它?

You might be trying to grab the gpu by accident, but it doesn't look like it.您可能试图无意中抓住 gpu,但它看起来不像。 You can try adding:您可以尝试添加:

import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"    

to the very top of the file you are using to force tf to run on your cpu.到您用来强制 tf 在您的 cpu 上运行的文件的最顶部。

You should also check to make sure you only have one version of tf and python etc. installed in your current environment.您还应该检查以确保在当前环境中只安装了一个版本的 tf 和 python 等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM