Ядро умирает при запуске примера кода Python - PullRequest
0 голосов
/ 23 октября 2019

Я пытался запустить этот код с https://keras.io/examples/cifar10_cnn/. Изначально он выдавал ошибки, связанные с тензорным потоком, керасами и cuda. Я решил это обновлением и все. Теперь, когда я запускаю этот код в Jupyter Notebooks, мое ядро ​​почти мгновенно умирает. Имейте в виду, я не намеренно использую 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])

Стек ошибок:

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.

Несмотря на то, что я установил все соответствующие пакеты, и они работали как часы раньше.

Когда я запустилэто на другой машине он просто начал скачивать Cifar10, но это было в универе. Мне нужно закончить работу на домашнем компьютере и посмотреть, как это исправить. Как я могу успешно выполнить это?

1 Ответ

0 голосов
/ 23 октября 2019

Возможно, вы пытаетесь захватить графический процессор случайно, но это не похоже на это. Вы можете попробовать добавить:

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

в самый верх файла, который вы используете, чтобы заставить tf работать на вашем процессоре.

Вам также следует убедиться, что в вашей текущей среде установлена ​​только одна версия tf, python и т. Д.

...