问题
I'm trying to train a model using this code from the tutorial of Adrian Rosebrock using my custom dataset to detect the emotion facial expression.
INIT_LR = 1e-3
EPOCHS = 30
BS = 10
print("[INFO] loading images...")
imagePaths = list(paths.list_images(args["dataset"]))
data = []
labels = []
for imagePath in imagePaths:
# extract the class label from the filename
label = imagePath.split(os.path.sep)[-2]
image = cv2.imread(imagePath)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = cv2.resize(image, (48, 48))
data.append(image)
labels.append(label)
data = np.array(data) / 255.0
labels = np.array(labels)
# perform one-hot encoding on the labels
lb = LabelBinarizer()
labels = lb.fit_transform(labels)
labels = to_categorical(labels)
(trainX, testX, trainY, testY) = train_test_split(data, labels,
test_size=0.20, stratify=labels, random_state=42) # line 80
trainAug = ImageDataGenerator(
rotation_range=15,
fill_mode="nearest")
baseModel = VGG16(weights="imagenet", include_top=False,
input_tensor=Input(shape=(48, 48, 3)))
headModel = baseModel.output
headModel = AveragePooling2D(pool_size=(4, 4))(headModel)
headModel = Flatten(name="flatten")(headModel)
headModel = Dense(64, activation="relu")(headModel)
headModel = Dropout(0.5)(headModel)
headModel = Dense(7, activation="softmax")(headModel)
model = Model(inputs=baseModel.input, outputs=headModel)
for layer in baseModel.layers:
layer.trainable = False
print("[INFO] compiling model...")
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt,
metrics=["accuracy"])
print("[INFO] training head...")
H = model.fit_generator(
trainAug.flow(trainX, trainY, batch_size=BS),
steps_per_epoch=len(trainX) // BS,
validation_data=(testX, testY),
validation_steps=len(testX) // BS,
epochs=EPOCHS) # InvalidArgumentError : Incompatible shapes
This code worked for two classes ( binary classification ). I would like to make this script train a dataset with 7 classes. I made some changes but when I execute this code, I got this error:
[INFO] loading images...
Traceback (most recent call last):
File "train_mask.py", line 80, in
test_size=0.20, stratify=labels, random_state=42), in check_array
% (array.ndim, estimator_name))
ValueError: Found array with dim 3. Estimator expected <= 2.
What should I do to make this code working for Multilabel classification, not a binary classification?
回答1:
Usually stratify parameter takes an array of strata or labels and not one-hot-encoded labels.
If you remove stratify does it run? If so just remove create a variable like hotlabels so you don't overwrite your original labels array.
This does depend on the train_test_split function you are using. If it's scikit it should be an array of labels.
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
来源:https://stackoverflow.com/questions/60921502/valueerror-found-array-with-dim-3-estimator-expected-2-keras-sklearn