极高的分类精度keras

时间:2018-04-29 05:47:17

标签: python tensorflow machine-learning keras

我正在尝试训练CNN分类器以在七类图像之间执行图像分类。天真地,我希望算法在训练的早期时期产生约20%的准确度,但它在~40%的准确度范围内,这使我得出结论,我的模型不知何故不能正确计算分类准确性。我做错了什么?

import glob

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras.utils import plot_model
from keras.metrics import top_k_categorical_accuracy

# Define Constants
img_height = 299
img_width = 299

batch_size=40
epochs=30

train_data_dir="./train/"
validate_data_dir="./validate/"
test_data_dir="./test/"

nb_train_samples=len(glob.glob(train_data_dir+"**/*.jpg"))
nb_validation_samples= len(glob.glob(validate_data_dir+"**/*.jpg"))
nb_test_samples= len(glob.glob(test_data_dir+"**/*.jpg"))

# Define CNN Layers
if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

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

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

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

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(7, activation='softmax'))

def top_2_categorical_accuracy(y_true, y_pred):
    return top_k_categorical_accuracy(y_true, y_pred, k=2) 

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['categorical_accuracy', top_2_categorical_accuracy])

# Train Datagen
print("\nInitializing Training Data Generator:")
train_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')
print("")

# Validation Datagen
print("Initializing Validation Data Generator:")
validation_datagen = ImageDataGenerator(rescale=1. / 255)
valid_generator = validation_datagen.flow_from_directory(
    validate_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')
print("")

# Test Datagen
print("Initializing Test Data Generator:")
test_datagen = ImageDataGenerator(rescale=1. / 255)
test_generator = test_datagen.flow_from_directory(
    test_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')
print("")

# Run
print("Starting Training...")
model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=valid_generator,
    validation_steps=nb_validation_samples // batch_size,
    verbose=2)
print("Done!\n\n")

# Save Weights
model.save('model.h5')

# Evaluate
print("Starting Testing...")
print("[Loss, Percent Error]")
model.evaluate_generator(test_generator)

这是输出:

Using TensorFlow backend.

Initializing Training Data Generator:
Found 5600 images belonging to 7 classes.

Initializing Validation Data Generator:
Found 700 images belonging to 7 classes.

Initializing Test Data Generator:
Found 700 images belonging to 7 classes.

Starting Training...
Epoch 1/30
 - 58s - loss: 1.8719 - categorical_accuracy: 0.2279 - top_2_categorical_accuracy: 0.4107 - val_loss: 1.8315 - val_categorical_accuracy: 0.2809 - val_top_2_categorical_accuracy: 0.4456
Epoch 2/30
 - 53s - loss: 1.7584 - categorical_accuracy: 0.2913 - top_2_categorical_accuracy: 0.4714 - val_loss: 1.6551 - val_categorical_accuracy: 0.3485 - val_top_2_categorical_accuracy: 0.5559
Epoch 3/30
 - 53s - loss: 1.6987 - categorical_accuracy: 0.3166 - top_2_categorical_accuracy: 0.5150 - val_loss: 1.6445 - val_categorical_accuracy: 0.3897 - val_top_2_categorical_accuracy: 0.5735
Epoch 4/30
 - 53s - loss: 1.6495 - categorical_accuracy: 0.3407 - top_2_categorical_accuracy: 0.5418 - val_loss: 1.5398 - val_categorical_accuracy: 0.3868 - val_top_2_categorical_accuracy: 0.6029
Epoch 5/30
 - 53s - loss: 1.5844 - categorical_accuracy: 0.3687 - top_2_categorical_accuracy: 0.5729 - val_loss: 1.5124 - val_categorical_accuracy: 0.4162 - val_top_2_categorical_accuracy: 0.5985
Epoch 6/30
 - 53s - loss: 1.4989 - categorical_accuracy: 0.4075 - top_2_categorical_accuracy: 0.6132 - val_loss: 1.5065 - val_categorical_accuracy: 0.3956 - val_top_2_categorical_accuracy: 0.6029
Epoch 7/30
 - 53s - loss: 1.4233 - categorical_accuracy: 0.4314 - top_2_categorical_accuracy: 0.6416 - val_loss: 1.4560 - val_categorical_accuracy: 0.4618 - val_top_2_categorical_accuracy: 0.6441
Epoch 8/30
 - 53s - loss: 1.3212 - categorical_accuracy: 0.4754 - top_2_categorical_accuracy: 0.6770 - val_loss: 1.4556 - val_categorical_accuracy: 0.4324 - val_top_2_categorical_accuracy: 0.6309
Epoch 9/30
 - 53s - loss: 1.2623 - categorical_accuracy: 0.4993 - top_2_categorical_accuracy: 0.7055 - val_loss: 1.5422 - val_categorical_accuracy: 0.4397 - val_top_2_categorical_accuracy: 0.6279
Epoch 10/30

1 个答案:

答案 0 :(得分:0)

发生这种情况的原因有两个:

  1. 使用steps_per_epoch=nb_train_samples // batch_size意味着它只会在batch_size个时代之后看到整个集合。

  2. 未设置shuffle选项。

  3. 结果,该模型正在学习投票给某个特定的课程。虽然这不是一个“错误”。可以这么说,在一个时代的结束时,准确度如此之高是令人担忧的。