联邦学习

联邦学习概念理解

联邦学习基础

####PHE加密

1
2
3
4
5
6
7
from phe import paillier
public_key, private_key = paillier.generate_paillier_keypair() #创建公钥和私钥
secret_number_list = [3.141592653, 300, -4.6e-12]
encrypted_number_list = [public_key.encrypt(x) for x in secret_number_list] #加密
[private_key.decrypt(x) for x in encrypted_number_list] #使用私钥解密
a, b, c = encrypted_number_list
a_plus_5 =a + 5

案例

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
import math

import numpy as np

fromphe import paillier

import pandas as pd

from sklearn import datasets

from sklearn.datasets import load_diabetes

from sklearn.preprocessing import StandardScaler

from sklearn.datasets import load_breast_cancer

from sklearn.model_selection import train_test_split

from sklearn.utils import shuffle

class Client:
def __init__(self, config):

## 模型参数

self.config = config

## 中间计算结果

self.data = {}

## 与其他节点的连接状况

self.other_client = {}

## 与其他参与方建立连接

def connect(self, client_name, target_client):

self.other_client[client_name] = target_client

## 向特定参与方发送数据

def send_data(self, data, target_client):

target_client.data.update(data)

class ClientA(Client):
def __init__(self, X, config):

super().__init__(config)

self.X = X

self.weights = np.zeros(X.shape[1])

def compute_z_a(self):
z_a = np.dot(self.X, self.weights)
return z_a

def compute_encrypted_dJ_a(self, encrypted_u):
return encrypted_dJ_a

def update_weight(self, dJ_a):
self.weights = self.weights - self.config["lr"] *dJ_a / len(self.X)
return

## A: step2

def task_1(self, client_B_name):
dt = self.data
public_key = dt['public_key']

z_a = self.compute_z_a()

u_a = 0.25 * z_a

z_a_square =z_a ** 2

encrypted_u_a = np.asarray([public_key.encrypt(x) forx in u_a])

encrypted_z_a_square = np.asarray([public_key.encrypt(x) forx in z_a_square])
dt.update({"encrypted_u_a": encrypted_u_a})
data_to_B = {"encrypted_u_a": encrypted_u_a, "encrypted_z_a_square": encrypted_z_a_square}
self.send_data(data_to_B, self.other_client[client_B_name])

def task_2(self, client_C_name):
dt = self.data
encrypted_u_b = dt['encrypted_u_b']

encrypted_u =encrypted_u_b + dt['encrypted_u_a']

encrypted_dJ_a = self.compute_encrypted_dJ_a(encrypted_u)

mask = np.random.rand(len(encrypted_dJ_a))

encrypted_masked_dJ_a =encrypted_dJ_a + mask
dt.update({"mask": mask})
data_to_C = {'encrypted_masked_dJ_a': encrypted_masked_dJ_a}

self.send_data(data_to_C, self.other_client[client_C_name])
def task_3(self):
dt = self.data