Skip to content

Instantly share code, notes, and snippets.

View phil8192's full-sized avatar
🦇

Phil Stubbings phil8192

🦇
View GitHub Profile
@phil8192
phil8192 / mm_rot.R
Last active March 15, 2021 17:15
matrix multiplication with rotations
# 4 elem vector
w <- c(10, 20, 30, 40)
# 4*3 matrix
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
# [3,] 7 8 9
# [4,] 10 11 12
x <- matrix(1:12, ncol=3, byrow=T)
##' calculate summary statistics from a confusion matrix.
##'
##' @param cm a confusion matrix, where rows = predicted, cols = actual.
##' @param dp round decimal place (default 2).
##' @return a classification report, similar to sklean.
##' @examples
##' \dontrun{
##' # 3 classes.
##' cm <- matrix(c(4, 6, 3, 1, 2, 0, 1, 2, 6), ncol=3, byrow=T)
##' cr(cm)
epochs = 10
times = []
for k in [None, 256, 512, 1024, 2048]:
pub_key, pri_key = paillier.generate_paillier_keypair(n_length=k) \
if k is not None else (None, None)
b = B(B_x, pub_key)
a = A(A_x, yy, b, pub_key)
class C:
def __init__(self, a, test_x, test_y, pri_key=None):
self.a = a # regerence to Host A.
self.test_x = test_x
self.test_y = test_y
self.features = test_x.shape[1]
self.pri_key = pri_key
def optimise(self, epochs, batch_size, eta, gamma):
class B:
def __init__(self, x, pub_key=None):
self.x = x # Host B's X.
self.features = x.shape[1]
self.pub_key = pub_key
# Called by Host (A) with current model Theta and A's
# (encypted) part of the gradient calculation.
def gradients(self, theta, u):
class A:
def __init__(self, x, y, b, pub_key=None):
self.x = x # A's vertical partition of X.
self.y = y # A's training labels.
self.b = b # reference to Host B.
self.features = x.shape[1]
self.pub_key = pub_key
# Called by Coordinator with current model Theta for each mini-batch
# returns (encrypted) gradients for Host A, Host B.
def taylor_gradient(theta, x, y):
return 1/x.shape[0] * np.dot(0.25 * np.dot(x, theta) - 0.5 * y, x)
def taylor_loss(theta, x, y):
wx = np.dot(x, theta)
return 1/x.shape[0] * np.sum(np.log(2) - 0.5 * y * wx + 0.125 * wx**2)
import phe as paillier
def encrypt(pub_key, x):
"""encrypt a vector with pub_key"""
return np.array([pub_key.encrypt(v) for v in x.tolist()])
def decrypt(pri_key, x):
"""decypt a vector with pri_key"""
return np.array([pri_key.decrypt(v) for v in x])
class FedAvg(BaseEstimator, ClassifierMixin):
def __init__(self,
n_runners=1,
sample_size=1,
rounds=1,
combine='weighted',
partition_params={
'scheme': 'uniform'
},