用 CNN 预测图像的 class

Predicting the class of image with CNN

我试图在训练模型上预测单个图像的 class,但我得到了一个奇怪的输出,所以这是我的代码:

from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os


def load_image(img_path, show=False):
  img = image.load_img(img_path, target_size=(300, 300))
  img_tensor = image.img_to_array(img)                    
  img_tensor = np.expand_dims(img_tensor, axis=0)         
  img_tensor /= 255.                                      

  if show:
    plt.imshow(img_tensor[0])
    plt.axis('off')
    plt.show()

  return img_tensor


if __name__ == "__main__":
  # load model
  model = load_model("model1.h5")

  # image path
  img_path = 'dog.jpg' # dog

  # load a single image
  new_image = load_image(img_path, True)

  # check prediction
  pred = model.predict(new_image)
  print(pred)

但我得到 [[0.8189566 0.18104333]] 作为输出。但是我有 classes 0 和 1。 这可能是因为没有在任何地方指定批量大小吗?

model.predict(new_image) 你获得每个测试图像属于特定 class

的概率

要获得输出 class,您需要 select 具有最大预测概率的 class:

np.argmax(pred, axis=1)