Simple Neural Network in Python not displaying lab

2019-07-30 13:26发布

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:

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.

1条回答
你好瞎i
2楼-- · 2019-07-30 14:15

Keras models have a predict method .

predictions = model.predict(images_as_numpy_array)

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)
查看更多
登录 后发表回答