Keras加载模型问题

时间:2018-04-10 10:44:13

标签: python deep-learning keras

所以我遇到了一个问题,我现在已经坚持了一段时间

我正在尝试理解并重复关于对抗性示例的jupyter教程。 但是,当我加载模型时,取决于它是如何完成的,我在两个模型之间存在很大差异:    - 当它在一个类中加载时,没有问题    - 当它在jupyter上加载时,精度会降低

该课程使用以下几行:

from keras.models import Sequential, load_model

class Lenet:

  def __init__(self, epochs=200, batch_size=128, load_weights=True):
    self.name               = 'lenet'
    self.model_filename     = 'networks/models/lenet.h5'
    self.num_classes        = 10
    self.input_shape        = 32, 32, 3
    self.batch_size         = batch_size
    self.epochs             = epochs
    self.iterations         = 391
    self.weight_decay       = 0.0001
    self.log_filepath       = r'networks/models/lenet/'

    if load_weights:
        try:
            self._model = load_model(self.model_filename)
            print('Successfully loaded', self.name)
        except (ImportError, ValueError, OSError):
            print('Failed to load', self.name)
我正在做的是:

modelPath = "networks/models/lenet.h5"
lenet2 = keras.models.load_model(modelPath)

modelPath2 = "networks/models/resnet.h5"
resnet2 = keras.models.load_model(modelPath2)

然而,当我测试两种模型的准确性时:

lenet = LeNet()
resnet = ResNet() #the class is nearly the same as LeNet
models = [lenet, lenet2, resnet, resnet2]
network_stats, correct_imgs = helper.evaluate_models(models, x_test, y_test)
network_stats = pd.DataFrame(network_stats, columns=['name', 'accuracy', 'param_count'])

我得到以下结果:(network_stats)

name                accuracy    param_count
0   lenet           0.7488            62006
1   sequential_1    0.4800            62006
2   resnet          0.9231           470218
3   model_1         0.1092           470218

link to the picture

解释图片:在左边,this is the class lenet,给出了很好的结果。在右侧,我尝试加载相同的模型失败

你知道为什么会这样吗?

- 编辑 -

无法在stackoverflow上发布图片,所以我解释了一点问题

- EDIT2 -

可以使用其他网络(resnet)重现

1 个答案:

答案 0 :(得分:0)

您能提供您所关注的教程的链接吗?

您是在训练模型还是只测试准确度?

我的猜测......这个类有一个颜色预处理功能,正在改变"准确度"方法。如果非类模型没有使用相同的函数,那么关于我期望看到的结果差异。

    def accuracy(self):
        (x_train, y_train), (x_test, y_test) = cifar10.load_data()
        y_train = keras.utils.to_categorical(y_train, self.num_classes)
        y_test = keras.utils.to_categorical(y_test, self.num_classes)

        # color preprocessing
        x_train, x_test = self.color_preprocessing(x_train, x_test)  # <--- here

        return self._model.evaluate(x_test, y_test, verbose=0)[1]