Purpose
이 Code Snippet은 '결과 재현이나 작업의 효율 증대 등을 위해 PyTorch의 기본 설정'하고자 합니다.
Dependency Packages
torch
random
numpy
os
Code Example
Ex1) PyTorch에서 GPU를 사용할 수 있는지 확인하고, Device 설정 및 출력
import torch
if torch.cuda.is_avilable() :
device = torch.device("cuda:0")
print(torch.cuda.get_device_properties(device))
else :
device = torch.device("cpu")
print("device is cpu")
Ex2) 결과 재현을 위해 각종 Random Seed를 고정
import torch
import random
import os
import numpy as np
def set_seed(seed: int):
"""
Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if
installed).
Args:
seed (:obj:`int`): The seed to set.
"""
print(f'all seed is {seed}')
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
if is_torch_available():
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if use multi-GPU
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
seed = 42
set_seed(seed)
PS
torch.cuda에 관련된 자세한 정보는 여기를 참고바랍니다. (Link)
'Python Code Snippet' 카테고리의 다른 글
[Python Code Snippet] Pickle File 저장하고 불러오는 함수 (0) | 2021.05.21 |
---|---|
[Python Code Snippet] Average Meter (0) | 2021.05.21 |
[Python Code Snippet] 코랩에 구글 드라이브 연결 (0) | 2021.03.24 |
[Python Code Snippet] 파일 입출력 (0) | 2021.03.23 |
[Python Code Snippet] 파일 확인 및 조작 (0) | 2021.03.23 |