首页 > 解决方案 > 为什么在加载时序列化的 numpy random_state 对象不同?

问题描述

我试图弄清楚为什么使用一组定义的索引、相同的输入数据和相同random_state的 in进行某些交叉验证会使用相同的模型超参数sklearn给出不同的结果。LogisticRegression我的第一个想法是,random_state后续运行中的初始值可能会有所不同。然后我意识到当我直接比较两个对象picklerandom_state它说对象不同但get_state方法中的值是相同的。为什么是这样?

random_state = np.random.RandomState(0)
print(random_state)
# <mtrand.RandomState object at 0x12424e480>

with open("./rs.pkl", "wb") as f:
    pickle.dump(random_state, f, protocol=pickle.HIGHEST_PROTOCOL)
with open("./rs.pkl", "rb") as f:
    random_state_copy = pickle.load(f)
    print(random_state_copy)
# <mtrand.RandomState object at 0x126465240>
print(random_state == random_state_copy)
# False
print(str(random_state.get_state()) == str(random_state_copy.get_state()))
# True

版本:

numpy='1.13.3',

Python='3.6.4 |Anaconda, Inc.| (默认,2018 年 1 月 16 日,12:04:33)\n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]')

标签: pythonnumpyrandomseed

解决方案


在您的示例中,初始随机状态的未腌制副本实际上会产生相同的随机数序列(在 python 3.6、numpy 1.15.4 上测试)。RandomState正如@jasonharper 指出的那样,可能没有实施平等测试。==返回False,但状态在行为上是相同的。

在您提供的代码之后插入以下代码片段:

a = random_state.randint(0, 10, 5)
b = random_state_copy.randint(0, 10, 5)
print(a)
print(b)
print(a==b)

产生:

[5 0 3 3 7]
[5 0 3 3 7]
[ True  True  True  True  True]

因此,最有可能的是,不是RandomState使运行结果不同:在其他地方寻找差异的原因。


推荐阅读