Keras模型(tensorflow后端)在python 3.5中训练得非常好,但在python 2.7中非常糟糕

ben*_*min 6 model python-2.7 python-3.5 keras tensorflow

我尝试做什么
我正在尝试使用Keras和Tensorflow-GPU作为后端在Python 2.7中训练卷积神经网络(CNN)进行图像检测,因为我需要将它与ROS动力学一起使用,它只支持Python 2.7(而不是3.5).我的模型是Sequential(代码见下).

我正在使用
Pycharm-Community 2018.1.4 Keras
2.2.0
Tensorflow-GPU 1.8.0
60000输入图像,100x100像素(3通道),3类("train_set")
20000评估图像,相同尺寸("evaluation_set")

什么工作
当使用Python 3.5在我的train_set上训练模型并使用Python 3.5进行评估时,它的工作完全正常(train_accuracy:0.99874,evaluation_accuracy:0.9993).

什么不起作用
使用Python 2.7在我的train_set上训练模型并使用Python 2.7进行评估时,我的准确率急剧下降(train_accuracy:0.695,evaluation_accuracy:0.543),这不过是猜测3个类(这将是0.3333) .
我还尝试在Python 3.5中训练模型并将其加载到Python 2.7中以进行评估和预测,但结果与以前一样糟糕.

在所有情况下,我使用完全相同的代码:

def build_model(training_input):
    model = Sequential()  
    model.add(Conv2D(32, (3, 3)) # Add some layers

    model.compile(optimizer='RMSprop', loss='categorical_crossentropy', metrics=['accuracy'])

def train():
    input_training = np.array(input_training_list)    # input_training_list is a list containing the imagedata
    labels_training = np.array(label_training_list)    # label_training_list is a list containing the labels corresponding to the imagedata
    model = create_model(input_training)
    history = model.fit(input_training, labels_training, epochs=10, shuffle=True, batch_size=20)
    model.save(model_directory + "my_model.h5")

def evaluation():
    input_evaluation = np.array(input_evaluation_list)
    labels_evaluation = np.array(label_evaluation_list)
    model = load_model(model_directory + "my_model.h5")
    loss, acc = model.evaluate(input_evaluation, labels_evaluation, batch_size=1)
Run Code Online (Sandbox Code Playgroud)

我听说很多人在使用不同的计算机或不同版本的Python在不同的Sessions()中加载相同的模型时遇到问题.但是在这两个Python版本中,相同的架构给出了完全不同的结果.

ben*_*min 2

我找到了问题的解决方案(感谢 user1735003 关于我的数据的提示)。我的糟糕结果的原因是由于Python 2.x 和 Python 3.x 的差异导致
数据实现错误。在实现我的图像数据时,我使用

for i in range(len(evaluation_files)):
    input_evaluation = np.divide(ndimage.imread(evaluation_files[i]), 255)
Run Code Online (Sandbox Code Playgroud)

但问题是:在 Python 3.x 中,这工作得很好,因为两个整数相除会产生浮点数,但在 Python 2.x 中,结果也是整数,所以我的 input_evalution 列表仅由零组成。我需要除以 255.0(使结果成为浮点数)。

input_evaluation = np.divide(ndimage.imread(evaluation_files[i]), 255.0)
Run Code Online (Sandbox Code Playgroud)

或者导入divisionfrom__future__以从 python 2 中已有的整数除法中获取浮点结果。

from __future__ import division
Run Code Online (Sandbox Code Playgroud)

使用 Python 2.x 或 Python 3.x 时存在一些主要差异,您可以在http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html上清楚地看到这些差异。

我还设法在 Python 3.5 上训练我的模型,使用 保存model.save('my_model')并使用 Python 2.7 加载它keras.models.load_model('my_model'),效果非常好。

人们还可以轻松地使用 保存权重model.save_weights('my_weights'),在 Python 2.7 中创建一个相同架构的新模型(!),并使用 加载权重到该模型中model.load_weights('my_weights'),但由于仅加载模型本身就可以完美地工作,因此这种方式要容易得多。