網站首頁 編程語言 正文
pytorch設置隨機種子
pytorch設置隨機種子 - 保證復現模型所有的訓練過程
在使用 PyTorch 時,如果希望通過設置隨機數種子,在 GPU 或 CPU 上固定每一次的訓練結果,則需要在程序執行的開始處添加以下代碼:
def seed_everything():
'''
設置整個開發環境的seed
:param seed:
:param device:
:return:
'''
import os
import random
import numpy as np
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# some cudnn methods can be random even after fixing the seed
# unless you tell it to be deterministic
torch.backends.cudnn.deterministic = True
pytorch/tensorflow設置隨機種子 ,保證結果復現
Pytorch隨機種子設置
import numpy as np
import random
import os
import torch
def seed_torch(seed=2021):
? ? random.seed(seed)
? ? os.environ['PYTHONHASHSEED'] = str(seed)
? ? np.random.seed(seed)
? ? torch.manual_seed(seed)
? ? torch.cuda.manual_seed(seed)
? ? torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
? ? torch.backends.cudnn.benchmark = False
? ? torch.backends.cudnn.deterministic = True
? ? torch.backends.cudnn.enabled = False
seed_torch()
Tensorflow設置隨機種子
第一步 僅導入設置種子和初始化種子值所需的那些庫
import tensorflow as tf
import os
import numpy as np
import random
SEED = 0
第二步 為所有可能具有隨機行為的庫初始化種子的函數
def set_seeds(seed=SEED):
? ? os.environ['PYTHONHASHSEED'] = str(seed)
? ? random.seed(seed)
? ? tf.random.set_seed(seed)
? ? np.random.seed(seed)
第三步 激活 Tensorflow 確定性功能
def set_global_determinism(seed=SEED):
? ? set_seeds(seed=seed)
? ? os.environ['TF_DETERMINISTIC_OPS'] = '1'
? ? os.environ['TF_CUDNN_DETERMINISTIC'] = '1'
? ??
? ? tf.config.threading.set_inter_op_parallelism_threads(1)
? ? tf.config.threading.set_intra_op_parallelism_threads(1)
# Call the above function with seed value
set_global_determinism(seed=SEED)
總結
原文鏈接:https://blog.csdn.net/xu624735206/article/details/124999824
相關推薦
- 2022-09-06 Python的functools模塊使用及說明_python
- 2022-04-25 利用Redis實現訪問次數限流的方法詳解_Redis
- 2022-08-19 vscode遠程免密登入Linux服務器的配置方法_Linux
- 2022-10-25 Python第三方常用模塊openpyxl的簡單介紹_python
- 2022-06-06 python?包之?threading?多線程_python
- 2022-06-27 Python數據類型和常用操作_python
- 2022-10-14 WebSecurityConfigurerAdapter已棄用
- 2023-05-30 docker運行nginx綁定配置文件失敗原因以及問題解決_docker
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支