我正在尝试构建一个模型并对其进行训练和预测,然后查看其准确性并生成一个分类报告。我不明白为什么我的“无事故”精确度为零。尽管我提供了286张事故图片和3249张无事故图片。我原本希望模型对无事故的精确度会很高,但结果恰恰相反,有人能告诉我可能的原因吗?
这是因为数据集非常不平衡造成的吗?还是我使用的模型不好?请有人能发表一下您的看法吗?
代码
X = np.array(X)y = np.array(y)X.shape (3535, 224, 224, 3)y.shape (3535,)np.unique(y)array(['accident', 'noaccident'], dtype=object)Frequency of unique values of the said array:[['accident' 'noaccident'][286 3249]]lb = LabelBinarizer()labels = lb.fit_transform(y)np.unique(labels)array([0, 1]) ---> two classes are there(trainX, testX, trainY, testY) = train_test_split(X, labels, test_size=0.20, stratify=labels, random_state=42)trainAug = ImageDataGenerator( rotation_range=30, zoom_range=0.15, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15, horizontal_flip=True, fill_mode="nearest")valAug = ImageDataGenerator()mean = np.array([123.68, 116.779, 103.939], dtype="float32")trainAug.mean = meanvalAug.mean = meanbaseModel = ResNet50(weights="imagenet", include_top=False, input_tensor=Input(shape=(224, 224, 3)))headModel = baseModel.outputheadModel = AveragePooling2D(pool_size=(7, 7))(headModel)headModel = Flatten(name="flatten")(headModel)headModel = Dense(512, activation="relu")(headModel)headModel = Dropout(0.5)(headModel)headModel = Dense(len(lb.classes_), activation="softmax")(headModel)model = Model(inputs=baseModel.input, outputs=headModel)for layer in baseModel.layers: layer.trainable = Falseprint("[INFO] compiling model...")opt = SGD(lr=1e-4, momentum=0.9, decay=1e-4 / 50)model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"])print("[INFO] training head...")H = model.fit( x=trainAug.flow(trainX, trainY, batch_size=32), steps_per_epoch=len(trainX) // 32, validation_data=valAug.flow(testX, testY), validation_steps=len(testX) // 32, epochs= 50)print("[INFO] evaluating network...")predictions = model.predict(x=testX.astype("float32"), batch_size=32)print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=lb.classes_))Output: precision recall f1-score support accident 1.00 0.57 0.72 707 noaccident 0.00 0.00 0.00 0 accuracy 0.57 707 macro avg 0.50 0.28 0.36 707weighted avg 1.00 0.57 0.72 707
回答:
尝试使用 –
print(classification_report(testY, predictions.argmax(axis=1), target_names=lb.classes_))
textY
已经是一个形状为 (n,1) 的向量,包含 0,1 类别,并且 testY.argmax(axis=1)
总是返回相同的值,即 0
。这就是为什么您的第一个类别的精确度为 1,而第二个类别的精确度为 0。因为您正确预测了所有的 0。
predictions.argmax(axis=1)
是一个形状为 (n,2) 的向量,包含类别 0 和类别 1 的概率值。您需要通过取 argmax 将其转换为类别,所以不要更改这一部分。