Views
No views yet
1import torch
2import torch.nn as nn
3from torchvision import transforms
4from PIL import Image
5import matplotlib.pyplot as plt
6import os
7
8
9class SimpleCNN(nn.Module):
10 def __init__(self, num_classes=6):
11 super(SimpleCNN, self).__init__()
12 self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
13 self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
14 self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
15 self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
16 self.fc1 = nn.Linear(128 * 28 * 28, 512)
17 self.fc2 = nn.Linear(512, num_classes)
18 self.relu = nn.ReLU()
19 self.dropout = nn.Dropout(0.5)
20
21 def forward(self, x):
22 x = self.pool(self.relu(self.conv1(x)))
23 x = self.pool(self.relu(self.conv2(x)))
24 x = self.pool(self.relu(self.conv3(x)))
25 x = x.view(-1, 128 * 28 * 28)
26 x = self.relu(self.fc1(x))
27 x = self.dropout(x)
28 x = self.fc2(x)
29 return x
30
31
32def predict_image(model, image_path, transform, device):
33 image = Image.open(image_path).convert('RGB')
34 image = transform(image)
35 image = image.unsqueeze(0)
36
37 model.eval()
38
39 with torch.no_grad():
40 image = image.to(device)
41 outputs = model(image)
42 _, predicted = torch.max(outputs, 1)
43 probabilities = torch.nn.functional.softmax(outputs, dim=1)
44 confidence = probabilities[0, predicted].item() * 100
45
46 return predicted.item(), confidence, image
47
48
49def main():
50 transform = transforms.Compose([
51 transforms.Resize((224, 224)),
52 transforms.ToTensor(),
53 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
54 ])
55
56 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
57 model = SimpleCNN(num_classes=6).to(device)
58 model.load_state_dict(
59 torch.load('Vbai-DPA 2.0/model/yolu',
60 map_location=device))
61
62 image_path = 'test/görüntüsü/yolu'
63
64 predicted_class, confidence, image = predict_image(model, image_path, transform, device)
65
66 class_names = ['Alzheimer Hastası', 'Hafif Alzheimer Riski', 'Ortalama Alzheimer Riski', 'Çok Hafif Alzheimer Riski',
67 'Risk Yok', 'Parkinson Hastası']
68
69 print(f'Tahmin edilen sınıf: {class_names[predicted_class]}')
70 print(f'Doğruluk: {confidence}%')
71 total_params = sum(p.numel() for p in model.parameters())
72 print(f'Parametre sayısı: {total_params}')
73
74 plt.imshow(image.squeeze(0).permute(1, 2, 0))
75 plt.title(f'Tahmin: {class_names[predicted_class]} \nDoğruluk: {confidence:.2f}%')
76 plt.axis('off')
77 plt.show()
78
79
80if __name__ == '__main__':
81 main()1import torch
2import torch.nn as nn
3from torchvision import transforms
4from PIL import Image
5import matplotlib.pyplot as plt
6import os
7
8
9class SimpleCNN(nn.Module):
10 def __init__(self, num_classes=6):
11 super(SimpleCNN, self).__init__()
12 self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
13 self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
14 self.conv3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
15 self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
16 self.fc1 = nn.Linear(128 * 28 * 28, 512)
17 self.fc2 = nn.Linear(512, num_classes)
18 self.relu = nn.ReLU()
19 self.dropout = nn.Dropout(0.5)
20
21 def forward(self, x):
22 x = self.pool(self.relu(self.conv1(x)))
23 x = self.pool(self.relu(self.conv2(x)))
24 x = self.pool(self.relu(self.conv3(x)))
25 x = x.view(-1, 128 * 28 * 28)
26 x = self.relu(self.fc1(x))
27 x = self.dropout(x)
28 x = self.fc2(x)
29 return x
30
31
32def predict_image(model, image_path, transform, device):
33 image = Image.open(image_path).convert('RGB')
34 image = transform(image)
35 image = image.unsqueeze(0)
36
37 model.eval()
38
39 with torch.no_grad():
40 image = image.to(device)
41 outputs = model(image)
42 _, predicted = torch.max(outputs, 1)
43 probabilities = torch.nn.functional.softmax(outputs, dim=1)
44 confidence = probabilities[0, predicted].item() * 100
45
46 return predicted.item(), confidence, image
47
48
49def main():
50 transform = transforms.Compose([
51 transforms.Resize((224, 224)),
52 transforms.ToTensor(),
53 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
54 ])
55
56 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
57 model = SimpleCNN(num_classes=6).to(device)
58 model.load_state_dict(
59 torch.load('Vbai-DPA 2.0/model/path',
60 map_location=device))
61
62 image_path = 'test/image/path'
63
64 predicted_class, confidence, image = predict_image(model, image_path, transform, device)
65
66 class_names = ['Alzheimer Disease', 'Mild Alzheimer Risk', 'Moderate Alzheimer Risk', 'Very Mild Alzheimer Risk',
67 'No Risk', 'Parkinson Disease']
68
69 print(f'Predicted Class: {class_names[predicted_class]}')
70 print(f'Accuracy: {confidence}%')
71 total_params = sum(p.numel() for p in model.parameters())
72 print(f'Params: {total_params}')
73
74 plt.imshow(image.squeeze(0).permute(1, 2, 0))
75 plt.title(f'Prediction: {class_names[predicted_class]} \nAccuracy: {confidence:.2f}%')
76 plt.axis('off')
77 plt.show()
78
79
80if __name__ == '__main__':
81 main()