-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpruned_federated_eval_radio_sig_identification.py
More file actions
128 lines (103 loc) · 4.88 KB
/
pruned_federated_eval_radio_sig_identification.py
File metadata and controls
128 lines (103 loc) · 4.88 KB
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
from tqdm import tqdm
from torch.utils.data import DataLoader
from dataset_classes.radio_sig import RadioSignal
import torch
import models_vit
import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import confusion_matrix
import random
from pathlib import Path
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.family'] = 'serif'
import torch.nn.functional as F
import timm
def forward(self, x):
"""https://github.com/huggingface/pytorch-image-models/blob/054c763fcaa7d241564439ae05fbe919ed85e614/timm/models/vision_transformer.py#L79"""
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv.unbind(0)
q, k = self.q_norm(q), self.k_norm(k)
if self.fused_attn:
x = F.scaled_dot_product_attention(
q, k, v,
dropout_p=self.attn_drop.p,
)
else:
q = q * self.scale
attn = q @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = attn @ v
x = x.transpose(1, 2).reshape(B, N, -1) # original implementation: x = x.transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
seed = 42
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
# dataset = RadioSignal(Path('../datasets/radio_sig_identification'))
dataset_train = RadioSignal(Path('fine-tuning_datasets/radio_sig_identification/train'))
dataset_test = RadioSignal(Path('fine-tuning_datasets/radio_sig_identification/test'))
# splitter = StratifiedShuffleSplit(n_splits=1, train_size=0.8, test_size=0.2, random_state=seed)
# all_labels = [dataset[i][1] for i in range(len(dataset))]
#
# for train_idx, test_idx in splitter.split(range(len(dataset)), all_labels):
# dataset_train = torch.utils.data.Subset(dataset, train_idx)
# dataset_test = torch.utils.data.Subset(dataset, test_idx)
dataloader_train = DataLoader(dataset_train, batch_size=256, shuffle=True, num_workers=0)
dataloader_test = DataLoader(dataset_test, batch_size=256, shuffle=False, num_workers=0)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = models_vit.__dict__['vit_small_patch16'](global_pool='token', num_classes=10, drop_path_rate=0.1, in_chans=1, head_layers=1)
# print(model)
# checkpoint = torch.load(Path('/home/ict317-3/Mohammad/mae/output_dir/checkpoint-190.pth'), map_location='cpu', weights_only=False)
# msg = model.load_state_dict(checkpoint['model'], strict=True)
# print(msg)
model = torch.load('/home/ict317-3/Mohammad/mae/sig_id_output_dir/fed_avg_model.pth', weights_only=False)
print(model)
for m in model.modules():
if isinstance(m, timm.models.vision_transformer.Attention):
m.forward = forward.__get__(m, timm.models.vision_transformer.Attention)
model = model.to(device)
model.eval()
class_names = ['ais', 'bluetooth', 'cellular', 'fm', 'lora','packet', 'rke', 'RS41-Radiosonde', 'sstv', 'wifi']
all_labels_train = []
all_preds_train = []
with torch.no_grad():
for samples, targets in tqdm(dataloader_train, desc='Train batch'):
samples, targets = samples.to(device), targets.to(device)
output = model(samples)
all_preds_train.extend(output.argmax(dim=-1).cpu().numpy())
all_labels_train.extend(targets.cpu().numpy())
all_labels_test = []
all_preds_test = []
with torch.no_grad():
for samples, targets in tqdm(dataloader_test, desc='Test batch'):
samples, targets = samples.to(device), targets.to(device)
output = model(samples)
all_preds_test.extend(output.argmax(dim=-1).cpu().numpy())
all_labels_test.extend(targets.cpu().numpy())
conf_mat_train = confusion_matrix(all_labels_train, all_preds_train)
conf_mat_test = confusion_matrix(all_labels_test, all_preds_test)
conf_mat_train = conf_mat_train.astype(np.float32)
conf_mat_test = conf_mat_test.astype(np.float32)
for i in range(len(class_names)):
conf_mat_train[i] /= np.sum(conf_mat_train[i])
conf_mat_test[i] /= np.sum(conf_mat_test[i])
accuracy_train = np.mean(np.diagonal(conf_mat_train))
accuracy_test = np.mean(np.diagonal(conf_mat_test))
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
fig.suptitle('Finetuning frozen ViT-S + 2 Layer Head')
sns.heatmap(conf_mat_train, cmap='Reds', yticklabels=class_names, ax=axs[0])
sns.heatmap(conf_mat_test, cmap='Reds', yticklabels=class_names, ax=axs[1])
axs[0].tick_params(axis='y', labelsize=10)
axs[1].tick_params(axis='y', labelsize=10)
axs[0].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
axs[1].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
axs[0].set_title(f'Train - Accuracy: {accuracy_train:.2f}')
axs[1].set_title(f'Test - Accuracy: {accuracy_test:.2f}')
plt.tight_layout()
plt.savefig('/home/ict317-3/Mohammad/mae/sig_id_output_dir/conf_mat_radio_identification.png', dpi=400)
plt.show()