如何使用模型.在CNN模型上使用我自己的图像时进行正确的预测



我正试图在此代码上测试我自己的图像,我可以看到该模型具有很高的验证精度,但我想看看它将如何在其他图像上执行,我已经尝试过模型。预测,但它给出了一个错误,因为输入是不兼容的,整个代码工作得很好,但预测部分(最后4行)是问题发生的地方?这是错误

输入0的图层"conv2d"与层不兼容:期望min_ndim=4,发现ndim=1。完整形状收到:(无,)">

import numpy as np
import os
import PIL
import PIL.Image
import tensorflow as tf
import cv2 as cv
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import matplotlib.pyplot as plt

data_dir = "/Users/anastalib/PycharmProjects/pythonProject1/BananaData"
# test_dir = "/Users/anastalib/PycharmProjects/pythonProject1/test_dataset"
batch_size = 50
img_height = 32
img_width = 32
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
print(train_ds)
test_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
print(test_ds)
class_names = train_ds.class_names
print(class_names)
# plt.figure(figsize=(10, 10))
# for images, labels in train_ds.take(1):
#   for i in range(9):
#     ax = plt.subplot(3, 3, i + 1)
#     plt.imshow(images[i].numpy().astype("uint8"))
#     plt.title(class_names[labels[i]])
#     plt.axis("off")
num_classes = 3
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(num_classes))
model.summary()
model.compile(
optimizer='adam',
loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(
train_ds,
epochs=20
)
# history = model_1.fit(train_ds, epochs=4)
# predictions = model_1.predict(test_ds)
# print(class_names[np.argmax(predictions)])
#
train_loss, train_accuracy = model.evaluate(train_ds, verbose=2)
print('nTrain Accuracy:', train_loss)
print('nTrain Loss:', train_accuracy)
test_loss, test_acc = model.evaluate(test_ds, verbose=2)
print('nTest Accuracy:', test_acc)
print('nTest Loss:', test_loss)
#
# Plot training accuracy vs loss values
plt.plot(history.history['accuracy'])
plt.plot(history.history['loss'])  # this is ripe
plt.title('Train Accuracy vs validation accuracy')
plt.ylabel('Percentage')
plt.xlabel('Epoch')
plt.legend(['Training accuracy', 'Training Loss'], loc='upper left')
plt.show()
image = '/Users/anastalib/PycharmProjects/pythonProject1/green.jpeg'
prediction = model.predict(np.expand_dims(image, axis=0))
# argclass = np.argmax(prediction, axis=1)
print('predictions:', prediction)
print(class_names[np.argmax(prediction)])

必须使用tf.keras.utils.load_img加载图像,然后对其进行预处理以进行预测。请在

下面找到示例代码
img = tf.keras.utils.load_img(
path_to_image, target_size=(img_height, img_width)
)
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array) 

我将Flowers数据集与您提供的模型一起使用。请在这里找到要点。谢谢你!

相关内容

  • 没有找到相关文章

最新更新