【问题标题】:Classify multiple images in one go with InceptionV3使用 InceptionV3 一次性对多张图像进行分类
【发布时间】:2020-03-01 14:45:23
【问题描述】:

我正在尝试使用 InceptionV3 一次在一个目录中对多个图像进行分类。
我能够使用目录流方法提取瓶颈特征,并将预测结果作为数组获取。

我的问题是我如何知道每个预测指的是哪个图像,因为它们在数组中是乱序的。
我尝试使用 generator_top.classes 提取类,但它从图像所在目录的名称中获取它们。
我看到预测都是正确的(图像上的那些对象,那些是在原始数组中获得的)。
我只会明白如何比较它们。

此外,我在大型测试样本上测试图像时使用了这种方法(每个类和图像都有文件夹),并且数组中的所有预测都按测试目录中的文件夹顺序显示 但是当我尝试从具有不同类的同一目录中执行此操作时,我无法将预测与图像进行比较。

from keras import applications

base_model = applications.InceptionV3(include_top=False, weights='imagenet')

res_model = Sequential()
res_model.add(GlobalAveragePooling2D(input_shape=train_data.shape[1:]))
res_model.add(Dense(17, activation='softmax'))
datagen=ImageDataGenerator(rescale=1./255)


generator = datagen.flow_from_directory(  
    test_path,  
    target_size=(img_width, img_height),  
    batch_size=batch_size,  
    class_mode=None,  
    shuffle=False)

nb_test_samples = len(generator.filenames)  #17
predict_size_test = int(math.ceil(nb_test_samples/batch_size))   #2  
bottleneck_features_test = base_model.predict_generator( generator, 
    predict_size_test, verbose=1) 

np.save('bottleneck_features_test_10000inc.npy', bottleneck_features_test)

generator = datagen.flow_from_directory(  
    test_path,  
    target_size=(img_width, img_height),  
    batch_size=batch_size,  
    class_mode=None,  
    shuffle=False)  

nb_test_samples = len(generator_top.filenames)  

test_data = np.load('bottleneck_features_test_10000inc.npy')  

test_labels = generator_top.classes
test_labels = to_categorical(test_labels, num_classes=17) 

tr_predictions=[np.argmax(res_model.predict(np.expand_dims(feature,axis=0)))for feature in test_data]

【问题讨论】:

    标签: python image-processing deep-learning classification


    【解决方案1】:

    您可以获取生成的文件的文件名,并将其与预测结果映射。

    datagen = ImageDataGenerator()
    gen = datagen.flow_from_directory(...)
    for i in gen:
    idx = (gen.batch_index - 1) * gen.batch_size
    filenames = gen.filenames[idx : idx + gen.batch_size]
    

    filenames 数组将包含文件名,使用 python 中的 zip 等函数来映射文件名和预测结果。

    注意 1 - 这将在

    时起作用
    shuffle=False
    

    在生成器中,因为数据在读取后可能会被打乱,您将无法跟踪打乱。

    注 2 - 这个答案的灵感来自 Keras flowFromDirectory get file names as they are being generated

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 2016-10-16
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2020-12-08
      • 2019-08-08
      相关资源
      最近更新 更多