Keras, memoryerror - data = data.astype ("float") / 255.0. Невозможно выделить 309. МиБ для массива с формой (13165, 32, 32, 3) - PullRequest
0 голосов
/ 05 апреля 2020

В настоящее время я работаю над набором данных Smiles, а затем применяю глубокое обучение, чтобы определить улыбку как позитивную или негативную. Машина, которую я использую, - Raspberry Pi 3, и версия Python для облегчения этой программы - 3,7 (не 2,7)

. В тренировочном наборе у меня всего 13165 изображений. Я хотел бы сохранить его в массиве. Однако я столкнулся с проблемой, которая заключается в выделении массива с формой (13165, 32, 32, 3).

Ниже показан исходный код ( shallownet_smile.py ):

from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from pyimagesearch.preprocessing import ImageToArrayPreprocessor
from pyimagesearch.preprocessing import SimplePreprocessor
from pyimagesearch.datasets import SimpleDatasetLoader
from pyimagesearch.nn.conv.shallownet import ShallowNet
from keras.optimizers import SGD
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse


ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to input dataset")
args = vars(ap.parse_args())

# grab the list of images we'll be describing
print("[INFO] loading images...")

imagePaths = list(paths.list_images(args["dataset"]))

sp = SimplePreprocessor(32, 32)
iap = ImageToArrayPreprocessor()

sdl = SimpleDatasetLoader(preprocessors=[sp, iap])
(data, labels) = sdl.load(imagePaths, verbose=1)
# convert values to between 0-1
data = data.astype("float") / 255.0

# partition our data into training and test sets
(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.25,
    random_state=42)

# convert the labels from integers to vectors
trainY = LabelBinarizer().fit_transform(trainY)
testY = LabelBinarizer().fit_transform(testY)

# initialize the optimizer and model
print("[INFO] compiling model...")

# initialize stochastic gradient descent with learning rate of 0.005
opt = SGD(lr=0.005)

model = ShallowNet.build(width=32, height=32, depth=3, classes=2)
model.compile(loss="categorical_crossentropy", optimizer=opt,
    metrics=["accuracy"])

# train the network
print("[INFO] training network...")

H = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=32,
    epochs=100, verbose=1)

print("[INFO] evaluating network...")

predictions = model.predict(testX, batch_size=32)

print(classification_report(
    testY.argmax(axis=1),
    predictions.argmax(axis=1),
    target_names=["positive", "negative"]
))

plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 100), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 100), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 100), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, 100), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.show()

Предположим, что набор данных находится в моем текущем каталоге. Вот ошибка, которую я получил:

python3 shallownet_smile.py -d = наборы данных / Smiles

сообщение об ошибке

Я все еще смущен тем, что не так. Я был бы очень признателен любому специалисту или тем, кто имел опыт глубокого обучения / машинного обучения, чтобы объяснить и объяснить мне, что я делаю неправильно.

Спасибо за вашу помощь и внимание.

1 Ответ

0 голосов
/ 06 апреля 2020

Прежде всего, у вас есть система с очень низким объемом памяти, поэтому попробуйте с меньшими изображениями.

Ошибка возникает в основном в этой строке data = data.astype("float") / 255.0

Причина в том, что данные уже Массив uint8 numpy, и, кроме того, вы создаете массив float32 numpy, который будет занимать дополнительную память.

Я изменяю некоторые части SimpleLataloader, чтобы вы могли тренироваться.

Go до from pyimagesearch.datasets import SimpleDatasetLoader. Он должен быть внутри папки pyimagesearch / datasets / simpledatasetloader.py (пример кода: https://github.com/whydna/Deep-Learning-For-Computer-Vision/blob/master/pyimagesearch/datasets/simpledatasetloader.py)

Измените этот файл .py с моим кодом и измените значение max_image (повторите его, если только вы можете работать с имеющейся у вас памятью), также удалите строку data = data.astype("float") / 255.0, так как я отправляю предварительно обработанный массив из функции.

# import the necessary packages
import numpy as np
import cv2
import os

max_image = 1000

class SimpleDatasetLoader:
    def __init__(self, preprocessors=None):
        # store the image preprocessor
        self.preprocessors = preprocessors

        # if the preprocessors are None, initialize them as an
        # empty list
        if self.preprocessors is None:
            self.preprocessors = []

    def load(self, imagePaths, verbose=-1):
        # initialize the list of features and labels
        data = []
        labels = []
        cnt = 0

        # loop over the input images
        for (i, imagePath) in enumerate(imagePaths):
            if cnt >= max_image:
                break
            # load the image and extract the class label assuming
            # that our path has the following format:
            # /path/to/dataset/{class}/{image}.jpg
            image = cv2.imread(imagePath)
            label = imagePath.split(os.path.sep)[-2]

            # check to see if our preprocessors are not None
            if self.preprocessors is not None:
                # loop over the preprocessors and apply each to
                # the image
                for p in self.preprocessors:
                    image = p.preprocess(image)

            # treat our processed image as a "feature vector"
            # by updating the data list followed by the labels
            data.append(image)
            labels.append(label)

            # show an update every `verbose` images
            cnt += 1
            if verbose > 0 and i > 0 and (i + 1) % verbose == 0:
                print("[INFO] processed {}/{}".format(i + 1,
                    len(imagePaths)))

        # return a tuple of the data and labels
        return (np.array(data, dtype='float32')/255., np.array(labels))

Если вы по-прежнему есть проблемы с памятью, уменьшите batch_size здесь

H = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=4,
    epochs=100, verbose=1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...