如何使用 tensorflow 的图像分类教程对不在原始训练或验证数据集中的看不见的图像进行分类?

How to use tensorflow's image classification tutorial for classifying unseen images not in the original training or validation dataset?

TensorFlow 有 this tutorial,我可以 运行。

然后我定义这个函数来使用模型:

def predict1(model,img):
    img = img.resize((150,150))  
    im = np.array(img)    
    im = im.reshape(-1,np.shape(im)[0],np.shape(im)[1],3)  # resize for 'batch'
    preds = model.predict(im)   # predict
    return preds

然后实际使用它:

img = Image.open('MYIMAGE.jpg')
predict1(model,img)

输出为:

array([[3415.0505]], dtype=float32)

我观察到,当一个正数(这里是 3415.0505)对应于其中一个类别时,负数对应于另一个类别(我尝试了几次后才意识到这一点)。这很好,我可以编写一个函数,根据返回字符串的符号 returns 我得到一个字符串 'dog''cat'

但是,我想我没抓住重点。实际获得 'dog''cat' 预测的更好方法是什么?

如果有很多类别,我基于符号的方法就会失败。我会用这个分类器来分类很多类别,这就是为什么我需要一个更好的方法。

这是基于您正在尝试做的教程,

我对教程中的代码做了一些修改,因为您要尝试做的是分类分类,而不是二元分类。

为了演示
对于 train_gen:

train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,
                                                           directory=train_dir,
                                                           shuffle=True,
                                                           target_size=(IMG_HEIGHT, IMG_WIDTH),
                                                           class_mode='categorical') // change from binary to categorical

对于validation_gen:

val_data_gen = validation_image_generator.flow_from_directory(batch_size=batch_size,
                                                              directory=validation_dir,
                                                              target_size=(IMG_HEIGHT, IMG_WIDTH),
                                                              class_mode='categorical') // changed from binary to categorical

我还更新了输出层,因为它是分类的

model = Sequential([
    Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH ,3)),
    MaxPooling2D(),
    Conv2D(32, 3, padding='same', activation='relu'),
    MaxPooling2D(),
    Conv2D(64, 3, padding='same', activation='relu'),
    MaxPooling2D(),
    Flatten(),
    Dense(512, activation='relu'),
    Dense(2)  #Changed to 2 since you wanted a multiple output e.g.[ 0.333, -0.1333]
]) 

在预测部分,我使用了tf.math.argmax方法,它returns预测的最高值。

listofLabels = ['dog', 'cat']
x = model.predict(sample_training_images)
labels = tf.math.argmax(x, axis = 1)
print(labels)
for label in labels:
    print(listofLabels[label])