python - ValueError:找到暗淡为 3 的数组。预计估计器 <= 2。(Keras,Sklearn)
问题描述
我正在尝试使用 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 个类的数据集。我做了一些更改,但是当我执行此代码时,出现此错误:
[信息] 正在加载图像...
回溯(最近一次通话最后):
文件“train_mask.py”,第 80 行,在
test_size=0.20,stratify=labels,random_state=42),在 check_array
% (array.ndim, estimator_name))
ValueError:找到暗淡为 3 的数组。估计器预期 <= 2。
我应该怎么做才能使此代码适用于多标签分类,而不是二进制分类?
解决方案
通常,分层参数采用一组分层或标签,而不是单热编码标签。
如果您删除分层它会运行吗?如果是这样,只需删除创建一个变量,如 hotlabels,这样您就不会覆盖原始标签数组。
这确实取决于您使用的 train_test_split 函数。如果它是 scikit,它应该是一个标签数组。
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
推荐阅读
- typescript - 打字稿 - 强制集合仅包含 2 种类型
- css - 如何在使用css同时更改颜色的同时将鼠标悬停在文本上?
- reactjs - React carousel:为什么图像进入列表视图而不是进入轮播
- google-cloud-platform - GCE startup script fails to run on Ubuntu 18.04
- javascript - 数组对象中的猫鼬更新项目
- image - 总是收到此错误(需要以下参数:-i/--image)
- c# - 验证无效字符串值 Mysql : '\xD9\xBE\xD8\xA7\xDA\xA9
- android - 当设备处于仅负责模式时,在 android studio 中获取 logcats
- java - 通过传递键列表获取 cloudant (couchDB) 数据库文档
- jenkins - Gradle + Jenkins + Artifactory Pro:发布分期和推广