카테고리 없음

RSNA 2023 Abdominal Trauma Detection(2)

꾸물꾸물 말고 꿈을 2023. 10. 11. 20:53

모델 변경

 

1.resnet18

# 전이학습된 ResNet-34 모델 불러옴 
model = torchvision.models.resnet18(False)
#미리 학습된 모델 가중치를 로드
model.load_state_dict(torch.load("/kaggle/input/pretrained-model-weights-pytorch/resnet18-5c106cde.pth"))
#모델의 fully connected (FC) 레이어를 새로운 레이어로 교체 및 출력크기 설정
model.fc = torch.nn.Linear(512, 14)
#모델의 첫 번째 합성곱 레이어를 변경.
#흑백 이미지를 처리-> 입력 채널 수를 1로 설정함, 출력 채널 수:64로 설정( ResNet 아키텍처에서 사용되는 출력 채널 수)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)

#모델을 GPU로 이동
model = model.cuda()

#다수 클래스(음성 클래스)에 비해 소수 클래스(양성 클래스)가 더 적은 경우 양성 클래스에 대한 가중치를 높게 설정
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
#BCEWithLogitsLoss, 양성 클래스에 대한 가중치를 적용
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

#최적화 알고리즘으로 SGD(Stochastic Gradient Descent)를 사용하며, 학습률은 0.0005로 설정
#모델의 학습 가능한 모든 매개변수를 최적화
optimizer = torch.optim.SGD(model.parameters(), 0.0005)

 

2.resnet50

# 전ResNet-34 모델 불러옴 
model = torchvision.models.resnet18(False)
#미리 학습된 모델 가중치를 로드
model.load_state_dict(torch.load("/kaggle/input/pretrained-model-weights-pytorch/resnet18-5c106cde.pth"))
#모델의 fully connected (FC) 레이어를 새로운 레이어로 교체 및 출력크기 설정
model.fc = torch.nn.Linear(512, 14)
#모델의 첫 번째 합성곱 레이어를 변경.
#흑백 이미지를 처리-> 입력 채널 수를 1로 설정함, 출력 채널 수:64로 설정( ResNet 아키텍처에서 사용되는 출력 채널 수)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)

#모델을 GPU로 이동
model = model.cuda()

#다수 클래스(음성 클래스)에 비해 소수 클래스(양성 클래스)가 더 적은 경우 양성 클래스에 대한 가중치를 높게 설정
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
#BCEWithLogitsLoss, 양성 클래스에 대한 가중치를 적용
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

#최적화 알고리즘으로 SGD(Stochastic Gradient Descent)를 사용하며, 학습률은 0.0005로 설정
#모델의 학습 가능한 모든 매개변수를 최적화
optimizer = torch.optim.SGD(model.parameters(), 0.0005)

 

 

 

3.resnet 50 + 증식 옵션 추가 + L2규제  

from torch.optim.lr_scheduler import StepLR
from tqdm import tqdm
model = torchvision.models.resnet50(False)
model.load_state_dict(torch.load("/kaggle/input/pretrained-model-weights-pytorch/resnet50-19c8e357.pth"))
#model.fc = torch.nn.Linear(512, 14)
model.fc = torch.nn.Linear(2048, 14)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)

model = model.cuda()
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

# Adam 옵티마이저 생성
optimizer = optim.Adam(model.parameters(),lr=0.0005, weight_decay=0.0005)  # 학습률(lr)은 필요에 따라 조절

#optimizer = torch.optim.SGD(model.parameters(), lr=0.0005, weight_decay=0.0001)
scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
# Define the transform
transform_train = transforms.Compose([
    transforms.RandomResizedCrop(size=(224, 224), scale=(0.8, 1.0)),
    transforms.ColorJitter(brightness=0.2, contrast=0.2),
    transforms.RandomRotation(degrees=15),
    transforms.Resize((224, 224)),  # Resize the image to 224x224 pixels
    transforms.RandomVerticalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.RandomHorizontalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.ToTensor()  # Convert the image to a PyTorch tensor
])

# Define the transform
transform_val = transforms.Compose([
    transforms.Resize((224, 224)),  # Resize the image to 224x224 pixels
    transforms.RandomVerticalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.RandomHorizontalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.ToTensor()  # Convert the image to a PyTorch tensor
])

-그냥  resnet18,34,50로 훈련시켰을때 val loss 는 증가하고 train loss는 감소해서 과적합이 심한것 같아서

