changed cnn architecture, added website image upload

This commit is contained in:
2026-04-29 14:02:56 +02:00
parent fd1c111739
commit 262dbe9f98
18 changed files with 264 additions and 51 deletions
+16
View File
@@ -0,0 +1,16 @@
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Copy requirements first (better Docker layer caching)
COPY . .
# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Make sure the startup script is executable
RUN chmod +x start_server.sh
# Use the script as the container entrypoint
ENTRYPOINT ["./start_server.sh"]
Binary file not shown.

After

Width:  |  Height:  |  Size: 218 KiB

Binary file not shown.
Binary file not shown.
+62 -11
View File
@@ -3,26 +3,77 @@ import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
class SeparableConvolution(nn.Module):
def __init__(self, c_in, c_out, kernel_size):
super().__init__()
self.depthwise = nn.Conv2d(c_in, c_in, kernel_size, groups=c_in, padding=kernel_size//2)
self.bn1 = nn.BatchNorm2d(c_in)
self.pointwise = nn.Conv2d(c_in, c_out, kernel_size=1)
self.bn2 = nn.BatchNorm2d(c_out)
def forward(self, x):
x = self.depthwise(x)
x = self.bn1(x)
x = F.relu(x)
x = self.pointwise(x)
x = self.bn2(x)
x = F.relu(x)
return x
class Bird_CNN(nn.Module):
def __init__(self, c_in, c_hidden, c_out, kernel_size, img_width, img_height):
def __init__(self, c_in, c_hidden, c_out):
super().__init__()
self.model = nn.Sequential(
nn.Conv2d(c_in, c_hidden, kernel_size, padding=kernel_size//2),
nn.ReLU(),
nn.Conv2d(c_hidden, c_hidden, kernel_size, padding=kernel_size//2),
self.conv_init = nn.Sequential(
nn.Conv2d(c_in, c_hidden, kernel_size=3, padding=1),
nn.BatchNorm2d(c_hidden),
nn.ReLU(),
nn.Flatten(),
nn.Linear(c_hidden * img_height * img_width, c_out)
nn.Conv2d(c_hidden, c_hidden, 3, stride=2, padding=1)
)
# 1x1 conv branch
self.branch1 = SeparableConvolution(c_in=c_hidden, c_out=64, kernel_size=1)
# 1x1 -> 3x3 conv branch
self.branch2 = SeparableConvolution(c_in=c_hidden, c_out=128, kernel_size=3)
# 1x1 -> 5x5 conv branch
self.branch3 = SeparableConvolution(c_in=c_hidden, c_out=32, kernel_size=5)
# 3x3 max pooling -> 1x1 conv branch
self.branch4 = nn.Sequential(
nn.MaxPool2d(kernel_size=3, stride=1, padding=1),
nn.Conv2d(c_hidden, 32, kernel_size=1),
nn.ReLU()
)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.flatten = nn.Flatten()
self.linear = nn.Linear(256, c_out)
self.dropout = nn.Dropout(0.3)
def forward(self, x):
return self.model(x)
x = self.conv_init(x)
b1 = self.branch1(x)
b2 = self.branch2(x)
b3 = self.branch3(x)
b4 = self.branch4(x)
x = torch.cat([b1, b2, b3, b4], dim=1)
x = F.relu(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.dropout(x)
return self.linear(x)
def trainCNN(model, optimizer, loss_module, train_data_loader, validation_data_loader, device, num_epochs, SAVE_PATH, save=False):
@@ -79,7 +130,7 @@ def trainCNN(model, optimizer, loss_module, train_data_loader, validation_data_l
save_dir = os.path.join(SAVE_PATH, "bird_cnn")
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, "bird_cnn")
save_path = os.path.join(save_dir, f"bird_cnn{epoch+1}")
torch.save(model.state_dict(), save_path)
print(f"epoch: {epoch+1} | train accuracy: {int(train_acc * 1000) / 10}% | validation accuracy: {int(val_acc * 1000) / 10}%")
+3 -3
View File
@@ -34,13 +34,13 @@ val_size = len(dataset) - train_size
train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)
train_loader = DataLoader(train_dataset, batch_size=26, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=26, shuffle=False)
device = torch.device("cpu") if not torch.cuda.is_available() else torch.device("cuda:0")
print("Using device", device)
model = Bird_CNN(c_in=3, c_hidden=15, c_out=7, kernel_size=3, img_width=IMAGE_SIZE[0], img_height=IMAGE_SIZE[1])
model = Bird_CNN(c_in=3, c_hidden=15, c_out=7)
model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)
loss_module = nn.CrossEntropyLoss()
+7
View File
@@ -0,0 +1,7 @@
fastapi==0.136.1
networkx==3.6.1
numpy==2.3.4
torch==2.11.0+cu126
torchvision==0.26.0+cu126
tqdm==4.67.3
uvicorn==0.46.0
+13
View File
@@ -4,6 +4,7 @@ import os
import torch
from torchvision import transforms
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import io
import torch.nn.functional as F
@@ -43,6 +44,18 @@ model.eval()
app = FastAPI()
origins = [
"http://localhost:5173",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image_bytes = await file.read()
+1
View File
@@ -0,0 +1 @@
python -m uvicorn server:app --reload