【问题标题】:Simple Neural Network in Python not displaying label for the test imagePython中的简单神经网络不显示测试图像的标签
【发布时间】:2018-01-01 07:26:28
【问题描述】:

我按照教程学习了如何使用 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 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))

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

但是,有没有一种方法可以代替这个测试集,我只提供一个图像的路径,它会告诉它是猫还是狗(本教程使用了猫/狗样本,所以只是将其用于现在)。我如何在上面的代码中做到这一点?谢谢。

【问题讨论】:

    标签: python opencv machine-learning neural-network keras


    【解决方案1】:

    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)
    

    【讨论】:

    • 然后像这样将“features”传递给model.predict:model.predict(features)??
    • 但这给了我这个错误:ValueError: Error when checks : expected dense_1_input to have shape (None, 3072) but got array with shape (3072, 1)
    • 我做了:img = cv2.imread(path_to_test_image) features1 = image_to_feature_vector(img) predictions = model.predict(features1) print(predictions)
    • 这样做features = np.expand_dims(features, axis=1)
    • 另外,如果你能告诉我这行:labels = np_utils.to_categorical(labels, 2) 正在做什么,那就太好了!
    猜你喜欢
    • 2016-03-02
    • 2022-01-08
    • 2018-04-10
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 2019-01-23
    • 2017-11-21
    相关资源
    最近更新 更多