자주 쓰는 모듈/라이브러리
import pandas as pd
pd.set_option('mode.chained_assignment', None)
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set_style('darkgrid')
import warnings
warnings.filterwarnings('ignore')
import sys
from glob import glob
import os
import platform
import random
import sklearn
import cv2
from PIL import Image
import torch
from torchvision import models
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from torchvision.models.efficientnet import efficientnet_b0, efficientnet_b1
import torch.nn.functional as F
from sklearn.metrics import f1_score
from tqdm import tqdm
def seed_everything(seed: int = 2022):
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
print(f"Setup complete. Using torch {torch.__version__} ({torch.cuda.get_device_properties(0).name if torch.cuda.is_available() else 'CPU'})")
print(f"- os: {platform.platform()}")
print(f"- python: {sys.version}")
print(f"- pandas: {pd.__version__}")
print(f"- numpy: {np.__version__}")
print(f"- sklearn: {sklearn.__version__}")
print(f"- pytorch: {torch.__version__}")
print(f"- opencv: {cv2.__version__}")
class config:
seed = 2022
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
lr = 3e-3
scheduler = ''
epochs = 100
batch_size = 16
patience = 5
min_delta = 1e-3
dropout= 0.5
optimizer = 'Adam'
train_5_folds = True
tta = True
seed_everything(config.seed)
acc_check
def acc_check(net, test_set, epoch, save=1):
correct = 0
total = 0
with torch.no_grad():
for data in test_set:
images, labels = data
images = images.to(device)
labels = labels.to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
acc = (100 * correct / total)
print('Accuracy of the network on the 10000 test images: %d %%' % acc)
if save:
torch.save(net.state_dict(), "./model/model_epoch_{}_acc_{}.pth".format(epoch, int(acc)))
return acc
모델 저장 / 불러오기
def save_model(model, saved_dir, file_name='best_model.pt'):
os.makedirs(saved_dir, exist_ok=True)
check_point = {
'net': model.state_dict()
}
output_path = os.path.join(saved_dir, file_name)
torch.save(model.state_dict(), output_path)
model_path = './saved/CNN/best_model.pt'
model = CNN().to(device)
checkpoint = torch.load(model_path, map_location=device)
model.load_state_dict(checkpoint)
GPU 캐시 비우기
import gc
gc.collect()
torch.cuda.empty_cache()
경로 확인 및 이동
os.getcwd()
os.chdir(r"C:\User")
f = open("sample folder/sample.txt", "r")