markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
2. Logistic regression objective function Recall from lectures, that logistic regression models the distribution of the binary class $y$ *conditional* on the feature vector $\mathbf{x}$ as$$y | \mathbf{x} \sim \mathrm{Bernoulli}[\sigma(\mathbf{w}^T \mathbf{x} + b)]$$where $\mathbf{w}$ is the weight vector, $b$ is the ... | from scipy.special import expit # this is the logistic function
# v: parameter vector
# X: feature matrix
# Y: class labels
# Lambda: regularisation constant
def obj_fn(v, X, Y, Lambda):
prob_1 = expit(np.dot(X,v[1::]) + v[0])
reg_term = 0.5 * Lambda * np.dot(v[1::],v[1::]) # fill in
cross_entropy_term = -... | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
Now for the gradient, we use the following result (if you're familiar with vector calculus, you may wish to derive this yourself):$$\nabla_{\mathbf{v}} f(\mathbf{v}; \ldots) = \left[\frac{\partial f(\mathbf{w}, b;\ldots)}{\partial b}, \nabla_{\mathbf{w}} f(\mathbf{w}, b; \ldots) \right] = \left[\sum_{i = 1}^{n} \sigma(... | # v: parameter vector
# X: feature matrix
# Y: class labels
# Lambda: regularisation constant
def grad_obj_fn(v, X, Y, Lambda):
prob_1 = expit(np.dot(X, v[1::]) + v[0])
grad_b = np.sum(prob_1 - Y)
grad_w = Lambda * v[1::] + np.dot(prob_1 - Y, X)
return np.insert(grad_w, 0, grad_b) | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
3. Solving the minimization problem using BFGS Now that we've implemented functions to compute the objective and the gradient, we can plug them into `fmin_bfgs`.Specifically, we define a function `my_logistic_regression` which calls `fmin_bfgs` and returns the optimal weight vector. | from scipy.optimize import fmin_bfgs
# X: feature matrix
# Y: class labels
# Lambda: regularisation constant
# v_initial: initial guess for parameter vector
def my_logistic_regression(X, Y, Lambda, v_initial, disp=True):
# Function for displaying progress
def display(v):
print('v is', v, 'objective is'... | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
Let's try it out! | Lambda = 1
v_initial = np.zeros(X_train.shape[1] + 1) # fill in a vector of zeros of appropriate length
v_opt = my_logistic_regression(X_train, Y_train, Lambda, v_initial)
# Function to plot the data points and decision boundary
def plot_results(X, Y, v, trans_func = None):
# Scatter plot in feature space
plt.... | v is [-0.12895873 -0.08185978 0.02005271] objective is 138.80620162265674
v is [-0.10559965 -0.16360542 0.05028661] objective is 138.71483494120764
v is [-0.10594786 -0.16265682 0.0537028 ] objective is 138.71470747506936
v is [-0.10744929 -0.16393098 0.05382675] objective is 138.71452420357136
v is [-0.10855209 -0... | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
**Question:** Is the solution what you expected? Is it a good fit for the data?**Answer:** *It's not a good fit because logistic regression is a linear classifier, and the data is not linearly seperable.***Question:** What's the accuracy of this model? Fill in the code below assuming the following decision function$$\h... | from sklearn.metrics import accuracy_score
Y_test_pred = ((np.dot(X_test, v_opt[1::]) + v_opt[0]) >= 0)*1 # fill in
accuracy_score(Y_test, Y_test_pred) | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
4. Adding polynomial features We've seen that ordinary logistic regression does poorly on this data set, because the data is not linearly separable in the $x_0,x_1$ feature space.We can get around this problem using basis expansion. In this case, we'll augment the feature space by adding polynomial features of degree ... | # X: original feature matrix
def add_quadratic_features(X):
return np.c_[X, X[:,0]**2, X[:,0]*X[:,1], X[:,1]**2]
Phi_train = add_quadratic_features(X_train)
Phi_test = add_quadratic_features(X_test) | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
Let's apply our custom logistic regression function again on the augmented feature space. | Lambda = 1
v_initial = np.zeros(Phi_train.shape[1] + 1) # fill in a vector of zeros of appropriate length
v_opt = my_logistic_regression(Phi_train, Y_train, Lambda, v_initial)
plot_results(X, Y, v_opt, trans_func=add_quadratic_features) | v is [-0.25330176 -0.16078962 0.0393877 -0.69061891 -0.06191788 -0.66913767] objective is 133.7254597353608
v is [ 0.14454987 -0.26356343 0.09103964 -1.12285189 -0.11645183 -1.10119619] objective is 123.21507652891698
v is [ 0.93565182 0.58998862 -0.16877892 -2.03937966 -0.1485882 -2.11948612] objective is 111.069... | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
This time we should get a better result for the accuracy on the test set. | from sklearn.metrics import accuracy_score
Y_test_pred = ((np.dot(Phi_test, v_opt[1::]) + v_opt[0]) >= 0)*1 # fill in
accuracy_score(Y_test, Y_test_pred) | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
5. Effect of regularisation So far, we've fixed the regularisation constant so that $\lambda = 1$. (Note it's possible to choose an "optimal" value for $\lambda$ by applying cross-validation.)**Question:** What do you think will happen if we switch the regularisation off? Try setting $\lambda$ to a small value (say $1... | from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(C=1)
clf.fit(Phi_train, Y_train)
from sklearn.metrics import accuracy_score
Y_test_pred = clf.predict(Phi_test)
accuracy_score(Y_test, Y_test_pred) | _____no_output_____ | MIT | Statistical_Machine_Learning/workshop/.ipynb_checkpoints/worksheet03_solutions-checkpoint.ipynb | infinityglow/Unimelb-CS-Subjects |
Does nn.Conv2d init work well? [Jump_to lesson 9 video](https://course.fast.ai/videos/?lesson=9&t=21) | #export
from exp.nb_02 import *
def get_data():
path = datasets.download_data(MNIST_URL, ext='.gz')
with gzip.open(path, 'rb') as f:
((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')
return map(tensor, (x_train,y_train,x_valid,y_valid))
def normalize(x, m, s): return... | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
```def reset_parameters(self): init.kaiming_uniform_(self.weight, a=math.sqrt(5)) why 5??? if self.bias is not None: fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight) bound = 1 / math.sqrt(fan_in) init.uniform_(self.bias, -bound, bound)``` Let's try to test that with MNIST, observi... | # Load data
x_train,y_train,x_valid,y_valid = get_data()
train_mean,train_std = x_train.mean(),x_train.std()
x_train = normalize(x_train, train_mean, train_std)
x_valid = normalize(x_valid, train_mean, train_std)
# Reshape
x_train = x_train.view(-1,1,28,28)
x_valid = x_valid.view(-1,1,28,28)
x_train.shape,x_valid.shape... | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
The parameters are: channels in (1 because is b&w), channels out (number of "hidden layer neurons") and kernel size.We take 100 samples from the original input: | x = x_valid[:100]
x.shape | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Write a function for a repetitive task like obtaining the stats ;) | def stats(x):
return x.mean(),x.std() | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
We can access to `l1.weight` and to `l1.bias` | l1.weight.shape, l1.bias.shape | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
The weights tensor dimensions: 32 output filters, 1 input filter (because we only have 1 channel), and 5x5 because of the filter/kernel size.The initialization of Conv2d gives us these stats: | stats(l1.weight),stats(l1.bias) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Pass our input through the conv layer... | t = l1(x)
stats(t) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
The std dev is far from the expected 1 value. This looks like a problem.Comparing to the regular kaiming normal (remember it's designed to be used followed by a ReLU layer, or more generally by a Leaky ReLU layer, where `a` is the slope of the negative part): | init.kaiming_normal_(l1.weight, a=1.)
stats(l1(x)) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Let's test our conv layer followed by a Leaky ReLU layer... | import torch.nn.functional as F
def f1(x,a=0):
return F.leaky_relu(l1(x),a) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
With a=0 (ReLU) the mean raises to 0.5 aprox, but std dev remains near to 1... | init.kaiming_normal_(l1.weight, a=0)
stats(f1(x)) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Compared to the default with a=5: | l1 = nn.Conv2d(1, nh, 5)
stats(f1(x)) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Let's write our own kaiming normalization function :) | l1.weight.shape
# receptive field size (number of kernel elements)
rec_fs = l1.weight[0,0].numel()
rec_fs
nf,ni,*_ = l1.weight.shape
nf,ni
# Effective fan in and fan out of the convolutional layer
fan_in = ni*rec_fs
fan_out = nf*rec_fs
fan_in,fan_out | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
The gain for the normalization, having `a` into account: | def gain(a):
return math.sqrt(2.0 / (1 + a**2))
gain(1),gain(0),gain(0.01),gain(0.1),gain(math.sqrt(5.)) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
The last value is the one corresponding to the PyTorch's `a` init value.Remember that PyTorch uses kaiming_uniform instead of kaiming_normal, and the std dev of an uniform distribution is not 1: | torch.zeros(10000).uniform_(-1,1).std()
1/math.sqrt(3.) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Our complete kaiming function, with the compensated gain: | def kaiming2(x,a, use_fan_out=False):
nf,ni,*_ = x.shape
rec_fs = x[0,0].shape.numel()
fan = nf*rec_fs if use_fan_out else ni*rec_fs
std = gain(a) / math.sqrt(fan)
bound = math.sqrt(3.) * std
x.data.uniform_(-bound,bound)
kaiming2(l1.weight, a=0);
stats(f1(x))
kaiming2(l1.weight, a=math.sqrt(5.)... | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
That std dev is very low, and we have a problem, because the variance is really small in the last layer. | l = mse(t,y)
l.backward()
stats(m[0].weight.grad) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Let's return to `kaiming_uniform`, and apply that to the previous network: | init.kaiming_uniform_??
for l in m:
if isinstance(l,nn.Conv2d):
init.kaiming_uniform_(l.weight)
l.bias.data.zero_()
t = m(x)
stats(t)
l = mse(t,y)
l.backward()
stats(m[0].weight.grad) | _____no_output_____ | Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
It's better than the default Conv2d.PyTorch team said it was a bug (not multiplying by math.sqrt(3.)) but it empirically worked really well :S Export | !python notebook2script.py 02a_why_sqrt5.ipynb | Converted 02a_why_sqrt5.ipynb to exp\nb_02a.py
| Apache-2.0 | nbs/dl2/02a_why_sqrt5.ipynb | pyjaime/fastai-dl-course-2019 |
Wordplay in Column Names============================== | import matplotlib.pyplot as plt
import networkx as nx
G=nx.Graph()
col = [c for c in train.columns if c not in ['id', 'target']]
G.add_node('Start')
for i in range(4):
G.add_node('Column Section '+ str(i))
G.add_edge('Start','Column Section '+ str(i))
for c in train[col].columns:
if c.split('-')[i... | _____no_output_____ | MIT | 5 instant gratification/cognitive-conditioning.ipynb | MLVPRASAD/KaggleProjects |
How unique are the column values========== | df = []
for c in train.columns:
if c not in ['target', 'id', 'wheezy-copper-turtle-magic']:
l1 = test[c].unique()
l2 = train[c].unique()
df.append([c, len(l1), len(l2), len(l1)- 131073, len(l2) - 262144])
df = pd.DataFrame(df, columns=['col', 'test_unique', 'train_unique', 'test_diff', 'trai... | 128997 129262
253919 255057
-2076 -1811
-8225 -7087
| MIT | 5 instant gratification/cognitive-conditioning.ipynb | MLVPRASAD/KaggleProjects |
Getting wheezy===== | col = [c for c in train.columns if c not in ['id', 'target', 'wheezy-copper-turtle-magic']]
df_all = pd.concat((train,test), axis=0, ignore_index=True).reset_index(drop=True)
df_all['wheezy-copper-turtle-magic'] = df_all['wheezy-copper-turtle-magic'].astype('category')
train = df_all[:train.shape[0]].reset_index(drop... | _____no_output_____ | MIT | 5 instant gratification/cognitive-conditioning.ipynb | MLVPRASAD/KaggleProjects |
Lets Race====== | test_ = []
kn = neighbors.KNeighborsClassifier(n_neighbors=17, p=2.9)
sv = svm.NuSVC(kernel='poly', degree=4, random_state=4, probability=True, coef0=0.08)
for s in sorted(train['wheezy-copper-turtle-magic'].unique()):
train2 = train[train['wheezy-copper-turtle-magic']==s].reset_index(drop=True).copy()
test2 ... | _____no_output_____ | MIT | 5 instant gratification/cognitive-conditioning.ipynb | MLVPRASAD/KaggleProjects |
Accessing the TriggerIn ATLAS all access to event trigger decision is via the Trigger Decision Tool (TDT). There is quite a bit of information attached to the trigger, and its layout is quite complex - for that reason one should use the TDT to access the data. It is not really possible for a human to navigate the data... | import matplotlib.pyplot as plt
from config import ds_zee as ds
from func_adl_servicex_xaodr21 import tdt_chain_fired, tmt_match_object | _____no_output_____ | MIT | book/chapters/trigger.ipynb | gordonwatts/xaod_usage |
Looking for events that fired a chainLets look at $Z \rightarrow ee$ Monte Carlo for a single electron trigger in the event. | n_electrons = (ds.Select(lambda e:
{
"n_ele": e.Electrons().Where(lambda e: abs(e.eta()) < 2.5).Count(),
"fired": tdt_chain_fired("HLT_e60_lhmedium_nod0"),
})
.AsAwkwardArray()
... | _____no_output_____ | MIT | book/chapters/trigger.ipynb | gordonwatts/xaod_usage |
Trigger MatchingNext, let's find the electrons that matched that trigger that fired above. We'll do this by looking only at events where the trigger has fired, and then asking each electron if it matches withing a $\Delta R$. | matched_electrons = (
ds.Where(lambda e: tdt_chain_fired("HLT_e60_lhmedium_nod0"))
.SelectMany(lambda e: e.Electrons())
.Select(
lambda e: {
"pt": e.pt() / 1001.0,
"eta": e.eta(),
"is_trig": tmt_match_object("HLT_e60_lhmedium_nod0", e, 0.7),
}
)
.A... | _____no_output_____ | MIT | book/chapters/trigger.ipynb | gordonwatts/xaod_usage |
To know the `tnt_match_object` arguments, you'll need to look up its definition below on the atlas twiki. | plt.hist(matched_electrons.pt, bins=100, range=(0, 100), label='All Electrons')
trigger_electrons = matched_electrons[matched_electrons.is_trig]
plt.hist(trigger_electrons.pt, bins=100, range=(0, 100), label='Trigger Electrons')
plt.xlabel('Electron $p_T$ [GeV]')
plt.ylabel('Number of Electrons')
_ = plt.legend() | _____no_output_____ | MIT | book/chapters/trigger.ipynb | gordonwatts/xaod_usage |
Additive Secret SharingAuthor: - Carlos Salgado - [email](mailto:csalgado@uwo.ca) - [linkedin](https://www.linkedin.com/in/eng-socd/) - [github](https://github.com/socd06) Additive Secret SharingAdditive Secret Sharing is a mechanism to share data among parties and to perform computation on it. 
# Uncomment the line below to see a hint
# q0.hint
# Uncomment the line below to see the solution
# q0.solution | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
[Quiz] Find the final share s2Using a small `Q` to facilitate calculation (it needs to be a **very high prime number** in production), let $ s = 7, n = 2 $ with $ Q = 59 $ and $ s_1 = 9 $plugged in on the secret reconstruction equation, find the final share s2.Fill the ____ space below with your answer. Feel free to i... | # Fill the ____ space below with your answer
final_share =
# run to check your answer
q1.check(final_share)
# Uncomment the line below to see a hint
# q1.hint
# Uncomment the line below to see the solution
# q1.solution | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
In PracticeJust as an educational example, we can generate a list of prime numbers using [sympy](https://www.sympy.org/en/index.html) | # Verify we have all the tools we need to run the notebook
!pip install -r requirements.txt
import sympy
# An arbitrary constant, feel free to play with it
CONST = 999
BIT_DEPTH = 31
# Range start
start = 2**BIT_DEPTH-CONST
# Maximum in Z2**32 ring
end = 2**BIT_DEPTH
prime_lst = list(sympy.primerange(start,end+1)... | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
And **randomly** choose one every time using [NumPy](https://numpy.org/devdocs/contents.html)'s [randint](https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html) | from numpy.random import randint
Q = prime_lst[randint(len(prime_lst))]
Q | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
As an additional note, the [Secrets module](https://docs.python.org/3/library/secrets.html), introduced in Python 3.6, provides randomness as secure as your operating system. | import secrets
Q = secrets.choice(prime_lst)
Q | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
The Final Share and 2-party Additive Secret SharingKnowing that $ s_n = Q - (\; \sum \limits _{i=1} ^{n-1} s_i \; mod \; Q \; ) + s $How do we implement 2-party ($ n=2 $) additive secret sharing using Python? Keep reading and fing out! | def dual_share(s, r):
'''
s = secret
r = randomness
'''
share_lst = list()
share_lst.append(randint(0,r))
final_share = r - (share_lst[0] % r) + s
share_lst.append(final_share)
return share_lst
# Let's generate a couple of shares
secret = 5
dual_shares = dual... | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Now go back to the previous cell and **run it again**. Notice anything?......... See it yet? The shares are never the same because they are **randomly generated**.Now let's implement the reconstruction (or decryption) function. | def decrypt(shares, r):
'''
shares = iterable made of additive secret shares
r = randomness
'''
return sum(shares) % r
# And let's decrypt our secret for the first time
decrypt(dual_shares, Q) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Exercise: Implement n-party additive secret sharing Fill the function below with your code. | def n_share(s, r, n):
'''
s = secret
r = randomness
n = number of nodes, workers or participants
returns a tuple of n-shares
'''
# replace with your code
pass
five_shares = n_share(s=686,r=Q,n=5)
five_shares
# run this cell to check your solution
q2.check(decrypt(fi... | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
AdditionGiven two shared values $a$ and $b$, a party $P_i$ can compute the added shares as:$ c_i = ( a_i + b_i ) \; mod \; Q$In Python, we can implement this type of addition like this: | def addition(a, b, r):
'''
a = iterable of the same length of b
b = iterable of the same length of a
r = randomness AKA randomly generated very high prime number
'''
c = list()
for i in range(len(a)):
c.append((a[i] + b[i]) % r)
return tuple(c) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Considering Alice and Bob are our parties, with secrets $s_a$ and $s_b$ to be shared (2-way) and wanting to compute addition.Let $s_a = 5 $ and $s_b = 11 $Alice's shares would be something like: | # Alice's secret
sa = 5
alice_shares = dual_share(sa, Q)
alice_shares | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
While Bob's shares would be | # Bob's secret
sb = 11
bob_shares = dual_share(sb, Q)
bob_shares
secret_sum = addition(alice_shares, bob_shares, Q)
secret_sum | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Doesn't make a lot of sense, does it?Secret shares must only reveal information about their secrets when they are all combined. Otherwise all data must be hidden, which defines the **privacy** property. These are still secret shares so there is one more step to get the sum of the original secrets. | decrypt(secret_sum, Q) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Et Voilà! Public (scalar) MultiplicationGiven a list of shared values $a$ and a **scalar** $b$, a party $P_i$ can compute the multiplied shares as:$ c_i = a_i \times b \; mod \; Q$In Python, we can implement this type of multiplication like this: | def public_mul(a, b, r):
'''
a = iterable of the same length of b
b = scalar to multiply a by
r = randomness AKA randomly generated very high prime number
'''
c = list()
for i in range(len(a)):
c.append((a[i] * b) % r)
return tuple(c) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Let's say another party wants to multiply Alice's shares by the **scalar** value of 3. | alice_times3 = public_mul(alice_shares, 3, Q) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Then we can decrypt (with Alice's permission) to double check we did multiply what we intended. | decrypt(alice_times3,Q) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
And this is `True` because Alice's secret $sa = 5$, remember? | decrypt(alice_times3,Q) == sa * 3 | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
PyTorch + PySyft implementationNow that you know how additive secret sharing works under the hood, let's see how we can leverage PyTorch and PySyft to do it for us. | import torch
import syft as sy
hook = sy.TorchHook(torch) | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Let's say Alice, Bob and Charlie are all enrolled on the **Foundations of Privacy** course and we, as instructors, want to know on average, how far in the course they are. We don't want to breach their privacy so each percentage of completion will be their own secret (a, b and c). For educational purposes, we will defi... | alice = sy.VirtualWorker(hook, id="alice")
bob = sy.VirtualWorker(hook, id="bob")
charlie = sy.VirtualWorker(hook, id="charlie") | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
We also need a "secure worker", also known as the `Crypto Provider` to provide us with random prime numbers. | secure_worker = sy.VirtualWorker(hook, "secure_worker") | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
We define our secrets using `torch.tensor` PyTorch tensor objects and we `Additive Share` them with our fellow workers. | # Let a, b and c be our students' completion percentage
a = torch.tensor([35])
b = torch.tensor([77])
c = torch.tensor([10])
# And we additive share with our parties
a = a.share(alice, bob, charlie, crypto_provider=secure_worker)
b = b.share(alice, bob, charlie, crypto_provider=secure_worker)
c = c.share(alice, bob, ch... | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
Also, see that the object type is **[AdditiveSharingTensor]**.For this example, we can decrypt our computation result using the get() method | decrypted_mean = mean.get()
decrypted_mean | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
And get the scalar using the item() method (Only works for 1-dimensional tensors). | scalar_mean = decrypted_mean.item()
scalar_mean | _____no_output_____ | MIT | Foundations_of_Private_Computation/Secure_multiparty_computation/Additive Secret Sharing.ipynb | gonzalo-munillag/Private_AI_OpenMined |
import numpy as np
import torch
x=torch.rand(3,2)
x
y=torch.ones(x.size())
y
z =x + y
z
z[0]
z[:,:1]
z.add(1)
z.size()
z.resize_(2,3)
a=np.random.rand(4,3)
a
b=torch.from_numpy(a)
b
b.numpy()
b.mul(2)
| _____no_output_____ | MIT | basic_torch.ipynb | RRakshit/AIPND | |
HMM Software- [hmmlearn](https://hmmlearn.readthedocs.io/en/latest/tutorial.html)- [pomegranite]()- [r calculate AIC/BIC of model](https://rdrr.io/cran/HMMpa/man/AIC_HMM.html)- [comparison between pomegranite and hmmlearn (with notebook)](https://kyso.io/share/pomegranate-vs-hmmlearnfiles)- [discussion of AIC/BIC from... | %env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=2
%load_ext autoreload
%autoreload 2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from tqdm.autonotebook import tqdm
from joblib import Parallel, delayed
import umap
import pandas as pd
from avgn.utils.paths import DATA_DIR, most_recen... | _____no_output_____ | MIT | notebooks/0.31-compare-sequence-models-bf/.ipynb_checkpoints/hmmlearn_FOMM-checkpoint.ipynb | xingjeffrey/avgn_paper |
Collect data | DATASET_ID = 'bengalese_finch_sober'
DATA_DIR
syllable_df = pd.concat([pd.read_pickle(i) for i in list((DATA_DIR / 'indv_dfs' / DATASET_ID).glob('*.pickle'))])
syllable_df[:3]
label = "hdbscan_labels" | _____no_output_____ | MIT | notebooks/0.31-compare-sequence-models-bf/.ipynb_checkpoints/hmmlearn_FOMM-checkpoint.ipynb | xingjeffrey/avgn_paper |
Compare hdbscan to hand | from avgn.visualization.projections import scatter_spec, scatter_projections
from avgn.utils.general import save_fig
from avgn.utils.paths import FIGURE_DIR, ensure_dir
indvs = syllable_df.indv.unique()
label_dict = {lab:i for i, lab in enumerate(np.unique(syllable_df['labels'].values))}
syllable_df['labels_num'] = [la... | _____no_output_____ | MIT | notebooks/0.31-compare-sequence-models-bf/.ipynb_checkpoints/hmmlearn_FOMM-checkpoint.ipynb | xingjeffrey/avgn_paper |
train HMM on data | indv = 'gy6or6'
indv_df = syllable_df[syllable_df.indv == indv]
indv_df = indv_df.sort_values(by=['syllables_sequence_id', 'syllables_sequence_pos'])
indv_df = indv_df.reset_index()
print(len(indv_df))
indv_df[:3]
element_prob = {i: np.sum(indv_df.labels_num.values== i) for i in np.unique(indv_df.labels_num.values)}
el... | _____no_output_____ | MIT | notebooks/0.31-compare-sequence-models-bf/.ipynb_checkpoints/hmmlearn_FOMM-checkpoint.ipynb | xingjeffrey/avgn_paper |
TODO- create a HMM where latent states are just normal states (e.g. Markov model) - compute likelihood of markov model- create a HMM where latent states are HDBSCAN states - compute likelihood of model- create a second order markov model - compute likelihood of markov model- create a HMM where latent states are le... | from hmmlearn.utils import iter_from_X_lengths
results_df.iloc[0]
model = results_df.iloc[0].model
lengths = [len(i) for i in seqs_test]
X = np.concatenate(seqs_test).reshape(-1, 1)
len(X), len(lengths)
curr_logprob = 0
for i,j in iter_from_X_lengths(X, lengths):
framelogprob = model._compute_log_likelihood(X[i:j])... | _____no_output_____ | MIT | notebooks/0.31-compare-sequence-models-bf/.ipynb_checkpoints/hmmlearn_FOMM-checkpoint.ipynb | xingjeffrey/avgn_paper |
TensorFlow Tutorial 05 Ensemble Learningby [Magnus Erik Hvass Pedersen](http://www.hvass-labs.org/)/ [GitHub](https://github.com/Hvass-Labs/TensorFlow-Tutorials) / [Videos on YouTube](https://www.youtube.com/playlist?list=PL9Hr9sNUjfsmEu1ZniY0XpHSzl5uihcXZ) IntroductionThis tutorial shows how to use a so-called ensem... | from IPython.display import Image
Image('images/02_network_flowchart.png') | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Imports | %matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
import os
# Use PrettyTensor to simplify Neural Network construction.
import prettytensor as pt | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
This was developed using Python 3.5.2 (Anaconda) and TensorFlow version: | tf.__version__ | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
PrettyTensor version: | pt.__version__ | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Load Data The MNIST data-set is about 12 MB and will be downloaded automatically if it is not located in the given path. | from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets('data/MNIST/', one_hot=True) | Extracting data/MNIST/train-images-idx3-ubyte.gz
Extracting data/MNIST/train-labels-idx1-ubyte.gz
Extracting data/MNIST/t10k-images-idx3-ubyte.gz
Extracting data/MNIST/t10k-labels-idx1-ubyte.gz
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The MNIST data-set has now been loaded and consists of 70,000 images and associated labels (i.e. classifications of the images). The data-set is split into 3 mutually exclusive sub-sets, but we will make random training-sets further below. | print("Size of:")
print("- Training-set:\t\t{}".format(len(data.train.labels)))
print("- Test-set:\t\t{}".format(len(data.test.labels)))
print("- Validation-set:\t{}".format(len(data.validation.labels))) | Size of:
- Training-set: 55000
- Test-set: 10000
- Validation-set: 5000
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Class numbersThe class-labels are One-Hot encoded, which means that each label is a vector with 10 elements, all of which are zero except for one element. The index of this one element is the class-number, that is, the digit shown in the associated image. We also need the class-numbers as integers for the test- and va... | data.test.cls = np.argmax(data.test.labels, axis=1)
data.validation.cls = np.argmax(data.validation.labels, axis=1) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-function for creating random training-setsWe will train 5 neural networks on different training-sets that are selected at random. First we combine the original training- and validation-sets into one big set. This is done for both the images and the labels. | combined_images = np.concatenate([data.train.images, data.validation.images], axis=0)
combined_labels = np.concatenate([data.train.labels, data.validation.labels], axis=0) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Check that the shape of the combined arrays is correct. | print(combined_images.shape)
print(combined_labels.shape) | (60000, 784)
(60000, 10)
| MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Size of the combined data-set. | combined_size = len(combined_images)
combined_size | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Define the size of the training-set used for each neural network. You can try and change this. | train_size = int(0.8 * combined_size)
train_size | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
We do not use a validation-set during training, but this would be the size. | validation_size = combined_size - train_size
validation_size | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-function for splitting the combined data-set into a random training- and validation-set. | def random_training_set():
# Create a randomized index into the full / combined training-set.
idx = np.random.permutation(combined_size)
# Split the random index into training- and validation-sets.
idx_train = idx[0:train_size]
idx_validation = idx[train_size:]
# Select the images and labels f... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Data Dimensions The data dimensions are used in several places in the source-code below. They are defined once so we can use these variables instead of numbers throughout the source-code below. | # We know that MNIST images are 28 pixels in each dimension.
img_size = 28
# Images are stored in one-dimensional arrays of this length.
img_size_flat = img_size * img_size
# Tuple with height and width of images used to reshape arrays.
img_shape = (img_size, img_size)
# Number of colour channels for the images: 1 c... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-function for plotting images Function used to plot 9 images in a 3x3 grid, and writing the true and predicted classes below each image. | def plot_images(images, # Images to plot, 2-d array.
cls_true, # True class-no for images.
ensemble_cls_pred=None, # Ensemble predicted class-no.
best_cls_pred=None): # Best-net predicted class-no.
assert len(images) == len(cls_tr... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Plot a few images to see if data is correct | # Get the first images from the test-set.
images = data.test.images[0:9]
# Get the true classes for those images.
cls_true = data.test.cls[0:9]
# Plot the images and labels using our helper-function above.
plot_images(images=images, cls_true=cls_true) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
TensorFlow GraphThe entire purpose of TensorFlow is to have a so-called computational graph that can be executed much more efficiently than if the same calculations were to be performed directly in Python. TensorFlow can be more efficient than NumPy because TensorFlow knows the entire computation graph that must be ex... | x = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x') | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The convolutional layers expect `x` to be encoded as a 4-dim tensor so we have to reshape it so its shape is instead `[num_images, img_height, img_width, num_channels]`. Note that `img_height == img_width == img_size` and `num_images` can be inferred automatically by using -1 for the size of the first dimension. So the... | x_image = tf.reshape(x, [-1, img_size, img_size, num_channels]) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Next we have the placeholder variable for the true labels associated with the images that were input in the placeholder variable `x`. The shape of this placeholder variable is `[None, num_classes]` which means it may hold an arbitrary number of labels and each label is a vector of length `num_classes` which is 10 in th... | y_true = tf.placeholder(tf.float32, shape=[None, 10], name='y_true') | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
We could also have a placeholder variable for the class-number, but we will instead calculate it using argmax. Note that this is a TensorFlow operator so nothing is calculated at this point. | y_true_cls = tf.argmax(y_true, dimension=1) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Neural Network This section implements the Convolutional Neural Network using Pretty Tensor, which is much simpler than a direct implementation in TensorFlow, see Tutorial 03.The basic idea is to wrap the input tensor `x_image` in a Pretty Tensor object which has helper-functions for adding new computational layers so... | x_pretty = pt.wrap(x_image) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Now that we have wrapped the input image in a Pretty Tensor object, we can add the convolutional and fully-connected layers in just a few lines of source-code.Note that `pt.defaults_scope(activation_fn=tf.nn.relu)` makes `activation_fn=tf.nn.relu` an argument for each of the layers constructed inside the `with`-block, ... | with pt.defaults_scope(activation_fn=tf.nn.relu):
y_pred, loss = x_pretty.\
conv2d(kernel=5, depth=16, name='layer_conv1').\
max_pool(kernel=2, stride=2).\
conv2d(kernel=5, depth=36, name='layer_conv2').\
max_pool(kernel=2, stride=2).\
flatten().\
fully_connected(size... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Optimization Method Pretty Tensor gave us the predicted class-label (`y_pred`) as well as a loss-measure that must be minimized, so as to improve the ability of the neural network to classify the input images.It is unclear from the documentation for Pretty Tensor whether the loss-measure is cross-entropy or something ... | optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Performance MeasuresWe need a few more performance measures to display the progress to the user.First we calculate the predicted class number from the output of the neural network `y_pred`, which is a vector with 10 elements. The class number is the index of the largest element. | y_pred_cls = tf.argmax(y_pred, dimension=1) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Then we create a vector of booleans telling us whether the predicted class equals the true class of each image. | correct_prediction = tf.equal(y_pred_cls, y_true_cls) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
The classification accuracy is calculated by first type-casting the vector of booleans to floats, so that False becomes 0 and True becomes 1, and then taking the average of these numbers. | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
SaverIn order to save the variables of the neural network, we now create a Saver-object which is used for storing and retrieving all the variables of the TensorFlow graph. Nothing is actually saved at this point, which will be done further below.Note that if you have more than 100 neural networks in the ensemble then ... | saver = tf.train.Saver(max_to_keep=100) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
This is the directory used for saving and retrieving the data. | save_dir = 'checkpoints/' | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Create the directory if it does not exist. | if not os.path.exists(save_dir):
os.makedirs(save_dir) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
This function returns the save-path for the data-file with the given network number. | def get_save_path(net_number):
return save_dir + 'network' + str(net_number) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
TensorFlow Run Create TensorFlow sessionOnce the TensorFlow graph has been created, we have to create a TensorFlow session which is used to execute the graph. | session = tf.Session() | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Initialize variablesThe variables for `weights` and `biases` must be initialized before we start optimizing them. We make a simple wrapper-function for this, because we will call it several times below. | def init_variables():
session.run(tf.initialize_all_variables()) | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-function to create a random training batch. There are thousands of images in the training-set. It takes a long time to calculate the gradient of the model using all these images. We therefore only use a small batch of images in each iteration of the optimizer.If your computer crashes or becomes very slow becaus... | train_batch_size = 64 | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Function for selecting a random training-batch of the given size. | def random_batch(x_train, y_train):
# Total number of images in the training-set.
num_images = len(x_train)
# Create a random index into the training-set.
idx = np.random.choice(num_images,
size=train_batch_size,
replace=False)
# Use the random... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Helper-function to perform optimization iterations Function for performing a number of optimization iterations so as to gradually improve the variables of the network layers. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples... | def optimize(num_iterations, x_train, y_train):
# Start-time used for printing time-usage below.
start_time = time.time()
for i in range(num_iterations):
# Get a batch of training examples.
# x_batch now holds a batch of images and
# y_true_batch are the true labels for those image... | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Create ensemble of neural networks Number of neural networks in the ensemble. | num_networks = 5 | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Number of optimization iterations for each neural network. | num_iterations = 10000 | _____no_output_____ | MIT | 05_Ensemble_Learning.ipynb | bianan/TensorFlow-Tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.