gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:39:20 24 4
gpt4 key购买 nike

我想做什么
我正在尝试使用 Keras 和 Tensorflow-GPU 作为 Python 2.7 的后端来训练卷积神经网络 (CNN) 进行图像检测,因为我需要将它与仅支持 Python 2.7(而不是 3.5)的 ROS kinetic 一起使用。我的模型是一个序列(代码见下文)。

我在用什么
Pycharm-社区 2018.1.4
凯拉斯 2.2.0
Tensorflow-GPU 1.8.0
60000 张输入图像,100x100 像素(3 个 channel ),3 个类别(“train_set”)
20000 张评估图像,相同尺寸(“evaluation_set”)

什么有效
使用 在我的 train_set 上训练模型时Python 3.5 并使用 Python 3.5 对其进行评估,它工作得非常好(train_accuracy:0.99874,evaluation_accuracy:0.9993)。

什么不起作用
使用 在我的 train_set 上训练模型时Python 2.7 并使用 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)

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

最佳答案

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

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

但问题是:在 Python 3.x 中,这工作得很好,因为两个整数的除法会产生一个浮点数,但在 Python 2.x 中,结果也是一个整数,所以我的 input_evaluation 列表只包含零。我需要 除以 255.0 (使结果为浮点数)。
input_evaluation = np.divide(ndimage.imread(evaluation_files[i]), 255.0)

或者导入 division来自 __future__从python 2中已经存在的整数除法中获取浮点结果。
from __future__ import division

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

我还管理在 Python 3.5 上训练我的模型,使用 model.save('my_model') 保存它并使用 keras.models.load_model('my_model') 在 Python 2.7 中加载它,它工作得很好。

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

关于python-2.7 - Keras 模型(tensorflow 后端)在 python 3.5 中训练得很好,但在 python 2.7 中非常糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50872628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com