首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Keras : KeyError:'acc‘,打印期间

Keras : KeyError:'acc‘,打印期间
EN

Stack Overflow用户
提问于 2019-09-19 21:49:47
回答 1查看 8.6K关注 0票数 1

我正在尝试可视化我的模型的训练图,我得到了这个错误:

代码语言:javascript
复制
    Traceback (most recent call last):
    File "train.py", line 120, in <module>
    plt.plot(H.history['acc'])
    KeyError: 'acc'

这是完整的代码:

代码语言:javascript
复制
     # set the matplotlib backend so figures can be saved in the background
     import matplotlib
     matplotlib.use("Agg")

     # import the necessary packages
     from pyimagesearch.resnet import ResNet
     from sklearn.preprocessing import LabelEncoder
     from sklearn.model_selection import train_test_split
     from sklearn.metrics import classification_report
     from keras.preprocessing.image import ImageDataGenerator
     from keras.optimizers import SGD
     from keras.utils import np_utils
     from imutils import paths
     import matplotlib.pyplot as plt
     import numpy as np
     import argparse
     import cv2
     import os

     # construct the argument parser and parse the arguments
     ap = argparse.ArgumentParser()
     ap.add_argument("-d", "--dataset", required=True,
         help="path to input dataset")
     ap.add_argument("-a", "--augment", type=int, default=-1,
         help="whether or not 'on the fly' data augmentation should be used")
     ap.add_argument("-p", "--plot", type=str, default="plot.png",
         help="path to output loss/accuracy plot")
     args = vars(ap.parse_args())

     # initialize the initial learning rate, batch size, and number of
     # epochs to train for
     INIT_LR = 1e-1
     BS = 8
     EPOCHS = 50

     # grab the list of images in our dataset directory, then initialize
     # the list of data (i.e., images) and class images
     print("[INFO] loading images...")
     imagePaths = list(paths.list_images(args["dataset"]))
     data = []
     labels = []

     # loop over the image paths
     for imagePath in imagePaths:
             # extract the class label from the filename, load the image, and
             # resize it to be a fixed 64x64 pixels, ignoring aspect ratio
             label = imagePath.split(os.path.sep)[-2]
             image = cv2.imread(imagePath)
             image = cv2.resize(image, (64, 64))

             # update the data and labels lists, respectively
             data.append(image)
             labels.append(label)

     # convert the data into a NumPy array, then preprocess it by scaling
     # all pixel intensities to the range [0, 1]
     data = np.array(data, dtype="float") / 255.0

     # encode the labels (which are currently strings) as integers and then
     # one-hot encode them
     le = LabelEncoder()
     labels = le.fit_transform(labels)
     labels = np_utils.to_categorical(labels, 3)

     # partition the data into training and testing splits using 75% of
     # the data for training and the remaining 25% for testing
     (trainX, testX, trainY, testY) = train_test_split(data, labels,
             test_size=0.25, random_state=42)

     # initialize an our data augmenter as an "empty" image data generator
     aug = ImageDataGenerator()

     # check to see if we are applying "on the fly" data augmentation, and
     # if so, re-instantiate the object
     if args["augment"] > 0:
            print("[INFO] performing 'on the fly' data augmentation")
            aug = ImageDataGenerator(
                    rotation_range=20,
                    zoom_range=0.15,
                    width_shift_range=0.2,
                    height_shift_range=0.2,
                    shear_range=0.15,
                    horizontal_flip=True,
                    fill_mode="nearest")

    # initialize the optimizer and model
    print("[INFO] compiling model...")
    opt = SGD(lr=INIT_LR, momentum=0.9, decay=INIT_LR / EPOCHS)
    model = ResNet.build(64, 64, 3, 2, (2, 3, 4),
            (32, 64, 128, 256), reg=0.0001)
    model.compile(loss="categorical_crossentropy", optimizer=opt,
            metrics=["accuracy"])

    # train the network
    print("[INFO] training network for {} epochs...".format(EPOCHS))
    H = model.fit_generator(
            aug.flow(trainX, trainY, batch_size=BS),
            validation_data=(testX, testY),
            steps_per_epoch=len(trainX) // BS,
            epochs=EPOCHS)

    # evaluate the network
    print("[INFO] evaluating network...")
    predictions = model.predict(testX, batch_size=BS)
    print(classification_report(testY.argmax(axis=1),
            predictions.argmax(axis=1), target_names=le.classes_))

    # plot the training loss and accuracy
    N = np.arange(0, EPOCHS)
    plt.style.use("ggplot")
    plt.figure()
    plt.plot(N, H.history["loss"], label="train_loss")
    plt.plot(N, H.history['val_loss'], label="val_loss")
    plt.plot(N, H.history['acc'], label="accuracy")
    plt.plot(N, H.history['val_acc'], label="val_acc")
    plt.title("Training Loss and Accuracy on Dataset")
    plt.xlabel("Epoch #")
    plt.ylabel("Loss/Accuracy")
    plt.legend(loc="lower left")
    plt.savefig(args["plot"])

所以,这段代码,最初来自博客Pyimagesearch,关于数据增强,所以,我决定试一试,原来的“流水线”是用于二进制分类的,所以,因为我对多类“任务”感兴趣,所以我带来了一些变化。

但是代码的绘图部分,对我来说似乎是正确的,我在Stack上检查了多个帖子,检查了keras文档,没有任何东西,我不明白,为什么它不工作!任何建议都将不胜感激。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-19 21:55:52

你试过H.history['accuracy']吗?由于您使用'accuracy'进行编译,因此它可能具有相同的字符串。

现在,您可以随时查看您所拥有的内容:

代码语言:javascript
复制
for key in H.history.keys():
    print(key)

您将看到在那里记录了什么

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58012584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档