|
|
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| class SwishActivation(nn.Module): |
| def forward(self, x): |
| return x * torch.sigmoid(x) |
|
|
| class ChannelAttention(nn.Module): |
| def __init__(self, in_channels, ratio=16): |
| super(ChannelAttention, self).__init__() |
| self.fc1 = nn.Conv2d(in_channels, in_channels // ratio, 1, bias=False) |
| self.fc2 = nn.Conv2d(in_channels // ratio, in_channels, 1, bias=False) |
| self.sigmoid = nn.Sigmoid() |
|
|
| def forward(self, x): |
| avg_out = torch.mean(x, dim=(2, 3), keepdim=True) |
| avg_out = self.fc2(F.relu(self.fc1(avg_out))) |
| return x * self.sigmoid(avg_out) |
|
|
| class BuildingBlock(nn.Module): |
| def __init__(self, in_channels, out_channels, stride=1): |
| super(BuildingBlock, self).__init__() |
| self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) |
| self.norm1 = nn.BatchNorm2d(out_channels) |
| self.swish1 = SwishActivation() |
| self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1) |
| self.norm2 = nn.BatchNorm2d(out_channels) |
| self.channel_attention = ChannelAttention(out_channels) |
| self.conv3 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride) |
| self.norm3 = nn.BatchNorm2d(out_channels) |
| self.swish2 = SwishActivation() |
| |
| def forward(self, x): |
| residual = x |
| out = self.conv1(x) |
| out = self.norm1(out) |
| out = self.swish1(out) |
| out = self.conv2(out) |
| out = self.norm2(out) |
| out = self.channel_attention(out) |
| if x.size() != out.size(): |
| residual = self.conv3(residual) |
| residual = self.norm3(residual) |
| out += residual |
| out = self.swish2(out) |
| return out |
| class UNetEncoder(nn.Module): |
| def __init__(self, in_channels, out_channels, num_blocks): |
| super(UNetEncoder, self).__init__() |
| self.initial_conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1) |
| self.initial_norm = nn.BatchNorm2d(out_channels) |
| self.initial_swish = SwishActivation() |
| self.blocks = nn.ModuleList([BuildingBlock(out_channels, out_channels) for _ in range(num_blocks)]) |
| |
| def forward(self, x): |
| x = self.initial_conv(x) |
| x = self.initial_norm(x) |
| x = self.initial_swish(x) |
| for block in self.blocks: |
| x = block(x) |
| return x |
|
|
| def encode(self, x): |
| features = [] |
| x = self.initial_conv(x) |
| x = self.initial_norm(x) |
| x = self.initial_swish(x) |
| features.append(x) |
| for block in self.blocks: |
| x = block(x) |
| features.append(x) |
| return features |
| class ClassificationModel(nn.Module): |
| def __init__(self, encoder, num_classes=10): |
| super(ClassificationModel, self).__init__() |
| self.encoder = encoder |
| self.global_avg_pool = nn.AdaptiveAvgPool2d((1, 1)) |
| self.fc = nn.Linear(encoder.blocks[-1].conv2.out_channels, num_classes) |
| |
| def forward(self, x): |
| features = self.encoder.encode(x) |
| x = self.global_avg_pool(features[-1]) |
| x = x.view(x.size(0), -1) |
| x = self.fc(x) |
| return x |
| |
| encoder = UNetEncoder(in_channels=3, out_channels=64, num_blocks=1) |
| classification_model = ClassificationModel(encoder, num_classes=2) |
|
|
| |
| |
| criterion = nn.CrossEntropyLoss() |
| optimizer = torch.optim.Adam(classification_model.parameters(), lr=1e-6) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| import pandas as pd |
| import os |
| from PIL import Image |
| from torch.utils.data import Dataset, DataLoader |
| import torchvision.transforms as transforms |
|
|
| import pandas as pd |
| import os |
| from PIL import Image |
| from torch.utils.data import Dataset, DataLoader, Subset |
| import torchvision.transforms as transforms |
| from sklearn.model_selection import train_test_split |
|
|
| |
| class CustomImageDataset(Dataset): |
| def __init__(self, csv_file, root_dir, transform=None): |
| self.data = pd.read_csv(csv_file) |
| self.root_dir = root_dir |
| self.transform = transform |
|
|
| def __len__(self): |
| return len(self.data) |
|
|
| def __getitem__(self, idx): |
| img_name = os.path.join(self.root_dir, self.data.iloc[idx, 0]+'.jpg') |
| image = Image.open(img_name).convert('RGB') |
| label = self.data.iloc[idx, 7] |
| |
| if self.transform: |
| image = self.transform(image) |
| |
| return image, label |
|
|
| |
| transform = transforms.Compose([ |
| transforms.Resize((224, 224)), |
| transforms.ToTensor(), |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| ]) |
|
|
| |
| csv_file_path = 'data/ISIC_2020_Training_GroundTruth.csv' |
| image_folder_path = 'data/train' |
|
|
| |
| data = pd.read_csv(csv_file_path) |
| |
| train_indices, test_indices = train_test_split(range(len(data)), test_size=0.015, random_state=42) |
|
|
| |
| train_dataset = Subset(CustomImageDataset(csv_file=csv_file_path, root_dir=image_folder_path, transform=transform), train_indices) |
| test_dataset = Subset(CustomImageDataset(csv_file=csv_file_path, root_dir=image_folder_path, transform=transform), test_indices) |
|
|
| |
| train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=4) |
| test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4) |
|
|
| best_accuracy=-1 |
| results_file="results//encoder_pretrained_rana_sir_a_block_model(num_blocks_1).txt" |
| early_stopping_epochs=2 |
| import tqdm |
| |
| for epoch in range(1): |
| for input,label in tqdm.tqdm(train_loader,desc=f'Epoch {epoch + 1}/100 (training)'): |
| optimizer.zero_grad() |
| outputs = classification_model(input) |
| loss = criterion(outputs, label) |
| loss.backward() |
| optimizer.step() |
| classification_model.eval() |
| total_correct = 0 |
| total_samples = 0 |
| with torch.no_grad(): |
| for input, label in tqdm.tqdm(test_loader): |
| outputs = classification_model(input) |
| _, predicted = torch.max(outputs, 1) |
| total_samples += label.size(0) |
| total_correct += (predicted == label).sum().item() |
| |
| |
| accuracy = total_correct / total_samples |
| print(f'Epoch {epoch + 1}, Accuracy: {accuracy:.4f}') |
|
|
| with open(results_file, 'a+') as f: |
| f.write(f'Epoch {epoch + 1}, Accuracy: {accuracy:.4f}\n') |
|
|
| |
| if accuracy > best_accuracy: |
| best_accuracy = accuracy |
| epochs_without_improvement = 0 |
| |
| torch.save(classification_model.state_dict(), 'model//isic(Block_1).pth') |
| else: |
| epochs_without_improvement += 1 |
| |
| |
| if epochs_without_improvement >= early_stopping_epochs: |
| print(f'Early stopping after epoch {epoch + 1}') |
| break |
|
|
| print('Training finished.') |
|
|
|
|
|
|
|
|
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |