Keras模型预测在训练数据集上几乎总是不正确的;即使训练到接近100%的准确率

z6psavjg  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(160)

我尝试用keras对视频游戏角色进行多类分类,问题是即使训练准确率和验证准确率分别接近100%和70%;当我在一张我刚刚训练过的图片上运行model.predict()时它的分类完全不正确。我每类大约有300张图片。
我能想到的都试过了我尝试了许多方法来加载数据,改变了模型架构一百万次,并预处理函数来准备运行model. predict的图像。
下面是我的代码:

`class_names = ['ana', 'ashe','baby', 'ball','bap', 'bastion','brig', 'cass','doom', 'dva'
,'echo', 'genji','hanzo', 'hog','jq', 'junkrat','kiriko', 'lucio','mei', 'mercy','moira', 'orisa'
,'pharah', 'ram','reaper', 'rein','sigma', 'sojourn','soldier', 'sombra','sym', 'torb','tracer', 'widow'
,'winston', 'zarya','zen']

class_names_label = {class_name:i for i, class_name in enumerate(class_names)}
nb_classes = len(class_names)
print(class_names_label)
IMAGE_SIZE = (128,128)

def load_data():
    DIRECTORY = r'D:\crop-id\enemy-crop'
    CATEGORY = ['train', 'test']

    output = []

    for category in CATEGORY:
        path = os.path.join(DIRECTORY, category)
        print(path)
        images = []
        labels = []

        print('Loading {}'.format(category))

        for folder in os.listdir(path):
            label = class_names_label[folder]

            #iterate through each img in folder
            for file in os.listdir(os.path.join(path,folder)):

                #get path name of img
                img_path = os.path.join(os.path.join(path, folder), file)

                #open and resize img
                image = cv.imread(img_path)
                image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
                image = cv.resize(image, IMAGE_SIZE)

                #append the image and its corresponding label to output
                images.append(image)
                labels.append(label)

        images = np.array(images, dtype = 'float32')
        labels = np.array(labels, dtype='int32')

        output.append((images, labels))

    return output

(train_images, train_labels), (test_images, test_labels) = load_data()

train_images, train_labels = shuffle(train_images, train_labels, random_state=25)

model = Sequential()
model.add(Conv2D(32, (3,3), activation='relu', input_shape=(128, 128, 3)))
model.add(MaxPooling2D())
model.add(BatchNormalization())

model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D())
model.add(BatchNormalization())

model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D()) 
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(37, activation='softmax'))
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
model.summary()
model.fit(train_images, train_labels, batch_size=32, epochs=10, validation_split=.2)

model.save(os.path.join('models','plzwork14.h5'))

predictions = model.predict(test_images)
pred_labels = np.argmax(predictions, axis = 1)
print(classification_report(test_labels, pred_labels))`

这是针对模型的,这是我为模型对图像运行的预处理。predict():

`def prepare(img):
    img = cv.resize(img, (128,128))
    img = np.reshape(img, (128,128,3))
    img = np.expand_dims(img/255, 0)
    prediction = model.predict(img)
    prediction = prediction[0]
    print(prediction)
    print(class_names[np.argmax(prediction)])

img1 = cv.imread(r'C:\Users\andrew\Desktop\sombra.jpg')

prepare(img1)`

谢谢你的帮忙!

zf2sa74q

zf2sa74q1#

在用于生成训练和测试图像的代码中,您有以下代码

image = cv.cvtColor(image, cv.COLOR_BGR2RGB)

因此,您的训练和测试数据是RGB图像。然而,当您进行预测时,您没有这行代码,因此您尝试预测的图像是BGR图像。因此,只需添加代码,将您想要预测的图像从BGR转换为RGB

相关问题