Python中的简单神经网络未显示测试图像的标签 [英] Simple Neural Network in Python not displaying label for the test image
问题描述
我遵循了一个教程,以学习如何使用python创建简单的神经网络.下面是代码:
I followed a tutorial to learn how to create a simple neural network using python. Below is the code:
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 list
data = []
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 integers
le = LabelEncoder()
labels = le.fit_transform(labels)
data = np.array(data) / 255.0
labels = 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 network
model = 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 SGD
print("[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 set
print("[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))
最后几行针对测试集运行经过训练的神经网络,并显示出以下准确性:
The last few lines run the trained neural network against the testing set and displays the accuracy as follows:
但是,有一种方法可以代替此测试集,而是提供图像的路径,并告诉它是猫还是狗(本教程使用了cat/dog样本,因此仅将其用于现在).如何在上面的代码中执行此操作?谢谢.
But, is there a way that instead of this testing set, I just supply a path of an image and it tells whether it is a cat or a dog (this tutorial used the cat/dog sample, so just using that for now). How do I do this in the above code? Thanks.
推荐答案
Keras模型具有预测方法.
Keras models have a predict method .
predictions = model.predict(images_as_numpy_array)
将为您提供任何选定数据的预测.您将先前已打开图像并将其转换为numpy数组.就像您为培训和测试集所做的那样,使用以下几行代码:
will give you predictions on any chosen data. You will to have previously opened and transformed your image as a numpy array. Just like you did for your training and testing set with the following lines:
image = cv2.imread(imagePath)
label = imagePath.split(os.path.sep)[-1].split(".")[0]
features = image_to_feature_vector(image)
这篇关于Python中的简单神经网络未显示测试图像的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!