训练模型,但在命令行上val_loss为0.0000e + 00,精度为1.0000

时间:2020-05-19 10:06:11

标签: python tensorflow keras

我知道这些数字不应该是这样吗?我认为我没有正确解析我的数据集,但是我不知道这是否是它的原因。

当我尝试使用此模型进行测试时,使用错误的标签可以得到100%的准确输出结果,而每个其他标签都可以得到0%的准确率(有四个可能的标签)。有人可以帮我这个忙,我真的不知道该怎么办?谢谢。

我已经包含了培训和测试代码的完整代码。我还包括了我用来训练的确切命令。

培训代码

import matplotlib
matplotlib.use("Agg")

from keras.preprocessing.image import ImageDataGenerator
from keras.opti
mizers import Adam
from sklearn.model_selection import train_test_split
from keras.preprocessing.image import img_to_array
from keras.utils import to_categorical
from pyimagesearch.lenet import LeNet
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
import random
import cv2
import os

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
    help="path to input dataset")
ap.add_argument("-m", "--model", required=True,
    help="path to output model")
ap.add_argument("-p", "--plot", type=str, default="plot.png",
    help="path to output loss/accuracy plot")
args = vars(ap.parse_args())

EPOCHS = 250
#EPOCHS = 5
INIT_LR = 1e-3
BS = 32

print("[INFO] loading images...")
data = []
labels = []

imagePaths = sorted(list(paths.list_images(args["dataset"])))
random.seed(42)
random.shuffle(imagePaths)


for imagePath in imagePaths:

    image = cv2.imread(imagePath)
    image = cv2.resize(image, (28, 28))
    image = img_to_array(image)
    data.append(image)

    label = imagePath.split(os.path.sep)[1]
    if label == "F15":
        label_type = 1
    elif label == "F16":
        label_type = 2
    elif label == "Bird":
        label_type = 3
    else: 
        label_type = 0

    labels.append(label_type)

data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)

(trainX, testX, trainY, testY) = train_test_split(data,
    labels, test_size=0.25, random_state=42)

trainY = to_categorical(trainY, num_classes=4)
testY = to_categorical(testY, num_classes=4)

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")

print("[INFO] compiling model...")
model = LeNet.build(width=28, height=28, depth=3, classes=4)
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(loss="categorical_crossentropy", optimizer=opt,
    metrics=["accuracy"])

print("[INFO] training network...")
H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),
    validation_data=(testX, testY), steps_per_epoch=len(trainX) // BS,
    epochs=EPOCHS, verbose=1)


print("[INFO] serializing network...")
model.save(args["model"])

plt.style.use("ggplot")
plt.figure()
N = EPOCHS
plt.plot(np.arange(0, N), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, N), H.history["accuracy"], label="train_acc")
plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_acc")
plt.title("Training Loss and Accuracy on F15/F16/Bird/Airplane")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="lower left")
plt.savefig(args["plot"])
plt.show()

测试代码

from keras.preprocessing.image import img_to_array
from keras.models import load_model
import numpy as np
import argparse
import imutils
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True,
    help="path to trained model model")
ap.add_argument("-i", "--image", required=True,
    help="path to input image")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
orig = image.copy()

image = cv2.resize(image, (28, 28))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)

print("[INFO] loading network...")
model = load_model(args["model"])

(Airplane, F15,F16, Bird) = model.predict(image)[0] 
print("F15: ", F15)
print("F16: ", F16)
print("Bird: ", Bird)
print("Airplane: ", Airplane)
classes =["F15", "F16", "Bird", "Airplane"]
results = [F15, F16, Bird, Airplane]

i = np.argmax(results)
label = classes[i]
proba = max(results) 

label = "{}: {:.2f}%".format(label, proba * 100)

output = imutils.resize(orig, width=400)
cv2.putText(output,  label, (10, 25),  cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

cv2.imshow("Output", output)
cv2.waitKey(0)

命令行

C:\Users\ggian\Desktop\FYP\image-classification-keras>python train_network.py --dataset image --model trial.model

在数据集“图像”中,它包含另外四个文件夹,每个文件夹包含约400张图像

0 个答案:

没有答案