-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathutils2.py
146 lines (112 loc) · 4.15 KB
/
utils2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""
Utility functions and classes for Jupyter Notebooks lessons.
"""
from collections import OrderedDict
from typing import List, Tuple, Dict, Optional
from flwr.common import Metrics, NDArrays, Scalar
import torch
import torch.nn as nn
from torch.utils.data import Subset, DataLoader, random_split
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns
import numpy as np
import logging
from flwr.common.logger import console_handler, log
from logging import INFO, ERROR
class InfoFilter(logging.Filter):
def filter(self, record):
return record.levelno == INFO
console_handler.setLevel(INFO)
console_handler.addFilter(InfoFilter())
transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]
)
# To filter logging coming from the Simulation Engine
# so it's more readable in notebooks
from logging import ERROR
backend_setup = {"init_args": {"logging_level": ERROR, "log_to_driver": False}}
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.out = nn.Linear(128, 10)
def forward(self, x):
x = torch.flatten(x, 1)
x = self.fc(x)
x = self.relu(x)
x = self.out(x)
return x
def train_model(model, train_set):
batch_size = 64
num_epochs = 10
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
model.train()
for epoch in range(num_epochs):
running_loss = 0.0
for inputs, labels in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
def evaluate_model(model, test_set):
model.eval()
correct = 0
total = 0
total_loss = 0
test_loader = DataLoader(test_set, batch_size=64, shuffle=False)
criterion = nn.CrossEntropyLoss()
with torch.no_grad():
for inputs, labels in test_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
loss = criterion(outputs, labels)
total_loss += loss.item()
accuracy = correct / total
average_loss = total_loss / len(test_loader)
# print(f"Test Accuracy: {accuracy:.4f}, Average Loss: {average_loss:.4f}")
return average_loss, accuracy
def include_digits(dataset, included_digits):
including_indices = [
idx for idx in range(len(dataset)) if dataset[idx][1] in included_digits
]
return torch.utils.data.Subset(dataset, including_indices)
def exclude_digits(dataset, excluded_digits):
including_indices = [
idx for idx in range(len(dataset)) if dataset[idx][1] not in excluded_digits
]
return torch.utils.data.Subset(dataset, including_indices)
def compute_confusion_matrix(model, testset):
# Initialize lists to store true labels and predicted labels
true_labels = []
predicted_labels = []
# Iterate over the test set to get predictions
for image, label in testset:
# Forward pass through the model to get predictions
output = model(image.unsqueeze(0)) # Add batch dimension
_, predicted = torch.max(output, 1)
# Append true and predicted labels to lists
true_labels.append(label)
predicted_labels.append(predicted.item())
# Convert lists to numpy arrays
true_labels = np.array(true_labels)
predicted_labels = np.array(predicted_labels)
# Compute confusion matrix
cm = confusion_matrix(true_labels, predicted_labels)
return cm
def plot_confusion_matrix(cm, title):
plt.figure(figsize=(6, 4))
sns.heatmap(cm, annot=True, cmap="Blues", fmt="d", linewidths=0.5)
plt.title(title)
plt.xlabel("Predicted Label")
plt.ylabel("True Label")
plt.show()