python - 为什么在加载时序列化的 numpy random_state 对象不同?
问题描述
我试图弄清楚为什么使用一组定义的索引、相同的输入数据和相同random_state
的 in进行某些交叉验证会使用相同的模型超参数sklearn
给出不同的结果。LogisticRegression
我的第一个想法是,random_state
后续运行中的初始值可能会有所不同。然后我意识到当我直接比较两个对象pickle
时random_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)]')
解决方案
在您的示例中,初始随机状态的未腌制副本实际上会产生相同的随机数序列(在 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
使运行结果不同:在其他地方寻找差异的原因。
推荐阅读
- python - 随着用户选择和训练数据而改进的线性回归模型
- sql - 从链接中提取数据并将其放置在新列中
- ballerina - Ballerina V 1.0 - 将数据库连接保存在单独的文件中
- laravel - 如何在 Laravel 5.8 的 owl carousal 滑块中显示我的数据库图像?
- elasticsearch - 使用 Elastic Stack 基本订阅的 OEM
- python - Python requests: Passing multiple client certificates to session.cert
- amazon-redshift - SQLWorkbenchJ 和 Redshift 永远执行这个查询
- android - 启动画面在 android 上的 react-native 应用程序中不起作用
- javascript - 计算无处不在。需要数学奇才
- python - 如何使用for循环绘制直方图和条形图并将它们一起显示?