【发布时间】:2020-07-10 06:54:28
【问题描述】:
我正在尝试使用 Adrian Rosebrock 教程中的这段代码训练模型,使用我的自定义数据集来检测面部表情。
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
此代码适用于两个类(二进制分类)。 我想让这个脚本训练一个包含 7 个类的数据集。 我做了一些更改,但是当我执行这段代码时,我得到了这个错误:
[INFO] 正在加载图片...
Traceback(最近一次调用最后一次):
文件“train_mask.py”,第 80 行,在
test_size=0.20,stratify=labels,random_state=42),在 check_array 中
% (array.ndim, estimator_name))
ValueError: 找到暗淡为 3 的数组。预计估计器
我应该怎么做才能使这段代码适用于多标签分类,而不是二元分类?
【问题讨论】:
-
data的形状是什么? -
维度为(48,48)
-
不是维度,
image.shape,我猜是(48, 48, 3),因为它是RGB图像,对吧? -
是的,是吗,我的意思是
(48, 48, 3) -
执行
to_categorical(labels)后labels的形状是什么?另外,请修复图像路径循环上的缩进
标签: python tensorflow keras scikit-learn deep-learning