使用Python创建简单神经网络时测试图像标签未显示

我按照一个教程学习如何使用Python创建一个简单的神经网络。以下是代码:

def image_to_feature_vector(image, size=(32,32)):    return cv2.resize(image, size).flatten()ap = argparse.ArgumentParser()ap.add_argument("-d", "--dataset", required=True,    help="path to input dataset")args = vars(ap.parse_args())print("[INFO] describing images...")imagePaths = list(paths.list_images(args["dataset"]))print(imagePaths) #this is list of all image paths# initialize the data matrix and labels listdata = []labels = []for (i, imagePath) in enumerate(imagePaths):    image = cv2.imread(imagePath)    label = imagePath.split(os.path.sep)[-1].split(".")[0]    features = image_to_feature_vector(image)    data.append(features)    labels.append(label)    # show an update every 1,000 images    if i > 0 and i % 1000 == 0:        print("[INFO] processed {}/{}".format(i, len(imagePaths)))# encode the labels, converting them from strings to integersle = LabelEncoder()labels = le.fit_transform(labels)data = np.array(data) / 255.0labels = np_utils.to_categorical(labels, 2)print("[INFO] constructing training/testing split...")(trainData, testData, trainLabels, testLabels) = train_test_split(    data, labels, test_size=0.25, random_state=42)#constructing the neural networkmodel = Sequential()model.add(Dense(768, input_dim=3072, init="uniform",    activation="relu"))model.add(Dense(384, init="uniform", activation="relu"))model.add(Dense(2))model.add(Activation("softmax"))# train the model using SGDprint("[INFO] compiling model...")sgd = SGD(lr=0.01)model.compile(loss="binary_crossentropy", optimizer=sgd,    metrics=["accuracy"])model.fit(trainData, trainLabels, nb_epoch=50, batch_size=128)#Test the model# show the accuracy on the testing setprint("[INFO] evaluating on testing set...")(loss, accuracy) = model.evaluate(testData, testLabels,    batch_size=128, verbose=1)print("[INFO] loss={:.4f}, accuracy: {:.4f}%".format(loss,    accuracy * 100))

最后几行代码运行训练好的神经网络对测试集进行测试,并显示如下准确率:

但是,有没有一种方法可以不是使用这个测试集,而是直接提供一张图像的路径,然后它告诉我这是一只猫还是一只狗(这个教程使用了猫/狗样本,所以现在就用这个)。我该如何在上面的代码中实现这个功能?谢谢。


回答:

Keras模型有一个predict方法。

predictions = model.predict(images_as_numpy_array)

这将为您提供对任何选定数据的预测。您需要事先将图像打开并转换为numpy数组。就像您对训练集和测试集所做的那样,使用以下几行代码:

image = cv2.imread(imagePath)label = imagePath.split(os.path.sep)[-1].split(".")[0]features = image_to_feature_vector(image)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注