在深度学习中,如何让predict_generator进行有序预测?

时间:2018-11-21 21:59:17

标签: python tensorflow machine-learning keras neural-network

我正在设计一个深度学习模型来对图像进行分类,并且正在使用以下代码检查预测性能。它将图像的标签与预测的类别进行比较,然后返回错误预测。

我正在使用顺序模型,并且此代码运行良好。但是,现在它不能正常工作。predict_generator更改图像的顺序。 (predict_classes和validation_generator的顺序不同)

我要按validation_generator中图像的顺序进行预测,您知道我该怎么做吗?

validation_generator = validation_datagen.flow_from_directory(
            validation_dir,
            target_size=(image_size, image_size),
            batch_size=val_batchsize,
            class_mode='categorical',
            shuffle=False)

    # Get the filenames from the generator
    fnames = validation_generator.filenames

    # Get the ground truth from generator
    ground_truth = validation_generator.classes

    # Get the label to class mapping from the generator
    label2index = validation_generator.class_indices

    # Getting the mapping from class index to class label
    idx2label = dict((v,k) for k,v in label2index.items())

    # Get the predictions from the model using the generator
    predictions = model.predict_generator(validation_generator, steps=validation_generator.samples/validation_generator.batch_size,verbose=1)
    predicted_classes = np.argmax(predictions,axis=1)

    errors = np.where(predicted_classes != ground_truth)[0]
    print("No of errors = {}/{}".format(len(errors),validation_generator.samples))

    # Show the errors
    for i in range(len(errors)):
        pred_class = np.argmax(predictions[errors[i]])
        pred_label = idx2label[pred_class]

        title = 'Original label:{}, Prediction :{}, confidence : {:.3f}'.format(
            fnames[errors[i]].split('/')[0],
            pred_label,
            predictions[errors[i]][pred_class])

        original = load_img('{}/{}'.format(validation_dir,fnames[errors[i]]))
        plt.figure(figsize=[7,7])
        plt.axis('off')
        plt.title(title)
        plt.imshow(original)
        plt.show()

型号代码

from keras.engine import  Model
vgg16_model = keras.applications.vgg16.VGG16()

input_layer2 = vgg16_model.input
vgg16_model.get_layer(index = 0).name = 'input2'

last_layer2 = vgg16_model.get_layer('block4_pool').output

x = Conv2D(512, (3, 3), activation='relu', name='block5_conv1', padding='same')(last_layer2)
x = BatchNormalization(name='bn1')(x)
x = Conv2D(512, (3, 3), activation='relu', name='block5_conv2', padding='same')(x)
x = BatchNormalization(name='bn2')(x)
x = Conv2D(512, (3, 3), activation='relu', name='block5_conv3', padding='same')(x)
x = BatchNormalization(name='bn3')(x)
x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), name = 'block5_pool')(x)
x = Flatten(name = 'flatten')(x)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(4096, activation='relu', name='fc2')(x)
out2 = Dropout(0.3, name='dropout1')(x)

#Classification layer
output_layer2 = Dense(class_no, activation='softmax', name='prediction')(out2) 
vgg16_face_model = Model(input_layer2, output_layer2)

vgg16_face_model.trainable = True
set_trainable = False
for layer in vgg16_face_model.layers:
    if layer.name == 'block5_conv1':
        set_trainable = True
    if set_trainable:
        layer.trainable = True
    else:
        layer.trainable = False

请帮助我。

0 个答案:

没有答案