aug 증식 옵션 추가하고 , l2규제 넣고 , adam optimizer 로 변경했는데 처음보다 loss값이 급격히 변하지 않았음.

 

 

4.resnet18  + 위와 증식옵션 같음.

import torch
torch.manual_seed(0)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True

from PIL import Image
import torchvision.models as models
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data.dataset import Dataset

# Define the transform
transform_train = transforms.Compose([
    transforms.Resize((224, 224)),  # Resize the image to 224x224 pixels
    transforms.RandomRotation(degrees=15),  # 15도까지 랜덤한 회전
    transforms.ColorJitter(brightness=0.2, contrast=0.2),
    transforms.RandomResizedCrop(size=(224, 224), scale=(0.8, 1.0), ratio=(1.0,1.0)),
    transforms.RandomVerticalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.RandomHorizontalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.ToTensor()  # Convert the image to a PyTorch tensor
    
])
# Define the transform
transform_val = transforms.Compose([
    transforms.Resize((224, 224)),  # Resize the image to 224x224 pixels
    transforms.RandomVerticalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.RandomHorizontalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.ToTensor()  # Convert the image to a PyTorch tensor
    
])

model = torchvision.models.resnet18(False)
#미리 학습된 모델 가중치를 로드
model.load_state_dict(torch.load("/kaggle/input/pretrained-model-weights-pytorch/resnet18-5c106cde.pth"))
#모델의 fully connected (FC) 레이어를 새로운 레이어로 교체 및 출력크기 설정
model.fc = torch.nn.Linear(512, 14)
#model.fc = torch.nn.Linear(2048, 14)

#모델의 첫 번째 합성곱 레이어를 변경.
#흑백 이미지를 처리-> 입력 채널 수를 1로 설정함, 출력 채널 수:64로 설정( ResNet 아키텍처에서 사용되는 출력 채널 수)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)

#모델을 GPU로 이동
model = model.cuda()

#다수 클래스(음성 클래스)에 비해 소수 클래스(양성 클래스)가 더 적은 경우 양성 클래스에 대한 가중치를 높게 설정
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
#BCEWithLogitsLoss, 양성 클래스에 대한 가중치를 적용
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

#최적화 알고리즘으로 SGD(Stochastic Gradient Descent)를 사용하며, 학습률은 0.0005로 설정
#모델의 학습 가능한 모든 매개변수를 최적화
#optimizer = torch.optim.SGD(model.parameters(),lr=0.0001,weight_decay=0.0005)

# Adam 최적화 알고리즘으로 변경
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, weight_decay=0.0005)

from torch.optim.lr_scheduler import StepLR
scheduler = StepLR(optimizer, step_size=5, gamma=0.5)

5. resnet18+ 규제 0.001 +

import torch
torch.manual_seed(0)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True

from PIL import Image
import torchvision.models as models
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data.dataset import Dataset

# Define the transform
transform_train = transforms.Compose([
    transforms.Resize((224, 224)),  # Resize the image to 224x224 pixels
    transforms.RandomRotation(degrees=15),  # 15도까지 랜덤한 회전
    transforms.ColorJitter(brightness=0.2, contrast=0.2),
    transforms.RandomResizedCrop(size=(224, 224), scale=(0.8, 1.0), ratio=(1.0,1.0)),
    transforms.RandomVerticalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.RandomHorizontalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.ToTensor()  # Convert the image to a PyTorch tensor
    
])
# Define the transform
transform_val = transforms.Compose([
    transforms.Resize((224, 224)),  # Resize the image to 224x224 pixels
    transforms.RandomVerticalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.RandomHorizontalFlip(0.5),  # Resize the image to 224x224 pixels
    transforms.ToTensor()  # Convert the image to a PyTorch tensor
    
])

 

# 전이학습된 ResNet-34 모델 불러옴 
model = torchvision.models.resnet18(False)
#미리 학습된 모델 가중치를 로드
model.load_state_dict(torch.load("/kaggle/input/pretrained-model-weights-pytorch/resnet18-5c106cde.pth"))
#모델의 fully connected (FC) 레이어를 새로운 레이어로 교체 및 출력크기 설정
model.fc = torch.nn.Linear(512, 14)
#model.fc = torch.nn.Linear(2048, 14)

#모델의 첫 번째 합성곱 레이어를 변경.
#흑백 이미지를 처리-> 입력 채널 수를 1로 설정함, 출력 채널 수:64로 설정( ResNet 아키텍처에서 사용되는 출력 채널 수)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)

#모델을 GPU로 이동
model = model.cuda()

