使用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

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

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