我试图在此代码上测试我自己的图像,我可以看到模型具有很高的验证准确性,但我想看看它将如何在其他图像上执行,我已经尝试了model.predict,但它给出了一个错误,因为输入是不兼容的,整个代码工作正常,但预测部分(最后4行)是问题发生的地方-这是错误
“层“conv 2d”的输入0与层不兼容:预期的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)])
1条答案
按热度按时间nzk0hqpo1#
您必须使用
tf.keras.utils.load_img
加载图像,然后对其进行预处理以进行预测。我已经使用了Flowers数据集和您提供的模型。请在这里找到要点。谢谢!