使用fit_generator()时如何获取y_true,y_pred?

时间:2019-03-28 14:20:11

标签: python tensorflow keras

我正在使用fit_generator()方法来批量调整数据。

我想获取标签值的列表(预测值和实际值/ y_pred,y_true)以生成混淆矩阵等。

Keras指标文档对此没有任何信息,我发现的任何示例都仅引用fit()方法。

在每个纪元结束时如何获得y_pred和y_true?

我的代码:

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import TensorBoard, ReduceLROnPlateau, EarlyStopping, Callback
from sklearn.utils import class_weight
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np


img_width, img_height = 200, 200

train_data_dir = 'augmentedImg/200/training_data'
validation_data_dir = 'augmentedImg/200/validation_data'
nb_train_samples = 9008
nb_validation_samples = 2251
epochs = 100
batch_size = 32

layer_size = 64

if K.image_data_format() == 'channels_first':
    input_shape = (1, img_width, img_height)
else:
    input_shape = (img_width, img_height, 1)

model = Sequential()
model.add(Conv2D(layer_size, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(layer_size, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(layer_size, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(layer_size, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())

model.add(Dense(1))
model.add(Activation('sigmoid'))

NAME="Phase10-Tryingauc_roc-%dSize-Grayscale-%depoch"% (img_width, epochs)
tensorboard = TensorBoard(log_dir="logs/{}".format(NAME))
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                              patience=5, min_lr=0.001)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])


train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    rotation_range=90,
    width_shift_range=0.1,
    height_shift_range=0.1,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True
    )

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    color_mode='grayscale',
    shuffle = True,
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    color_mode='grayscale',
    batch_size=batch_size,
    class_mode='binary')

class_weights = class_weight.compute_class_weight(
               'balanced',
                np.unique(train_generator.classes), 
                train_generator.classes)

my_callbacks = [tensorboard, reduce_lr]

model.fit_generator(
    train_generator,
    class_weight=class_weights,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples,# // batch_size,
    callbacks=my_callbacks
    )

print("End of program")

1 个答案:

答案 0 :(得分:1)

要获取标签值,可以使用validation_generator.classes。它提供了用于验证的所有标签。有关更多信息,请查看此code。它显示了一个使用keras数据flow_from_directory进行混淆矩阵评估的示例。