Spaces:
Running
Running
Create 27_Inception_model.py
Browse files- pages/27_Inception_model.py +104 -0
pages/27_Inception_model.py
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.optim as optim
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torchvision import datasets, transforms
|
6 |
+
from torch.utils.data import DataLoader
|
7 |
+
import streamlit as st
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
# Define the Inception Module
|
12 |
+
class InceptionModule(nn.Module):
|
13 |
+
def __init__(self, in_channels):
|
14 |
+
super(InceptionModule, self).__init__()
|
15 |
+
|
16 |
+
self.branch1x1 = nn.Conv2d(in_channels, 64, kernel_size=1)
|
17 |
+
|
18 |
+
self.branch3x3 = nn.Conv2d(in_channels, 64, kernel_size=3, padding=1)
|
19 |
+
|
20 |
+
self.branch5x5 = nn.Conv2d(in_channels, 64, kernel_size=5, padding=2)
|
21 |
+
|
22 |
+
self.branch_pool = nn.Conv2d(in_channels, 64, kernel_size=1)
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
branch1x1 = self.branch1x1(x)
|
26 |
+
|
27 |
+
branch3x3 = self.branch3x3(x)
|
28 |
+
|
29 |
+
branch5x5 = self.branch5x5(x)
|
30 |
+
|
31 |
+
branch_pool = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)(x)
|
32 |
+
branch_pool = self.branch_pool(branch_pool)
|
33 |
+
|
34 |
+
outputs = [branch1x1, branch3x3, branch5x5, branch_pool]
|
35 |
+
return torch.cat(outputs, 1)
|
36 |
+
|
37 |
+
# Define the Inception Network
|
38 |
+
class InceptionNet(nn.Module):
|
39 |
+
def __init__(self, num_classes=10):
|
40 |
+
super(InceptionNet, self).__init__()
|
41 |
+
|
42 |
+
self.inception1 = InceptionModule(in_channels=3)
|
43 |
+
self.fc = nn.Linear(64 * 4 * 224 * 224, num_classes)
|
44 |
+
|
45 |
+
def forward(self, x):
|
46 |
+
x = self.inception1(x)
|
47 |
+
x = x.view(x.size(0), -1)
|
48 |
+
x = self.fc(x)
|
49 |
+
return x
|
50 |
+
|
51 |
+
# Training function
|
52 |
+
def train(model, device, train_loader, optimizer, epoch):
|
53 |
+
model.train()
|
54 |
+
for batch_idx, (data, target) in enumerate(train_loader):
|
55 |
+
data, target = data.to(device), target.to(device)
|
56 |
+
optimizer.zero_grad()
|
57 |
+
output = model(data)
|
58 |
+
loss = F.cross_entropy(output, target)
|
59 |
+
loss.backward()
|
60 |
+
optimizer.step()
|
61 |
+
if batch_idx % 10 == 0:
|
62 |
+
print(f'Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)} ({100. * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}')
|
63 |
+
|
64 |
+
# Define a simple transformation
|
65 |
+
transform = transforms.Compose([
|
66 |
+
transforms.Resize((224, 224)),
|
67 |
+
transforms.ToTensor()
|
68 |
+
])
|
69 |
+
|
70 |
+
# Initialize model and optimizer
|
71 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
72 |
+
model = InceptionNet().to(device)
|
73 |
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
74 |
+
|
75 |
+
# Streamlit app
|
76 |
+
st.title("InceptionNet Image Classifier")
|
77 |
+
|
78 |
+
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
|
79 |
+
if uploaded_file is not None:
|
80 |
+
image = plt.imread(uploaded_file)
|
81 |
+
st.image(image, caption='Uploaded Image', use_column_width=True)
|
82 |
+
|
83 |
+
image = transform(image).unsqueeze(0).to(device)
|
84 |
+
|
85 |
+
st.write("Classifying...")
|
86 |
+
model.eval()
|
87 |
+
with torch.no_grad():
|
88 |
+
output = model(image)
|
89 |
+
st.write("Output:", output.cpu().detach().numpy())
|
90 |
+
|
91 |
+
# Adjust Hyperparameters
|
92 |
+
st.sidebar.title("Adjust Hyperparameters")
|
93 |
+
learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 0.01, 0.001)
|
94 |
+
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
|
95 |
+
|
96 |
+
# Visualize Model's Predictions
|
97 |
+
if st.sidebar.button("Train Model"):
|
98 |
+
# Load dummy data for demonstration purposes
|
99 |
+
train_loader = DataLoader(
|
100 |
+
datasets.FakeData(transform=transform),
|
101 |
+
batch_size=64, shuffle=True
|
102 |
+
)
|
103 |
+
train(model, device, train_loader, optimizer, epoch=1)
|
104 |
+
st.sidebar.write("Model Trained!")
|