Image Classification
torch
DanielCruz09 commited on
Commit
ceb2293
·
1 Parent(s): 5abcc9e

Added source code for the model

Browse files
Files changed (2) hide show
  1. README.md +8 -0
  2. resnet50.py +113 -0
README.md CHANGED
@@ -1,3 +1,11 @@
1
  ---
2
  license: openmdw-1.0
3
  ---
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: openmdw-1.0
3
  ---
4
+
5
+ # Natural Disaster Image Classifier
6
+
7
+ A PyTorch CNN that can classify images into the following categories:
8
+ - Fire
9
+ - Flood
10
+ - Earthquake
11
+ - Non-Damage
resnet50.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ import torchvision.models as models
5
+ import numpy as np
6
+ from PIL import Image
7
+ import torchvision.transforms as transforms
8
+ import os
9
+ import pandas as pd
10
+
11
+
12
+ def create_indices(labels):
13
+ mapping = {
14
+ "Non_Damage": 0,
15
+ "Land_Disaster": 1,
16
+ "Fire_Disaster": 2,
17
+ "Water_Disaster": 3
18
+ }
19
+
20
+ indices = list(mapping[category] for category in labels)
21
+ return indices
22
+
23
+ def write_to_csv(predicted, actual, probs, write_path, header):
24
+
25
+ label_names = ["Non-Damage", "Earthquake", "Fire", "Flood"]
26
+
27
+ if header:
28
+ with open(write_path, "w") as file:
29
+ file.write("Predicted,True,Non_Damage_Score,Earthquake_Score,Fire_Score,Flood_Score\n")
30
+
31
+ with open(write_path, "a") as file:
32
+ for i in range(len(actual)):
33
+ file.write(
34
+ f"{label_names[actual[i].item()]},"
35
+ f"{label_names[predicted[i].item()]},"
36
+ f"{probs[i, 0].item()},"
37
+ f"{probs[i, 1].item()},"
38
+ f"{probs[i, 2].item()},"
39
+ f"{probs[i, 3].item()}\n"
40
+ )
41
+
42
+
43
+ class ResNet50():
44
+
45
+ def __init__(self, num_classes, lr=0.01, momentum=0.9):
46
+ self.model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
47
+ self.num_classes = num_classes
48
+ self.lr = lr
49
+ self.momentum = momentum
50
+ self.num_features = self.model.fc.in_features
51
+ self.model.fc = nn.Linear(self.num_features, self.num_classes)
52
+
53
+ self.criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
54
+ self.optimizer = optim.SGD(self.model.parameters(), lr=self.lr, momentum=self.momentum)
55
+
56
+ def train(self, epochs, train_loader):
57
+ loss_over_time = []
58
+ num_epochs = list(range(1, epochs + 1))
59
+ for epoch in range(epochs):
60
+ self.model.train()
61
+ current_loss = 0.0
62
+ for i, data in enumerate(train_loader, 0):
63
+ inputs, labels = data
64
+ self.optimizer.zero_grad()
65
+ outputs = self.model(data[inputs].float())
66
+ indices = create_indices(data[labels])
67
+ target = torch.tensor(indices)
68
+ loss = self.criterion(outputs, target)
69
+ loss.backward()
70
+ self.optimizer.step()
71
+ current_loss += loss.item()
72
+ loss_over_time.append(current_loss / len(train_loader))
73
+ print(f"Epoch: {epoch + 1} \t Loss: {current_loss / len(train_loader)}")
74
+
75
+ torch.save({
76
+ "model_state_dict": self.model.state_dict(),
77
+ "optimizer_state_dict": self.optimizer.state_dict(),
78
+ "epochs": num_epochs,
79
+ "loss": loss_over_time
80
+ }, "model_weights.pth")
81
+
82
+ data = {
83
+ "Epochs": num_epochs,
84
+ "Loss": loss_over_time
85
+ }
86
+ data = pd.DataFrame(data=data)
87
+ data.to_csv("results/model_progress.csv", index=False)
88
+
89
+ def eval(self, test_loader, write_path=None):
90
+ self.model.eval()
91
+ header = True
92
+
93
+ with torch.no_grad():
94
+ correct = 0
95
+ total = 0
96
+ for data in test_loader:
97
+ images, labels = data
98
+ images = data[images].float()
99
+ labels = data[labels]
100
+ indices = create_indices(labels)
101
+ labels = torch.tensor(indices)
102
+
103
+ outputs = self.model(images)
104
+ _, predicted = torch.max(outputs.data, 1)
105
+ probs = torch.softmax(outputs, dim=1)
106
+
107
+ total += len(labels)
108
+ correct += (predicted == labels).sum().item()
109
+ if write_path:
110
+ write_to_csv(predicted, labels, probs, write_path=write_path, header=header)
111
+ header = False
112
+
113
+ print(f'Accuracy of the network on the test images: {round(100 * correct / total, 3)}%')