-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutils.py
154 lines (133 loc) · 5.82 KB
/
utils.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
147
148
149
150
151
import torch
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from matplotlib.cbook import boxplot_stats
from datasets import *
from aggregation import *
eps = np.finfo(float).eps
def gaussian_attack(update, peer_pseudonym, malicious_behavior_rate = 0,
device = 'cpu', attack = False, mean = 0.0, std = 0.5):
flag = 0
for key in update.keys():
r = np.random.random()
if r <= malicious_behavior_rate:
# print('Gausiian noise attack launched by ', peer_pseudonym, ' targeting ', key, i+1)
noise = torch.cuda.FloatTensor(update[key].shape).normal_(mean=mean, std=std)
flag = 1
update[key]+= noise
return update, flag
def contains_class(dataset, source_class):
for i in range(len(dataset)):
x, y = dataset[i]
if y == source_class:
return True
return False
# Prepare the dataset for label flipping attack from a target class to another class
def label_filp(data, source_class, target_class):
poisoned_data = PoisonedDataset(data, source_class, target_class)
return poisoned_data
def flatten_updates(updates):
f = torch.nn.utils.parameters_to_vector
updates_ = [f(update.parameters()).view(-1).cpu().data.numpy() for update in updates]
return updates_
def get_last(updates):
data = []
for u in updates:
l = list(u.parameters())[-2].view(-1).cpu().data.numpy()
data.append(l)
return data
def get_last_classes(updates, classes):
data = []
for u in updates:
l = list(u.parameters())[-2].cpu().data.numpy()
data.append(l[classes].reshape(-1))
return data
#Plot the PCA of updates with their peers types. Types are: Honest peer or attacker
def plot_updates_components(updates, peers_types, epoch):
flattened_updates = flatten_updates(updates)
flattened_updates = StandardScaler().fit_transform(flattened_updates)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(flattened_updates)
principalDf = pd.DataFrame(data = principalComponents,
columns = ['c1', 'c2'])
peers_typesDf = pd.DataFrame(data = peers_types,
columns = ['target'])
finalDf = pd.concat([principalDf, peers_typesDf['target']], axis = 1)
fig = plt.figure(figsize = (7,7))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Component 1', fontsize = 10)
ax.set_ylabel('Component 2', fontsize = 10)
ax.set_title('2 component PCA', fontsize = 15)
targets = ['Good update', 'Bad update']
colors = ['white', 'black']
for target, color in zip(targets,colors):
indicesToKeep = finalDf['target'] == target
ax.scatter(finalDf.loc[indicesToKeep, 'c1'],
finalDf.loc[indicesToKeep, 'c2'],
c = color,
edgecolors='gray',
s = 80)
ax.legend(targets)
plt.savefig('pca\epoch{}.png'.format(epoch), dpi = 600)
# plt.show()
def plot_layer_components(updates, peers_types, epoch, layer = 'last_weight'):
# res = {'updates':updates, 'peers_types':peers_types}
# torch.save(res, 'results/epoch{}.t7'.format(epoch))
flattened_updates = get_last(updates)
flattened_updates = StandardScaler().fit_transform(flattened_updates)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(flattened_updates)
principalDf = pd.DataFrame(data = principalComponents,
columns = ['c1', 'c2'])
peers_typesDf = pd.DataFrame(data = peers_types,
columns = ['target'])
finalDf = pd.concat([principalDf, peers_typesDf['target']], axis = 1)
fig = plt.figure(figsize = (7,7))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Component 1', fontsize = 10)
ax.set_ylabel('Component 2', fontsize = 10)
ax.set_title('2 component PCA', fontsize = 15)
targets = ['Good update', 'Bad update']
colors = ['white', 'black']
for target, color in zip(targets,colors):
indicesToKeep = finalDf['target'] == target
ax.scatter(finalDf.loc[indicesToKeep, 'c1'],
finalDf.loc[indicesToKeep, 'c2'],
c = color,
edgecolors='gray',
s = 80)
ax.legend(targets)
plt.savefig('pca\epoch{}_layer_{}.png'.format(epoch, layer), dpi = 600)
plt.show()
def plot_source_target(updates, peers_types, epoch, classes):
# res = {'updates':updates, 'peers_types':peers_types}
# torch.save(res, 'results/epoch{}.t7'.format(epoch))
flattened_updates = get_last_classes(updates, classes)
flattened_updates = StandardScaler().fit_transform(flattened_updates)
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(flattened_updates)
principalDf = pd.DataFrame(data = principalComponents,
columns = ['c1', 'c2'])
peers_typesDf = pd.DataFrame(data = peers_types,
columns = ['target'])
finalDf = pd.concat([principalDf, peers_typesDf['target']], axis = 1)
fig = plt.figure(figsize = (7,7))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Component 1', fontsize = 10)
ax.set_ylabel('Component 2', fontsize = 10)
ax.set_title('2 component PCA', fontsize = 15)
targets = ['Good update', 'Bad update']
colors = ['white', 'black']
for target, color in zip(targets,colors):
indicesToKeep = finalDf['target'] == target
ax.scatter(finalDf.loc[indicesToKeep, 'c1'],
finalDf.loc[indicesToKeep, 'c2'],
c = color,
edgecolors='gray',
s = 80)
ax.legend(targets)
plt.savefig('pca\epoch{}_srctarget.png'.format(epoch), dpi = 600)
plt.show()