ожидается, что Activation_8 будет иметь форму (2,), но получил массив с формой (1,) - PullRequest
1 голос
/ 29 января 2020

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

Я работаю над проектом распознавания изображений.

Сначала я импортирую библиотеки:

from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers.core import Activation
from keras.layers.core import Flatten, Dropout
from keras import backend as K
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
import random
import pickle
import cv2
import os

Затем я создаю экземпляр своей модели CNN:

class SmallVGGNet:
    @staticmethod
    def build(width, height, depth, classes):
        model = Sequential()
        inputShape = (height, width, depth)
        chanDim = -1


        if K.image_data_format() == "channels_first":
            inputShape = (depth, height, width)
            chanDim = 1


        # CONV => RELU => POOL layer set
        model.add(Conv2D(32, (3, 3), padding="same",
            input_shape=inputShape))
        model.add(Activation("relu"))
        model.add(BatchNormalization(axis=chanDim))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.25))



        # (CONV => RELU) * 2 => POOL layer set
        model.add(Conv2D(64, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(axis=chanDim))
        model.add(Conv2D(64, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(axis=chanDim))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.25))


        # (CONV => RELU) * 3 => POOL layer set
        model.add(Conv2D(128, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(axis=chanDim))
        model.add(Conv2D(128, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(axis=chanDim))
        model.add(Conv2D(128, (3, 3), padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(axis=chanDim))
        model.add(MaxPooling2D(pool_size=(2, 2)))
        model.add(Dropout(0.25))


        # first (and only) set of FC => RELU layers
        model.add(Flatten())
        model.add(Dense(512))
        model.add(Activation("relu"))
        model.add(BatchNormalization())
        model.add(Dropout(0.5))

        # softmax classifier
        model.add(Dense(classes))
        model.add(Activation("softmax"))

        # return the constructed network architecture
        return model

Собрал и обработал мои изображения:

data = []
labels = []

# grab the image paths and randomly shuffle them
shiba_path = sorted(list(paths.list_images('../downloads/shiba')))
fox_path = sorted(list(paths.list_images('../downloads/fox')))
combine_path = [shiba_path,fox_path]
random.seed(42)

# loop over the input data dictionaries
for path in combine_path:
    path = random.shuffle(path)

# loop over the input images
for imagePaths in combine_path:
    for imagePath in imagePaths:
        try:
            # load the image, resize the image to be 32x32 pixels (ignoring
            # aspect ratio), flatten the image into 32x32x3=3072 pixel image
            # into a list, and store the image in the data list
            image = cv2.imread(imagePath)
            image = cv2.resize(image, (64, 64))
            data.append(image)

            # extract the class label from the image path and update the
            # labels list
            label = imagePath.split(os.path.sep)[-2].split('/')[-1]
            labels.append(label)
        except:
            pass
# scale the raw pixel intensities to the range [0, 1]
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)

Запустите мою модель:

# partition the data into training and testing splits using 75% of
# the data for training and the remaining 25% for testing
(trainX, testX, trainY, testY) = train_test_split(data,
    labels, test_size=0.25, random_state=42)

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

trainY имеет форму (1429,1) и trainX имеет форму (1429, 64, 64, 3)

# construct the image generator for data augmentation
aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,
    height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
    horizontal_flip=True, fill_mode="nearest")

# initialize our VGG-like Convolutional Neural Network
model = SmallVGGNet.build(width=64, height=64, depth=3,
    classes=len(lb.classes_))

Проблема возникает на следующем шаге.

# initialize our initial learning rate, # of epochs to train for,
# and batch size
INIT_LR = 0.01
EPOCHS = 20
BS = 32

# initialize the model and optimizer
print("[INFO] training network...")
opt = SGD(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt,
    metrics=["accuracy"])

# train the network
H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),
    validation_data=(testX, testY), steps_per_epoch=len(trainX) // BS,
    epochs=EPOCHS)

Этот шаг генерирует

Ошибка при проверке цели: ожидается, что Activation_8 будет иметь форму (2,), но получил массив с формой (1,)

Куда я иду не так? Что я делаю, ожидая, что мой Y будет иметь форму 2? Должна ли она иметь форму 1 или 2?

Любая помощь будет принята с благодарностью.

...