Commit
·
250a0ca
1
Parent(s):
6518169
Migration with slight changes
Browse files- app.py +207 -0
- model.py +205 -0
- requirements.txt +0 -0
app.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from huggingface_hub import hf_hub_download
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from medmnist import INFO
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import os
|
| 9 |
+
import base64
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from huggingface_hub import HfApi
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
import io
|
| 14 |
+
|
| 15 |
+
from model import resnet18, resnet50
|
| 16 |
+
|
| 17 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 18 |
+
AUTH_TOKEN = os.getenv("APP_TOKEN")#to acces the app
|
| 19 |
+
DATASET_REPO = os.getenv("Dataset_repo") #"G44mlops/API_received"
|
| 20 |
+
HF_TOKEN = os.getenv("HF_TOKEN") #to acces dataset repo
|
| 21 |
+
MODEL = os.getenv("Model_repo")#"G44mlops/ResNet-medmnist"
|
| 22 |
+
|
| 23 |
+
#taken from Mikolaj code with closed PR
|
| 24 |
+
def load_model_from_hf(
|
| 25 |
+
repo_id: str,
|
| 26 |
+
filename: str,
|
| 27 |
+
model_type: str,
|
| 28 |
+
num_classes: int,
|
| 29 |
+
in_channels: int,
|
| 30 |
+
device: str,
|
| 31 |
+
) -> torch.nn.Module:
|
| 32 |
+
"""Load trained model from Hugging Face Hub.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
repo_id: Hugging Face repository ID
|
| 36 |
+
filename: Model checkpoint filename
|
| 37 |
+
model_type: Type of model ('resnet18' or 'resnet50')
|
| 38 |
+
num_classes: Number of output classes
|
| 39 |
+
in_channels: Number of input channels
|
| 40 |
+
device: Device to load model on
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
Loaded model in eval mode
|
| 44 |
+
"""
|
| 45 |
+
print(f"Downloading model from Hugging Face: {repo_id}/{filename}")
|
| 46 |
+
checkpoint_path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 47 |
+
|
| 48 |
+
# Create model
|
| 49 |
+
if model_type == "resnet18":
|
| 50 |
+
model = resnet18(num_classes=num_classes, in_channels=in_channels)
|
| 51 |
+
else:
|
| 52 |
+
model = resnet50(num_classes=num_classes, in_channels=in_channels)
|
| 53 |
+
|
| 54 |
+
# Load checkpoint
|
| 55 |
+
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)
|
| 56 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 57 |
+
model.to(device)
|
| 58 |
+
model.eval()
|
| 59 |
+
|
| 60 |
+
return model
|
| 61 |
+
#taken from Mikolaj code with closed PR
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Image preprocessing pipeline (basic so far, can be improved)
|
| 65 |
+
def get_preprocessing_pipeline() -> transforms.Compose:
|
| 66 |
+
"""Get preprocessing pipeline for images."""
|
| 67 |
+
#getting information on number of image channels (RGB or Grayscale) for trained model
|
| 68 |
+
info = INFO["organamnist"] # Using organamnist as reference
|
| 69 |
+
output_channels = info["n_channels"] # RGB or Grayscale
|
| 70 |
+
#chosing 'standard' mean and std values for normalization if dataset statistics are not available
|
| 71 |
+
mean = (0.5,) * output_channels
|
| 72 |
+
std = (0.5,) * output_channels
|
| 73 |
+
#preparing transformation pipeline
|
| 74 |
+
trans = transforms.Compose([
|
| 75 |
+
transforms.Resize(256),
|
| 76 |
+
transforms.CenterCrop(224),
|
| 77 |
+
transforms.ToTensor(),
|
| 78 |
+
transforms.Normalize(mean=mean, std=std),
|
| 79 |
+
])
|
| 80 |
+
#returning the transformation pipeline
|
| 81 |
+
return trans
|
| 82 |
+
def get_class_labels(data_flag: str = "organamnist") -> list[str]:
|
| 83 |
+
"""Get class labels for MedMNIST dataset."""
|
| 84 |
+
#retrieving dataset info
|
| 85 |
+
info = INFO[data_flag]
|
| 86 |
+
labels = info["label"]
|
| 87 |
+
#returning class labels
|
| 88 |
+
return labels
|
| 89 |
+
|
| 90 |
+
def save_image_to_hf_folder(image_path, prediction_label):
|
| 91 |
+
"""Upload image to HF dataset folder."""
|
| 92 |
+
api = HfApi()
|
| 93 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 94 |
+
|
| 95 |
+
# Create a text file with metadata
|
| 96 |
+
metadata = f"prediction: {prediction_label}\ntimestamp: {timestamp}"
|
| 97 |
+
metadata_path = f"{Path(image_path).stem}_metadata.txt"
|
| 98 |
+
|
| 99 |
+
# Upload image
|
| 100 |
+
api.upload_file(
|
| 101 |
+
path_or_fileobj=image_path,
|
| 102 |
+
path_in_repo=f"uploads/{timestamp}_{Path(image_path).name}",
|
| 103 |
+
repo_id=DATASET_REPO,
|
| 104 |
+
repo_type="dataset",
|
| 105 |
+
token=HF_TOKEN
|
| 106 |
+
)
|
| 107 |
+
# Upload metadata as separate file
|
| 108 |
+
api.upload_file(
|
| 109 |
+
path_or_fileobj=io.BytesIO(metadata.encode()),
|
| 110 |
+
path_in_repo=f"uploads/{timestamp}_{Path(image_path).stem}_metadata.txt",
|
| 111 |
+
repo_id=DATASET_REPO,
|
| 112 |
+
repo_type="dataset",
|
| 113 |
+
token=HF_TOKEN
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def classify_images(images) -> str:
|
| 117 |
+
"""Classify images and return formatted HTML with embedded images."""
|
| 118 |
+
# Handle case with no images
|
| 119 |
+
if images is None:
|
| 120 |
+
return "<p>No images uploaded</p>"
|
| 121 |
+
# Ensure images is a list if(case when only one image is uploaded is problematic without it)
|
| 122 |
+
if isinstance(images, str):
|
| 123 |
+
images = [images]
|
| 124 |
+
#creating HTML structure for results
|
| 125 |
+
html = "<div style='display: flex; flex-wrap: wrap; gap: 30px; padding: 20px; justify-content: center;'>"
|
| 126 |
+
#loop over images and classify them
|
| 127 |
+
for image_path in images:
|
| 128 |
+
#preparing image for classification
|
| 129 |
+
img = Image.open(image_path).convert("L") # Convert to grayscale (as project uses grayscale images)
|
| 130 |
+
input_tensor = preprocess(img).unsqueeze(0)
|
| 131 |
+
#forward pass + softmax to get probabilities
|
| 132 |
+
with torch.no_grad():
|
| 133 |
+
output = model(input_tensor)
|
| 134 |
+
probs = torch.nn.functional.softmax(output[0], dim=0)
|
| 135 |
+
top_class = probs.argmax().item()
|
| 136 |
+
#getting class label
|
| 137 |
+
label = class_labels[str(top_class)]
|
| 138 |
+
#getting image filename
|
| 139 |
+
filename = Path(image_path).name
|
| 140 |
+
#Preparing image for embedding in HTML (base64 encoding)
|
| 141 |
+
buffered = BytesIO()
|
| 142 |
+
img.save(buffered, format="JPEG")
|
| 143 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 144 |
+
#adding current image block to HTML
|
| 145 |
+
html += f"""
|
| 146 |
+
<div style='border: 2px solid #ddd; padding: 15px; border-radius: 8px; background: #f9f9f9; width: 280px;'>
|
| 147 |
+
<p style='font-size: 14px; color: #666; margin: 0 0 10px 0; text-align: center; font-weight: bold;'>{filename}</p>
|
| 148 |
+
<img src='data:image/jpeg;base64,{img_str}' style='width: 250px; height: 250px; object-fit: contain; display: block; margin: 0 auto 10px;'>
|
| 149 |
+
<p style='font-size: 18px; color: #0066cc; margin: 10px 0 0 0; text-align: center; font-weight: bold;'>{label}</p>
|
| 150 |
+
</div>
|
| 151 |
+
"""
|
| 152 |
+
# Save image and metadata to HF dataset folder
|
| 153 |
+
save_image_to_hf_folder(image_path, label)
|
| 154 |
+
#closing HTML container
|
| 155 |
+
html += "</div>"
|
| 156 |
+
#returning results
|
| 157 |
+
return html
|
| 158 |
+
|
| 159 |
+
###main code to launch Gradio app###
|
| 160 |
+
|
| 161 |
+
#prepare model and preprocessing pipeline (kind of backend)
|
| 162 |
+
model = load_model_from_hf(#taken from Mikolaj code with closed PR
|
| 163 |
+
repo_id=MODEL,
|
| 164 |
+
filename="resnet18_best.pth",
|
| 165 |
+
model_type="resnet18",
|
| 166 |
+
num_classes=11,
|
| 167 |
+
in_channels=1,
|
| 168 |
+
device=DEVICE,
|
| 169 |
+
)
|
| 170 |
+
preprocess = get_preprocessing_pipeline()
|
| 171 |
+
class_labels = get_class_labels()
|
| 172 |
+
#preparing Gradio interface (frontend)
|
| 173 |
+
with gr.Blocks() as demo:
|
| 174 |
+
#app "title"
|
| 175 |
+
gr.Markdown("<h1 style='text-align: center;'> MLOps project - MedMNIST dataset Image Classifier</h1>")
|
| 176 |
+
#app message/information )
|
| 177 |
+
gr.Markdown("This is a Gradio web application for MLOps course project. Given images are stored in our dataset. " \
|
| 178 |
+
"By uploading images you agrree that they will be stored by us and insures that they can be stored by us. " \
|
| 179 |
+
"If you somewhat passed the login and are not connected to the project, please do not upload any images. " )
|
| 180 |
+
#app spine layout
|
| 181 |
+
with gr.Column():
|
| 182 |
+
#title of load segment
|
| 183 |
+
gr.Markdown("<h2 style='text-align: center;'> Upload Images</h2>")
|
| 184 |
+
#images loading component
|
| 185 |
+
images_input = gr.File(file_count="multiple", file_types=["image"], label="Upload Images")
|
| 186 |
+
#buttons row for app functionality
|
| 187 |
+
with gr.Row():
|
| 188 |
+
submit_btn = gr.Button("Classify")
|
| 189 |
+
reset_btn = gr.Button("Reset")
|
| 190 |
+
#title of results segment
|
| 191 |
+
gr.Markdown("<h2 style='text-align: center;'> Results</h2>")
|
| 192 |
+
#classification results output component
|
| 193 |
+
output = gr.HTML(label="Results")
|
| 194 |
+
#getting callable reset function
|
| 195 |
+
def reset():
|
| 196 |
+
return None, ""
|
| 197 |
+
#linking buttons to functions
|
| 198 |
+
submit_btn.click(classify_images, inputs=images_input, outputs=output)
|
| 199 |
+
reset_btn.click(reset, outputs=[images_input, output])
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
#just launch
|
| 203 |
+
server_name = os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
|
| 204 |
+
demo.launch(
|
| 205 |
+
server_name=server_name,
|
| 206 |
+
auth=[("user", AUTH_TOKEN)] if AUTH_TOKEN else None
|
| 207 |
+
)
|
model.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class BasicBlock(nn.Module):
|
| 6 |
+
"""Basic building block for ResNet-18/34"""
|
| 7 |
+
expansion = 1
|
| 8 |
+
|
| 9 |
+
def __init__(self, in_channels: int, out_channels: int, stride: int = 1, downsample: nn.Module = None):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 12 |
+
self.bn1 = nn.BatchNorm2d(out_channels)
|
| 13 |
+
self.relu = nn.ReLU(inplace=True)
|
| 14 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
|
| 15 |
+
self.bn2 = nn.BatchNorm2d(out_channels)
|
| 16 |
+
self.downsample = downsample
|
| 17 |
+
|
| 18 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 19 |
+
identity = x
|
| 20 |
+
|
| 21 |
+
out = self.conv1(x)
|
| 22 |
+
out = self.bn1(out)
|
| 23 |
+
out = self.relu(out)
|
| 24 |
+
|
| 25 |
+
out = self.conv2(out)
|
| 26 |
+
out = self.bn2(out)
|
| 27 |
+
|
| 28 |
+
if self.downsample is not None:
|
| 29 |
+
identity = self.downsample(x)
|
| 30 |
+
|
| 31 |
+
out += identity
|
| 32 |
+
out = self.relu(out)
|
| 33 |
+
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Bottleneck(nn.Module):
|
| 38 |
+
"""Bottleneck building block for ResNet-50/101/152"""
|
| 39 |
+
expansion = 4
|
| 40 |
+
|
| 41 |
+
def __init__(self, in_channels: int, out_channels: int, stride: int = 1, downsample: nn.Module = None):
|
| 42 |
+
super().__init__()
|
| 43 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
|
| 44 |
+
self.bn1 = nn.BatchNorm2d(out_channels)
|
| 45 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 46 |
+
self.bn2 = nn.BatchNorm2d(out_channels)
|
| 47 |
+
self.conv3 = nn.Conv2d(out_channels, out_channels * self.expansion, kernel_size=1, bias=False)
|
| 48 |
+
self.bn3 = nn.BatchNorm2d(out_channels * self.expansion)
|
| 49 |
+
self.relu = nn.ReLU(inplace=True)
|
| 50 |
+
self.downsample = downsample
|
| 51 |
+
|
| 52 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 53 |
+
identity = x
|
| 54 |
+
|
| 55 |
+
out = self.conv1(x)
|
| 56 |
+
out = self.bn1(out)
|
| 57 |
+
out = self.relu(out)
|
| 58 |
+
|
| 59 |
+
out = self.conv2(out)
|
| 60 |
+
out = self.bn2(out)
|
| 61 |
+
out = self.relu(out)
|
| 62 |
+
|
| 63 |
+
out = self.conv3(out)
|
| 64 |
+
out = self.bn3(out)
|
| 65 |
+
|
| 66 |
+
if self.downsample is not None:
|
| 67 |
+
identity = self.downsample(x)
|
| 68 |
+
|
| 69 |
+
out += identity
|
| 70 |
+
out = self.relu(out)
|
| 71 |
+
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ResNet(nn.Module):
|
| 76 |
+
"""ResNet model for image classification
|
| 77 |
+
|
| 78 |
+
Supports ResNet-18, ResNet-34, ResNet-50, ResNet-101, ResNet-152
|
| 79 |
+
Adapted for small images like MedMNIST (28x28)
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
block: type[BasicBlock | Bottleneck],
|
| 85 |
+
layers: list[int],
|
| 86 |
+
num_classes: int = 11,
|
| 87 |
+
in_channels: int = 1,
|
| 88 |
+
):
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.in_channels = 64
|
| 91 |
+
|
| 92 |
+
# Initial convolution layer (adapted for small 28x28 images)
|
| 93 |
+
self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=3, stride=1, padding=1, bias=False)
|
| 94 |
+
self.bn1 = nn.BatchNorm2d(64)
|
| 95 |
+
self.relu = nn.ReLU(inplace=True)
|
| 96 |
+
# Removed maxpool for small images
|
| 97 |
+
|
| 98 |
+
# ResNet layers
|
| 99 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
| 100 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
| 101 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
| 102 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
| 103 |
+
|
| 104 |
+
# Global average pooling and classifier
|
| 105 |
+
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
|
| 106 |
+
self.fc = nn.Linear(512 * block.expansion, num_classes)
|
| 107 |
+
|
| 108 |
+
# Initialize weights
|
| 109 |
+
self._initialize_weights()
|
| 110 |
+
|
| 111 |
+
def _make_layer(self, block: type[BasicBlock | Bottleneck], out_channels: int, blocks: int, stride: int = 1) -> nn.Sequential:
|
| 112 |
+
downsample = None
|
| 113 |
+
if stride != 1 or self.in_channels != out_channels * block.expansion:
|
| 114 |
+
downsample = nn.Sequential(
|
| 115 |
+
nn.Conv2d(self.in_channels, out_channels * block.expansion, kernel_size=1, stride=stride, bias=False),
|
| 116 |
+
nn.BatchNorm2d(out_channels * block.expansion),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
layers = []
|
| 120 |
+
layers.append(block(self.in_channels, out_channels, stride, downsample))
|
| 121 |
+
self.in_channels = out_channels * block.expansion
|
| 122 |
+
for _ in range(1, blocks):
|
| 123 |
+
layers.append(block(self.in_channels, out_channels))
|
| 124 |
+
|
| 125 |
+
return nn.Sequential(*layers)
|
| 126 |
+
|
| 127 |
+
def _initialize_weights(self):
|
| 128 |
+
for m in self.modules():
|
| 129 |
+
if isinstance(m, nn.Conv2d):
|
| 130 |
+
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
| 131 |
+
elif isinstance(m, nn.BatchNorm2d):
|
| 132 |
+
nn.init.constant_(m.weight, 1)
|
| 133 |
+
nn.init.constant_(m.bias, 0)
|
| 134 |
+
|
| 135 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 136 |
+
x = self.conv1(x)
|
| 137 |
+
x = self.bn1(x)
|
| 138 |
+
x = self.relu(x)
|
| 139 |
+
|
| 140 |
+
x = self.layer1(x)
|
| 141 |
+
x = self.layer2(x)
|
| 142 |
+
x = self.layer3(x)
|
| 143 |
+
x = self.layer4(x)
|
| 144 |
+
|
| 145 |
+
x = self.avgpool(x)
|
| 146 |
+
x = torch.flatten(x, 1)
|
| 147 |
+
x = self.fc(x)
|
| 148 |
+
|
| 149 |
+
return x
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def resnet18(num_classes: int = 11, in_channels: int = 1) -> ResNet:
|
| 153 |
+
"""ResNet-18 model
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
num_classes: Number of output classes (default: 11 for organamnist)
|
| 157 |
+
in_channels: Number of input channels (default: 1 for grayscale)
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
ResNet-18 model
|
| 161 |
+
"""
|
| 162 |
+
return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes, in_channels=in_channels)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def resnet50(num_classes: int = 11, in_channels: int = 1) -> ResNet:
|
| 166 |
+
"""ResNet-50 model
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
num_classes: Number of output classes (default: 11 for organamnist)
|
| 170 |
+
in_channels: Number of input channels (default: 1 for grayscale)
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
ResNet-50 model
|
| 174 |
+
"""
|
| 175 |
+
return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, in_channels=in_channels)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# Keep the old Model class for backward compatibility
|
| 179 |
+
class Model(nn.Module):
|
| 180 |
+
"""Just a dummy model to show how to structure your code"""
|
| 181 |
+
def __init__(self):
|
| 182 |
+
super().__init__()
|
| 183 |
+
self.layer = nn.Linear(1, 1)
|
| 184 |
+
|
| 185 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 186 |
+
return self.layer(x)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
# Test ResNet-18
|
| 191 |
+
model18 = resnet18(num_classes=11, in_channels=1)
|
| 192 |
+
x = torch.rand(4, 1, 28, 28) # Batch of 4 grayscale 28x28 images
|
| 193 |
+
output = model18(x)
|
| 194 |
+
print(f"ResNet-18 output shape: {output.shape}") # Should be [4, 11]
|
| 195 |
+
|
| 196 |
+
# Test ResNet-50
|
| 197 |
+
model50 = resnet50(num_classes=11, in_channels=1)
|
| 198 |
+
output50 = model50(x)
|
| 199 |
+
print(f"ResNet-50 output shape: {output50.shape}") # Should be [4, 11]
|
| 200 |
+
|
| 201 |
+
# Count parameters
|
| 202 |
+
params18 = sum(p.numel() for p in model18.parameters())
|
| 203 |
+
params50 = sum(p.numel() for p in model50.parameters())
|
| 204 |
+
print(f"ResNet-18 parameters: {params18:,}")
|
| 205 |
+
print(f"ResNet-50 parameters: {params50:,}")
|
requirements.txt
ADDED
|
Binary file (14.4 kB). View file
|
|
|