如何使scikit学习机器学习模型的结果可重现

时间:2020-04-16 09:40:33

标签: python machine-learning scikit-learn random-seed

我已经使用scikit-learn工具包训练了几个模型,当我在不同的机器上运行模型时,它会给出不同的结果,但是当我在同一台机器上多次运行相同的模型时,结果就是同样,该如何解决?

示例代码:

model = ensemble.RandomForestRegressor(
        n_estimators=1000, 
        max_depth=3,
        min_samples_split=2, 
        max_features=n,
    )

model.fit(X_train, y_train)

我一直在使用joblib.dump(model,file)进行转储,并使用joblib.load()进行预测

3 个答案:

答案 0 :(得分:2)

我认为您可能需要使用种子才能获得可重复的结果。就像这样:https://www.mikulskibartosz.name/how-to-set-the-global-random_state-in-scikit-learn/

答案 1 :(得分:2)

随机种子是用于初始化伪随机数生成器的数字。如果您不使用固定种子,那么生成的伪随机数将始终是不同的,因为用于初始化生成器的数将是不同的。


现在,如果您希望结果可重复,则必须使用固定种子,以防使用scikit-learn函数作为随机种子作为参数的情况,必须确保种子始终相同。例如,对于train_test_split,您还必须使用硬编码的random_state

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

如果不这样做,那么每次运行都会得到不同的训练和测试集,因此结果会有所不同。

这同样适用于某些接受scikit-learn参数的特定random_state模型。如果要使用其中任何一个,请确保使用固定的random_state


此外,如果您的代码调用random(),则还需要确保使用固定种子:

import numpy as np
np.random.seed(42)

作为np.random.seed()的补充说明,如果您想多次致电np.random.permutation(10)并获得相同的结果,则每次致电{{1 }}。

例如,

np.random.seed(42)

将产生不同的结果:

permutation()

同时

np.random.seed(42)
print(np.random.permutation(10))
print(np.random.permutation(10))

将给出相同的输出:

[8 1 5 0 7 2 9 4 3 6]
[0 1 8 5 3 4 7 9 6 2]

或者,您可以使用

np.random.seed(42)
print(np.random.permutation(10))
np.random.seed(42)
print(np.random.permutation(10))

没有局部效果。

答案 2 :(得分:-1)

我假设您在具有相同代码的不同机器上获得不同的预测。

尝试在机器上训练模型并保存训练后的模型。您可以使用pickle模块。这是用于保存和恢复经过训练的模型的示例代码。

import pickle


# Code for your model goes here
# model = ...

# Saving the trained model in the current working directory
pkl_filename = "pickle_model.pkl"
with open(pkl_filename, 'wb') as file:
    pickle.dump(model, file)

# Load trained model from file
with open(pkl_filename, 'rb') as file:
    pickle_model = pickle.load(file)

# Use the loaded model to predict values
y_pred = pickle_model.predict(X_test)

您可以将pickle文件复制到任何计算机上,以确保每次加载相同的模型。

此外,如果要在不同的机器上训练模型并获得相同的结果,则需要对所有伪随机生成器使用固定的种子。