#다수 클래스(음성 클래스)에 비해 소수 클래스(양성 클래스)가 더 적은 경우 양성 클래스에 대한 가중치를 높게 설정
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
#BCEWithLogitsLoss, 양성 클래스에 대한 가중치를 적용
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

#최적화 알고리즘으로 SGD(Stochastic Gradient Descent)를 사용하며, 학습률은 0.0005로 설정
#모델의 학습 가능한 모든 매개변수를 최적화
#optimizer = torch.optim.SGD(model.parameters(),lr=0.0001,weight_decay=0.0005)

# Adam 최적화 알고리즘으로 변경
optimizer = torch.optim.Adam(model.parameters(), lr=0.0005, weight_decay=0.001)

from torch.optim.lr_scheduler import StepLR
scheduler = StepLR(optimizer, step_size=5, gamma=0.5)

 

리더보드

ep7

ep 8부터 이어서 학습

 

이어서 학습

train loss와 val loss 잘 떨어지지 않아서 l2 규제 줄임.

# 전이학습된 ResNet-34 모델 불러옴 
model = torchvision.models.resnet18(False)
#미리 학습된 모델 가중치를 로드
#모델의 fully connected (FC) 레이어를 새로운 레이어로 교체 및 출력크기 설정
model.fc = torch.nn.Linear(512, 14)
#model.fc = torch.nn.Linear(2048, 14)

#모델의 첫 번째 합성곱 레이어를 변경.
#흑백 이미지를 처리-> 입력 채널 수를 1로 설정함, 출력 채널 수:64로 설정( ResNet 아키텍처에서 사용되는 출력 채널 수)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
model.load_state_dict(torch.load("/kaggle/input/resnet18-ep7-ep-16-train/model_8.pth"))
#모델을 GPU로 이동
model = model.cuda()

#다수 클래스(음성 클래스)에 비해 소수 클래스(양성 클래스)가 더 적은 경우 양성 클래스에 대한 가중치를 높게 설정
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
#BCEWithLogitsLoss, 양성 클래스에 대한 가중치를 적용
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

#최적화 알고리즘으로 SGD(Stochastic Gradient Descent)를 사용하며, 학습률은 0.0005로 설정
#모델의 학습 가능한 모든 매개변수를 최적화
#optimizer = torch.optim.SGD(model.parameters(),lr=0.0001,weight_decay=0.0005)

# Adam 최적화 알고리즘으로 변경
optimizer = torch.optim.Adam(model.parameters(), lr=0.0005, weight_decay=0.0005)

from torch.optim.lr_scheduler import StepLR
scheduler = StepLR(optimizer, step_size=5, gamma=0.5)

ep3,5,8

ep16

ep부터 이어서 학습

 

 

l2규제 줄임

# 전이학습된 ResNet-34 모델 불러옴 
model = torchvision.models.resnet18(False)
#미리 학습된 모델 가중치를 로드
#모델의 fully connected (FC) 레이어를 새로운 레이어로 교체 및 출력크기 설정
model.fc = torch.nn.Linear(512, 14)
#model.fc = torch.nn.Linear(2048, 14)
#ep16+18=ep34
#모델의 첫 번째 합성곱 레이어를 변경.
#흑백 이미지를 처리-> 입력 채널 수를 1로 설정함, 출력 채널 수:64로 설정( ResNet 아키텍처에서 사용되는 출력 채널 수)
model.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
model.load_state_dict(torch.load("/kaggle/working/model_17.pth"))
#모델을 GPU로 이동
model = model.cuda()

#다수 클래스(음성 클래스)에 비해 소수 클래스(양성 클래스)가 더 적은 경우 양성 클래스에 대한 가중치를 높게 설정
pos_weight = torch.Tensor([1,2,1,6,1,2,4,1,2,4,1,2,4,6]).cuda()
#BCEWithLogitsLoss, 양성 클래스에 대한 가중치를 적용
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)

#최적화 알고리즘으로 SGD(Stochastic Gradient Descent)를 사용하며, 학습률은 0.0005로 설정
#모델의 학습 가능한 모든 매개변수를 최적화
#optimizer = torch.optim.SGD(model.parameters(),lr=0.0001,weight_decay=0.0005)

# Adam 최적화 알고리즘으로 변경
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, weight_decay=0.0001)

from torch.optim.lr_scheduler import StepLR
scheduler = StepLR(optimizer, step_size=5, gamma=0.5)

 

https://www.kaggle.com/code/noir3747/rsna-v1/notebook