tensorflow - Keras:MLP 对 CPU 再现性的影响

标签 tensorflow machine-learning keras neural-network

我正在构建和测试一个简单的 MLP 模型,但我的结果遇到了 Keras 再现性问题。我正在尝试设置我的神经网络,以便在运行网络时预测输出不会改变。

我已经遵循了 Keras 在线指南以及这篇文章 ( Reproducible results using Keras with TensorFlow backend )。我在本地计算机上运行 Keras,使用 Tensorflow 后端和以下版本:

tensorflow 2.0.0-alpha0, 喀拉斯 2.2.4-tf, numpy 1.16.0

import os  
os.environ['PYTHONHASHSEED']=str(0)

import random
random.seed(0)

from numpy.random import seed
seed(1)
import tensorflow as tf
tf.compat.v1.set_random_seed(2)

from keras import backend as K
session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
K.set_session(sess)

import numpy as np
from tensorflow.python.keras.layers import Dropout, BatchNormalization
from tensorflow.python.keras.optimizers import Adam


class Machine_Learning_Classifier_Keras(object):    
    @classmethod
    def _get_classifier(cls, n_input_features=None, **params):
        KerasClassifier = tf.keras.wrappers.scikit_learn.KerasClassifier
        Dense = tf.keras.layers.Dense
        Sequential = tf.keras.models.Sequential

        sk_params = {"epochs": 200, "batch_size": 128, "shuffle": False}

        def create_model(optimizer='adam', init='he_normal'):
            # create model
            model = Sequential()
            model.add(BatchNormalization())
            model.add(Dropout(0.2))
            model.add(Dense(500, input_dim=4, kernel_initializer=init, activation='relu'))
            model.add(BatchNormalization())
            model.add(Dropout(0.2))
            model.add(Dense(250, kernel_initializer=init, activation='relu'))
            model.add(BatchNormalization())
            model.add(Dropout(0.2))
            model.add(Dense(500, kernel_initializer=init, activation='relu'))
            model.add(Dense(1, kernel_initializer=init, activation='sigmoid'))
            # Compile model
            model.compile(loss='binary_crossentropy', optimizer=Adam(lr=3e-3, decay=0.85), metrics=['accuracy'])
            return model

        return KerasClassifier(build_fn=create_model, **sk_params)

if __name__ == "__main__":
    X = np.asarray([[0.0, 0.0], [1.0, 1.0], [2.0, 2.5], [1.5, 1.6]])
    y = np.asarray([0, 0, 1, 1])

    nn = Machine_Learning_Classifier_Keras._get_classifier()
    nn.fit(X, y, sample_weight=np.asarray([0, 0, 1, 1]))

    values = np.asarray([[0.5, 0.5], [0.6, 0.5], [0.8, 1.0], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5]])

    probas = nn.predict_proba(values)
    print(probas)

我希望预测概率值的输出在运行之间保持相同;但是,我连续两次运行时得到以下结果(结果会有所不同):

    Run 1:
    [[0.9439231  0.05607685]
     [0.91351616 0.08648387]
     [0.06378722 0.9362128 ]
     [0.9439231  0.05607685]
     [0.9439231  0.05607685]
     [0.9439231  0.05607685]
     [0.94392323 0.05607677]
     [0.94392323 0.05607677]]

    Run 2:
    [[0.94391584 0.05608419]
     [0.91350436 0.08649567]
     [0.06378281 0.9362172 ]
     [0.94391584 0.05608419]
     [0.94391584 0.05608419]
     [0.94391584 0.05608419]
     [0.94391584 0.05608416]
     [0.94391584 0.05608416]]

最佳答案

最终弄清楚问题是什么,但不确定如何解决 - 它与第一个 BatchNormalization() 层有关,该层应该标准化输入。如果删除该层,结果是完全可重现的,但 BatchNormalization() 实现中的某些内容会导致不可重现的行为

关于tensorflow - Keras:MLP 对 CPU 再现性的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56587801/

相关文章:

Tensorflow 对象检测 API RCNN 在 CPU : 1 frame per min 上运行缓慢

machine-learning - 随机森林实现之间的差异

machine-learning - 使用深度神经网络估计对象大小

python - 如何从 tensorflow/keras 中下载的 tar.gz 文件加载数据?

keras - Tensorflow.js 使用自定义层和已训练的模型

tensorflow - 将 SageMaker 管道模式与 tfrecords 的 s3 目录一起使用

python - 将 tf.contrib.opt.ScipyOptimizerInterface 与 tf.keras.layers 一起使用,损失不变

python - tf.boolean_mask 不接受轴参数

python - 我可以在 "model.fit()"循环中使用 "for"来更改每次迭代中的训练数据吗

matlab - 自组织映射: How to identify clusters from plots?