使用Keras的VGG16进行的MNIST和转移学习-验证准确性较低

时间:2018-12-05 20:45:42

标签: python-3.x tensorflow machine-learning keras vgg-net

我最近开始在项目中使用Keras的flow_from_dataframe()功能,并决定使用MNIST数据集对其进行测试。我有一个目录,里面充满了png格式的MNIST样本,还有一个数据框,其中一列的内容为绝对目录,另一列的内容为标签。

我还使用转移学习,将VGG16导入为基础,并在10的softmax层之前添加我自己的512节点relu密集层和0.5退出(对于数字0-9)。我正在使用rmsprop(lr = 1e-4)作为优化程序。

启动环境时,它会从Git调用最新版本的keras_preprocessing,它支持绝对目录和大写的文件扩展名。

我的问题是我的训练准确性很高,而验证准确性却非常低。到最后一个时期(10),我的训练精度为0.94,验证精度为0.01。

我想知道我的脚本是否根本上有问题?对于另一个数据集,在第4个时期之后,我什至都获得了训练和验证损失值的NaN(我检查了相关列,没有任何空值!)

这是我的代码。我将不胜感激,如果有人可以浏览一下,看看是否有任何东西跳出来。

import pandas as pd
import numpy as np

import keras
from keras_preprocessing.image import ImageDataGenerator

from keras import applications
from keras import optimizers
from keras.models import Model 
from keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D
from keras import backend as k 
from keras.callbacks import ModelCheckpoint, CSVLogger

from keras.applications.vgg16 import VGG16, preprocess_input

# INITIALIZE MODEL

img_width, img_height = 32, 32
model = VGG16(weights = 'imagenet', include_top=False, input_shape = (img_width, img_height, 3))

# freeze all layers
for layer in model.layers:
    layer.trainable = False

# Adding custom Layers 
x = model.output
x = Flatten()(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.5)(x)
predictions = Dense(10, activation="softmax")(x)

# creating the final model 
model_final = Model(input = model.input, output = predictions)

# compile the model 
rms = optimizers.RMSprop(lr=1e-4)
#adadelta = optimizers.Adadelta(lr=0.001, rho=0.5, epsilon=None, decay=0.0)

model_final.compile(loss = "categorical_crossentropy", optimizer = rms, metrics=["accuracy"])

# LOAD AND DEFINE SOURCE DATA

train = pd.read_csv('MNIST_train.csv', index_col=0)
val = pd.read_csv('MNIST_test.csv', index_col=0)

nb_train_samples = 60000
nb_validation_samples = 10000
batch_size = 60
epochs = 10

# Initiate the train and test generators
train_datagen = ImageDataGenerator()
test_datagen = ImageDataGenerator()

train_generator = train_datagen.flow_from_dataframe(dataframe=train,
                                                    directory=None,
                                                    x_col='train_samples',
                                                    y_col='train_labels',
                                                    has_ext=True,
                                                    target_size = (img_height,
                                                                   img_width),
                                                    batch_size = batch_size, 
                                                    class_mode = 'categorical',
                                                    color_mode = 'rgb')

validation_generator = test_datagen.flow_from_dataframe(dataframe=val,
                                                        directory=None,
                                                        x_col='test_samples',
                                                        y_col='test_labels',
                                                        has_ext=True,
                                                        target_size = (img_height, 
                                                                       img_width),
                                                        batch_size = batch_size, 
                                                        class_mode = 'categorical',
                                                        color_mode = 'rgb')

# GET CLASS INDICES
print('****************')
for cls, idx in train_generator.class_indices.items():
    print('Class #{} = {}'.format(idx, cls))
print('****************')

# DEFINE CALLBACKS

path = './chk/epoch_{epoch:02d}-valLoss_{val_loss:.2f}-valAcc_{val_acc:.2f}.hdf5'

chk = ModelCheckpoint(path, monitor = 'val_acc', verbose = 1, save_best_only = True, mode = 'max')

logger = CSVLogger('./chk/training_log.csv', separator = ',', append=False)

nPlus = 1
samples_per_epoch = nb_train_samples * nPlus

# Train the model 
model_final.fit_generator(train_generator,
                          steps_per_epoch = int(samples_per_epoch/batch_size),
                          epochs = epochs,
                          validation_data = validation_generator,
                          validation_steps = int(nb_validation_samples/batch_size),
                          callbacks = [chk, logger])

1 个答案:

答案 0 :(得分:2)

您是否尝试过显式定义图像的类?这样:

train_generator=image.ImageDataGenerator().flow_from_dataframe(classes=[0,1,2,3,4,5,6,7,8,9])
训练生成器和验证生成器中的

我发现有时候训练和验证生成器会创建不同的对应字典。