Yenes/My-Model
0
1import torch
2import torch.nn as nn
3import torchvision.transforms as transforms
4import gradio as gr
5from PIL import Image
6
7class ConvModel(nn.Module):
8 def __init__(self):
9 super().__init__()
10 self.cnn1 = nn.Sequential(
11 nn.Conv2d(3, 16, kernel_size=3, padding=1),
12 nn.ReLU(),
13 nn.MaxPool2d(2)
14 )
15 self.cnn2 = nn.Sequential(
16 nn.Conv2d(16, 32, kernel_size=3, padding=1),
17 nn.ReLU(),
18 nn.MaxPool2d(2)
19 )
20 self.fc = nn.Sequential(
21 nn.Flatten(),
22 nn.Linear(32 * 56 * 56, 2)
23 )
24
25 def forward(self, x):
26 x = self.cnn1(x)
27 x = self.cnn2(x)
28 x = self.fc(x)
29 return x
30
31model = ConvModel()
32model.load_state_dict(torch.load("conv_model.pth", map_location="cpu"))
33model.eval()
34
35class_names=['NORMAL', 'PNEUMONIA']
36
37transform = transforms.Compose([
38 transforms.Resize((224, 224)),
39 transforms.ToTensor(),
40 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
41])
42
43def predict(img):
44 img = transform(img).unsqueeze(0)
45 with torch.inference_mode():
46 pred_probs = torch.softmax(model(img), dim=1)
47
48 pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
49 return pred_labels_and_probs
50
51
52title = "Zatürre Bulucu"
53description = "Gönderilen fotoğrafa göre Sağlıklı mı yoksa Zatürre mi olduğunu tahmin eder."
54
55demo = gr.Interface(
56 fn=predict,
57 inputs=gr.Image(type="pil"),
58 outputs=[gr.Label(num_top_classes=2, label="Predictions")],
59 title=title,
60 description=description
61)
62
63demo.launch(debug=False, share=True)