[英]Why are accuracy of fit_generator, accuracy of evaluate_generator and custom accuracy different in Keras?
I wrote the following code:我写了以下代码:
epochs = 4
batch_size = 5
numclasses = 7
train_datagen = ImageDataGenerator(
rescale=1. / 280,
rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.1, # Randomly zoom image
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
#shear_range=0.2,
vertical_flip=False,
horizontal_flip=True)
# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 280)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical')
nb_train_samples = 7*132
nb_validation_samples = 7*28
lr = 1e-5
decay = 1e-7 #0.0
optimizer = RMSprop(lr=lr, decay=decay)
# model is resnet
model.load_weights('modelweights.h5')
model.compile(loss='categorical_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
history = model.fit_generator(
train_generator,
steps_per_epoch = len(train_generator),
epochs=epochs,
workers=1,
use_multiprocessing=False,
validation_data=validation_generator,
validation_steps=len(validation_generator))
If I try to calculate the accuracy with evaluate_generator or with custom code, I get different accuracy from the one I got with fit_generator.如果我尝试使用 evaluate_generator 或自定义代码计算精度,我会得到与使用 fit_generator 不同的精度。 More specifically:
进一步来说:
y_true = validation_generator.classes
y_pred_test = model.predict_generator(validation_generator,verbose=1,steps=len(validation_generator))
predicted_class_indices=np.argmax(y_pred_test,axis=1)
custom_accuracy = accuracy_score(y_true,predicted_class_indices)
or或者
model.evaluate_generator(validation_generator,steps = len(validation_generator),verbose=1)
Accuracy variables are different values.精度变量是不同的值。 Why is this happening?
为什么会这样?
generator.classes
does not give you the labels in the same order than generator predictions, so any metric computed on this will not be correct. generator.classes
不会以与生成器预测相同的顺序为您提供标签,因此基于此计算的任何指标都将不正确。
The value computed by evaluate_generator
is correct. evaluate_generator
计算的值是正确的。
The only way to make a proper evaluation using a generator or Sequence is to iterate over all batches in the generator, computing the metric batch by batch (each batch has inputs and labels), and then aggregating the results.使用生成器或序列进行正确评估的唯一方法是迭代生成器中的所有批次,逐批次计算度量标准(每个批次都有输入和标签),然后聚合结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.