python - Issue with reproducibility across different sessions
问题描述
I am trying to make a script reproducible but having some issue. The code is in Tensorflow 2.x and doesn't use keras API. It has many layers build with tf.compat. The model is created and trained with a function get_model()
os.environ['tf_deterministic_ops'] = "2"
os.environ["PYTHONHASHSEED"] = "2"
random.seed(2)
np.random.seed(2)
tf.random.set_seed(2)
for i in range(5):
get_model()
So, I am training the same model 5 times above, and the results are same every time. But When I run the following script 5 times, the results are different. Am I doing something wrong? Any help will be great. Thanks!
os.environ['tf_deterministic_ops'] = "2"
os.environ["PYTHONHASHSEED"] = "2"
random.seed(2)
np.random.seed(2)
tf.random.set_seed(2)
get_model()
解决方案
我想说一切正常:设置随机种子总是产生相同的随机变量序列,例如
import numpy as np
# set seed
np.random.seed(2)
for i in range(5):
print(np.random.randint(10)) # prints: 8, 8, 6, 2, 8
for i in range(5):
np.random.seed(2)
print(np.random.randint(10)) # prints: 8, 8, 8, 8, 8
因此,运行您的第二个脚本五次每次都会产生相同的模型,因为您在每次执行时都将种子设置为 2。在您的第一个脚本中迭代 for 循环会生成与前五个输出中的变量相对应的模型,其中seed=2
. 使用我的代码示例:您的第二个脚本将始终创建模型“8”,您的第一个脚本创建模型“8”、“8”、“6”、“2”和“8”。
推荐阅读
- python - 以字符串格式返回一天
- swift - 将 ViewController 嵌入到 NavigationController 中时 - 快速 - 以编程方式
- javascript - jquery 多个选择器在 keyup/keydown 事件上具有唯一的超时
- typescript - TypeScript:Jest 测试中的类型上不存在属性“mockImplementation”
- javascript - 如何调整已使用 `alignItems` 和 `justifyContent` 垂直和水平居中的组件的位置?
- matlab - 矩阵对角线上的高斯包络
- c++ - Ostream 和 istream 作为构造函数的争论
- java - 收到n个元素后如何退出akka流?
- python - 如何使用 gremlin 和 python 在海王星中进行组合布尔运算?
- c# - EF Core 获取整个对象以进行空检查