From 45e9280a8ccd69a7b22d3e299fe37d5b79d8fd36 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Thu, 2 Jan 2020 16:35:37 +0800 Subject: [PATCH 01/18] Initial commit --- tutorials/adult_tutorial.py | 179 ++++++++++++++++++++++++++ tutorials/imdb_tutorial.py | 179 ++++++++++++++++++++++++++ tutorials/movielens_tutorial.py | 216 ++++++++++++++++++++++++++++++++ 3 files changed, 574 insertions(+) create mode 100644 tutorials/adult_tutorial.py create mode 100644 tutorials/imdb_tutorial.py create mode 100644 tutorials/movielens_tutorial.py diff --git a/tutorials/adult_tutorial.py b/tutorials/adult_tutorial.py new file mode 100644 index 0000000..a406306 --- /dev/null +++ b/tutorials/adult_tutorial.py @@ -0,0 +1,179 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Training a one-layer NN on Adult data with differentially private SGD optimizer.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import tensorflow as tf +from scipy.stats import norm + +from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp +from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent +from tensorflow_privacy.privacy.optimizers import dp_optimizer + +from privacy_accountants import * +#### FLAGS +tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' + 'train with vanilla SGD.') +tf.flags.DEFINE_float('learning_rate', .15, 'Learning rate for training') +tf.flags.DEFINE_float('noise_multiplier', 0.55, + 'Ratio of the standard deviation to the clipping norm') +tf.flags.DEFINE_float('l2_norm_clip', 1, 'Clipping norm') +tf.flags.DEFINE_integer('epochs', 20, 'Number of epochs') +tf.flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') +tf.flags.DEFINE_string('model_dir', None, 'Model directory') + +FLAGS = tf.flags.FLAGS + +microbatches=256 +np.random.seed(0) +tf.set_random_seed(0) + +def nn_model_fn(features, labels, mode): + + # Define CNN architecture using tf.keras.layers. + input_layer = tf.reshape(features['x'], [-1,123]) + y = tf.keras.layers.Dense(16,activation='relu').apply(input_layer) + logits = tf.keras.layers.Dense(2).apply(y) + + # Calculate loss as a vector (to support microbatches in DP-SGD). + vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( + labels=labels, logits=logits) + # Define mean of loss across minibatch (for reporting through tf.Estimator). + scalar_loss = tf.reduce_mean(vector_loss) + + # Configure the training op (for TRAIN mode). + if mode == tf.estimator.ModeKeys.TRAIN: + + if FLAGS.dpsgd: + # Use DP version of GradientDescentOptimizer. Other optimizers are + # available in dp_optimizer. Most optimizers inheriting from + # tf.train.Optimizer should be wrappable in differentially private + # counterparts by calling dp_optimizer.optimizer_from_args(). + optimizer = dp_optimizer.DPGradientDescentGaussianOptimizer( + l2_norm_clip=FLAGS.l2_norm_clip, + noise_multiplier=FLAGS.noise_multiplier, + num_microbatches=microbatches, + learning_rate=FLAGS.learning_rate) + opt_loss = vector_loss + else: + optimizer = tf.train.GradientDescentOptimizer( + learning_rate=FLAGS.learning_rate) + opt_loss = scalar_loss + global_step = tf.train.get_global_step() + train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) + # In the following, we pass the mean of the loss (scalar_loss) rather than + # the vector_loss because tf.estimator requires a scalar loss. This is only + # used for evaluation and debugging by tf.estimator. The actual loss being + # minimized is opt_loss defined above and passed to optimizer.minimize(). + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + train_op=train_op) + + # Add evaluation metrics (for EVAL mode). + elif mode == tf.estimator.ModeKeys.EVAL: + eval_metric_ops = { + 'accuracy': + tf.metrics.accuracy( + labels=labels, + predictions=tf.argmax(input=logits, axis=1)) + } + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + eval_metric_ops=eval_metric_ops) + + +def load_adult(): + """Loads ADULT a2a as in LIBSVM and preprocesses to combine training and validation data.""" + """https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html""" + import pandas as pd + from sklearn.model_selection import KFold + + X=pd.read_csv("adult.csv") + kf = KFold(n_splits=10) + for train_index, test_index in kf.split(X): + train, test = X.iloc[train_index,:], X.iloc[test_index,:] + train_data = train.iloc[:,range(X.shape[1]-1)].values.astype('float32') + test_data = test.iloc[:,range(X.shape[1]-1)].values.astype('float32') + + train_labels = (train.iloc[:,X.shape[1]-1]==1).astype('int32').values + test_labels = (test.iloc[:,X.shape[1]-1]==1).astype('int32').values + + return train_data, train_labels, test_data, test_labels + + +def main(unused_argv): + tf.logging.set_verbosity(3) + + # Load training and test data. + train_data, train_labels, test_data, test_labels = load_adult() + + # Instantiate the tf.Estimator. + adult_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, + model_dir=FLAGS.model_dir) + + # Create tf.Estimator input functions for the training and test data. + eval_input_fn = tf.estimator.inputs.numpy_input_fn( + x={'x': test_data}, + y=test_labels, + num_epochs=1, + shuffle=False) + + # Training loop. + steps_per_epoch = 29305 // 256 + test_accuracy_list = [] + for epoch in range(1, FLAGS.epochs + 1): + np.random.seed(epoch) + for step in range(steps_per_epoch): + tf.set_random_seed(0) + whether=np.random.random_sample(29305)>(1-256/29305) + subsampling=[i for i in np.arange(29305) if whether[i]] + global microbatches + microbatches=len(subsampling) + + train_input_fn = tf.estimator.inputs.numpy_input_fn( + x={'x': train_data[subsampling]}, + y=train_labels[subsampling], + batch_size=len(subsampling), + num_epochs=1, + shuffle=True) + # Train the model for one step. + adult_classifier.train(input_fn=train_input_fn, steps=1) + + # Evaluate the model and print results + eval_results = adult_classifier.evaluate(input_fn=eval_input_fn) + test_accuracy = eval_results['accuracy'] + test_accuracy_list.append(test_accuracy) + print('Test accuracy after %d epochs is: %.3f' % (epoch, test_accuracy)) + + # Compute the privacy budget expended so far. + if FLAGS.dpsgd: + eps = compute_epsP(epoch,FLAGS.noise_multiplier,29305,256,1e-5) + mu= compute_muP(epoch,FLAGS.noise_multiplier,29305,256) + print('For delta=1e-5, the current epsilon is: %.2f' % eps) + print('For delta=1e-5, the current mu is: %.2f' % mu) + + if mu>FLAGS.max_mu: + break + else: + print('Trained with vanilla non-private SGD optimizer') + + +if __name__ == '__main__': + tf.app.run() diff --git a/tutorials/imdb_tutorial.py b/tutorials/imdb_tutorial.py new file mode 100644 index 0000000..48ec599 --- /dev/null +++ b/tutorials/imdb_tutorial.py @@ -0,0 +1,179 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Training a deep NN on IMDB reviews with differentially private Adam optimizer.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import tensorflow as tf +from scipy.stats import norm + +from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp +from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent +from tensorflow_privacy.privacy.optimizers import dp_optimizer + +from privacy_accountants import * + +from keras.preprocessing import sequence +#### FLAGS +tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' + 'train with vanilla SGD.') +tf.flags.DEFINE_float('learning_rate', 0.02, 'Learning rate for training') +tf.flags.DEFINE_float('noise_multiplier', 0.56, + 'Ratio of the standard deviation to the clipping norm') +tf.flags.DEFINE_float('l2_norm_clip', 1, 'Clipping norm') +tf.flags.DEFINE_integer('epochs', 25, 'Number of epochs') +tf.flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') +tf.flags.DEFINE_string('model_dir', None, 'Model directory') + +FLAGS = tf.flags.FLAGS + +microbatches=512 +np.random.seed(0) +tf.set_random_seed(0) + +max_features = 10000 +# cut texts after this number of words (among top max_features most common words) +maxlen = 256 + + +def rnn_model_fn(features, labels, mode): + # Define CNN architecture using tf.keras.layers. + input_layer = tf.reshape(features['x'], [-1,maxlen]) + y = tf.keras.layers.Embedding(max_features,16).apply(input_layer) + y=tf.keras.layers.GlobalAveragePooling1D().apply(y) + y= tf.keras.layers.Dense(16, activation='relu').apply(y) + logits= tf.keras.layers.Dense(2).apply(y) + + # Calculate loss as a vector (to support microbatches in DP-SGD). + vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( + labels=labels, logits=logits) + # Define mean of loss across minibatch (for reporting through tf.Estimator). + scalar_loss = tf.reduce_mean(vector_loss) + + # Configure the training op (for TRAIN mode). + if mode == tf.estimator.ModeKeys.TRAIN: + + if FLAGS.dpsgd: + # Use DP version of GradientDescentOptimizer. Other optimizers are + # available in dp_optimizer. Most optimizers inheriting from + # tf.train.Optimizer should be wrappable in differentially private + # counterparts by calling dp_optimizer.optimizer_from_args(). + optimizer = dp_optimizer.DPAdamGaussianOptimizer( + l2_norm_clip=FLAGS.l2_norm_clip, + noise_multiplier=FLAGS.noise_multiplier, + num_microbatches=microbatches, + learning_rate=FLAGS.learning_rate) + opt_loss = vector_loss + else: + optimizer = tf.train.AdamOptimizer( + learning_rate=FLAGS.learning_rate) + opt_loss = scalar_loss + + global_step = tf.train.get_global_step() + train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) + # In the following, we pass the mean of the loss (scalar_loss) rather than + # the vector_loss because tf.estimator requires a scalar loss. This is only + # used for evaluation and debugging by tf.estimator. The actual loss being + # minimized is opt_loss defined above and passed to optimizer.minimize(). + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + train_op=train_op) + + # Add evaluation metrics (for EVAL mode). + elif mode == tf.estimator.ModeKeys.EVAL: + eval_metric_ops = { + 'accuracy': + tf.metrics.accuracy( + labels=labels, + predictions=tf.argmax(input=logits, axis=1)) + } + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + eval_metric_ops=eval_metric_ops) + + + +def load_imdb(): + (train_data,train_labels), (test_data,test_labels) = tf.keras.datasets.imdb.load_data(num_words=max_features) + + train_data = sequence.pad_sequences(train_data, maxlen=maxlen).astype('float32') + test_data = sequence.pad_sequences(test_data, maxlen=maxlen).astype('float32') + return train_data,train_labels,test_data,test_labels + + +def main(unused_argv): + tf.logging.set_verbosity(3) + + # Load training and test data. + train_data,train_labels,test_data,test_labels = load_imdb() + + # Instantiate the tf.Estimator. + imdb_classifier = tf.estimator.Estimator(model_fn=rnn_model_fn, + model_dir=FLAGS.model_dir) + + # Create tf.Estimator input functions for the training and test data. + eval_input_fn = tf.estimator.inputs.numpy_input_fn( + x={'x': test_data}, + y=test_labels, + num_epochs=1, + shuffle=False) + + # Training loop. + steps_per_epoch = 25000 // 512 + test_accuracy_list = [] + + for epoch in range(1, FLAGS.epochs + 1): + np.random.seed(epoch) + for step in range(steps_per_epoch): + tf.set_random_seed(0) + whether=np.random.random_sample(25000)>(1-512/25000) + subsampling=[i for i in np.arange(25000) if whether[i]] + global microbatches + microbatches=len(subsampling) + + train_input_fn = tf.estimator.inputs.numpy_input_fn( + x={'x': train_data[subsampling]}, + y=train_labels[subsampling], + batch_size=len(subsampling), + num_epochs=1, + shuffle=False) + # Train the model for one step. + imdb_classifier.train(input_fn=train_input_fn, steps=1) + + # Evaluate the model and print results + eval_results = imdb_classifier.evaluate(input_fn=eval_input_fn) + test_accuracy = eval_results['accuracy'] + test_accuracy_list.append(test_accuracy) + print('Test accuracy after %d epochs is: %.3f' % (epoch, test_accuracy)) + + # Compute the privacy budget expended so far. + if FLAGS.dpsgd: + eps = compute_epsP(epoch,FLAGS.noise_multiplier,25000,512,1e-5) + mu= compute_muP(epoch,FLAGS.noise_multiplier,25000,512) + print('For delta=1e-5, the current epsilon is: %.2f' % eps) + print('For delta=1e-5, the current mu is: %.2f' % mu) + + if mu>FLAGS.max_mu: + break + else: + print('Trained with vanilla non-private SGD optimizer') + + +if __name__ == '__main__': + tf.app.run() diff --git a/tutorials/movielens_tutorial.py b/tutorials/movielens_tutorial.py new file mode 100644 index 0000000..035e119 --- /dev/null +++ b/tutorials/movielens_tutorial.py @@ -0,0 +1,216 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Training a deep NN on MovieLens with differentially private Adam optimizer.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import app +from absl import flags + +import numpy as np +import tensorflow as tf +from scipy.stats import norm + +from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp +from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent +from tensorflow_privacy.privacy.optimizers import dp_optimizer + +from privacy_accountants import * + +#### FLAGS +tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' + 'train with vanilla SGD.') +tf.flags.DEFINE_float('learning_rate', .01, 'Learning rate for training') +tf.flags.DEFINE_float('noise_multiplier', 0.55, + 'Ratio of the standard deviation to the clipping norm') +tf.flags.DEFINE_float('l2_norm_clip', 5, 'Clipping norm') +tf.flags.DEFINE_integer('epochs', 25, 'Number of epochs') +tf.flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') +tf.flags.DEFINE_string('model_dir', None, 'Model directory') + +FLAGS = tf.flags.FLAGS + +microbatches=10000 +np.random.seed(0) +tf.set_random_seed(0) + +n_users=6040 +n_movies=3706 + +def nn_model_fn(features, labels, mode): +# Adapted from https://github.com/hexiangnan/neural_collaborative_filtering + n_latent_factors_user = 10 + n_latent_factors_movie = 10 + n_latent_factors_mf = 5 + + user_input = tf.reshape(features['user'], [-1,1]) + item_input = tf.reshape(features['movie'], [-1,1]) + + mf_embedding_user = tf.keras.layers.Embedding(n_users,n_latent_factors_mf,input_length=1) + mf_embedding_item = tf.keras.layers.Embedding(n_movies,n_latent_factors_mf,input_length=1) + mlp_embedding_user = tf.keras.layers.Embedding(n_users,n_latent_factors_user,input_length=1) + mlp_embedding_item = tf.keras.layers.Embedding(n_movies,n_latent_factors_movie,input_length=1) + + # GMF part + # Flatten the embedding vector as latent features in GMF + mf_user_latent = tf.keras.layers.Flatten()(mf_embedding_user(user_input)) + mf_item_latent = tf.keras.layers.Flatten()(mf_embedding_item(item_input)) + # Element-wise multiply + mf_vector = tf.keras.layers.multiply([mf_user_latent, mf_item_latent]) + + # MLP part + # Flatten the embedding vector as latent features in MLP + mlp_user_latent = tf.keras.layers.Flatten()(mlp_embedding_user(user_input)) + mlp_item_latent = tf.keras.layers.Flatten()(mlp_embedding_item(item_input)) + # Concatenation of two latent features + mlp_vector = tf.keras.layers.concatenate([mlp_user_latent, mlp_item_latent]) + + predict_vector = tf.keras.layers.concatenate([mf_vector, mlp_vector]) + + logits = tf.keras.layers.Dense(5)(predict_vector) + + # Calculate loss as a vector (to support microbatches in DP-SGD). + vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) + # Define mean of loss across minibatch (for reporting through tf.Estimator). + scalar_loss = tf.reduce_mean(vector_loss) + + # Configure the training op (for TRAIN mode). + if mode == tf.estimator.ModeKeys.TRAIN: + + if FLAGS.dpsgd: + # Use DP version of GradientDescentOptimizer. Other optimizers are + # available in dp_optimizer. Most optimizers inheriting from + # tf.train.Optimizer should be wrappable in differentially private + # counterparts by calling dp_optimizer.optimizer_from_args(). + optimizer = dp_optimizer.DPAdamGaussianOptimizer( + l2_norm_clip=FLAGS.l2_norm_clip, + noise_multiplier=FLAGS.noise_multiplier, + num_microbatches=microbatches, + learning_rate=FLAGS.learning_rate) + opt_loss = vector_loss + else: + optimizer = tf.train.AdamOptimizer( + learning_rate=FLAGS.learning_rate) + opt_loss = scalar_loss + + global_step = tf.train.get_global_step() + train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) + # In the following, we pass the mean of the loss (scalar_loss) rather than + # the vector_loss because tf.estimator requires a scalar loss. This is only + # used for evaluation and debugging by tf.estimator. The actual loss being + # minimized is opt_loss defined above and passed to optimizer.minimize(). + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + train_op=train_op) + + # Add evaluation metrics (for EVAL mode). + elif mode == tf.estimator.ModeKeys.EVAL: + eval_metric_ops = { + 'rmse': + tf.metrics.root_mean_squared_error( + labels=tf.cast(labels, tf.float32), + predictions=tf.tensordot(a=tf.nn.softmax(logits,axis=1),b=tf.constant(np.array([0,1,2,3,4]),dtype=tf.float32),axes=1)) + } + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + eval_metric_ops=eval_metric_ops) + + +def load_adult(): + import pandas as pd + import numpy as np + + data = pd.read_csv('ratings.dat', sep='::', header=None,names=["userId", "movieId", "rating", "timestamp"]) + n_users=len(set(data['userId'])) + n_movies=len(set(data['movieId'])) + print('number of movie: ',n_movies) + print('number of user: ',n_users) + + # give unique dense movie index to movieId + from scipy.stats import rankdata + data['movieIndex']=rankdata(data['movieId'], method='dense') + # minus one to reduce the minimum value to 0, which is the start of col index + + print('number of ratings:',data.shape[0]) + print('percentage of sparsity:',(1-data.shape[0]/n_users/n_movies)*100,'%') + + from sklearn.model_selection import train_test_split + train,test=train_test_split(data,test_size=0.2,random_state=100) + + return train.values-1, test.values-1, np.mean(train['rating']) + + +def main(unused_argv): + tf.logging.set_verbosity(3) + + # Load training and test data. + train_data, test_data, mean = load_adult() + + # Instantiate the tf.Estimator. + adult_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, + model_dir=FLAGS.model_dir) + + # Create tf.Estimator input functions for the training and test data. + eval_input_fn = tf.estimator.inputs.numpy_input_fn( + x={'user': test_data[:,0], 'movie': test_data[:,4]}, + y=test_data[:,2], + num_epochs=1, + shuffle=False) + + # Training loop. + steps_per_epoch = 800167 // 10000 + test_accuracy_list = [] + for epoch in range(1, FLAGS.epochs + 1): + np.random.seed(epoch) + for step in range(steps_per_epoch): + tf.set_random_seed(0) + whether=np.random.random_sample(800167)>(1-10000/800167) + subsampling=[i for i in np.arange(800167) if whether[i]] + global microbatches + microbatches=len(subsampling) + + train_input_fn = tf.estimator.inputs.numpy_input_fn( + x={'user': train_data[subsampling,0], 'movie': train_data[subsampling,4]}, + y=train_data[subsampling,2], + batch_size=len(subsampling), + num_epochs=1, + shuffle=True) + # Train the model for one step. + adult_classifier.train(input_fn=train_input_fn, steps=1) + + # Evaluate the model and print results + eval_results = adult_classifier.evaluate(input_fn=eval_input_fn) + test_accuracy = eval_results['rmse'] + test_accuracy_list.append(test_accuracy) + print('Test RMSE after %d epochs is: %.3f' % (epoch, test_accuracy)) + + # Compute the privacy budget expended so far. + if FLAGS.dpsgd: + eps = compute_epsP(epoch,FLAGS.noise_multiplier,800167,10000,1e-6) + mu= compute_muP(epoch,FLAGS.noise_multiplier,800167,10000) + print('For delta=1e-6, the current epsilon is: %.2f' % eps) + print('For delta=1e-6, the current mu is: %.2f' % mu) + + if mu>FLAGS.max_mu: + break + else: + print('Trained with vanilla non-private SGD optimizer') + + +if __name__ == '__main__': + tf.app.run() From cbce4540d397f3bce457363310f3272192318c77 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Thu, 2 Jan 2020 16:36:31 +0800 Subject: [PATCH 02/18] Initial commit --- .../privacy/analysis/GDprivacy_accountants.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py diff --git a/tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py b/tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py new file mode 100644 index 0000000..ba56dac --- /dev/null +++ b/tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py @@ -0,0 +1,59 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +r"""This code applies the Dual and Central Limit +Theorem (CLT) to estimate privacy budget of an iterated subsampled +Gaussian Mechanism (by either uniform or Poisson subsampling). +""" + + +import numpy as np +from scipy.stats import norm +from scipy import optimize + +# Total number of examples:N +# batch size:batch_size +# Noise multiplier for DP-SGD/DP-Adam:noise_multiplier +# current epoch:epoch +# Target delta:delta + +# Compute mu from uniform subsampling +def compute_muU(epoch,noise_multi,N,batch_size): + T=epoch*N/batch_size + c=batch_size*np.sqrt(T)/N + return(np.sqrt(2)*c*np.sqrt(np.exp(noise_multi**(-2))*norm.cdf(1.5/noise_multi)+3*norm.cdf(-0.5/noise_multi)-2)) + +# Compute mu from Poisson subsampling +def compute_muP(epoch,noise_multi,N,batch_size): + T=epoch*N/batch_size + return(np.sqrt(np.exp(noise_multi**(-2))-1)*np.sqrt(T)*batch_size/N) + +# Dual between mu-GDP and (epsilon,delta)-DP +def delta_eps_mu(eps,mu): + return norm.cdf(-eps/mu+mu/2)-np.exp(eps)*norm.cdf(-eps/mu-mu/2) + +# inverse Dual +def eps_from_mu(mu,delta): + def f(x): + return delta_eps_mu(x,mu)-delta + return optimize.root_scalar(f, bracket=[0, 500], method='brentq').root + +# inverse Dual of uniform subsampling +def compute_epsU(epoch,noise_multi,N,batch_size,delta): + return(eps_from_mu(compute_muU(epoch,noise_multi,N,batch_size),delta)) + +# inverse Dual of Poisson subsampling +def compute_epsP(epoch,noise_multi,N,batch_size,delta): + return(eps_from_mu(compute_muP(epoch,noise_multi,N,batch_size),delta)) \ No newline at end of file From 4a39d26c2f51fd36750c0510ec9c549eec45d309 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Thu, 2 Jan 2020 16:37:24 +0800 Subject: [PATCH 03/18] Initial commit --- tutorials/adult_tutorial.py | 2 +- tutorials/imdb_tutorial.py | 2 +- tutorials/movielens_tutorial.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tutorials/adult_tutorial.py b/tutorials/adult_tutorial.py index a406306..0323875 100644 --- a/tutorials/adult_tutorial.py +++ b/tutorials/adult_tutorial.py @@ -27,7 +27,7 @@ from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer -from privacy_accountants import * +from GDprivacy_accountants import * #### FLAGS tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' 'train with vanilla SGD.') diff --git a/tutorials/imdb_tutorial.py b/tutorials/imdb_tutorial.py index 48ec599..cdb94c3 100644 --- a/tutorials/imdb_tutorial.py +++ b/tutorials/imdb_tutorial.py @@ -27,7 +27,7 @@ from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer -from privacy_accountants import * +from GDprivacy_accountants import * from keras.preprocessing import sequence #### FLAGS diff --git a/tutorials/movielens_tutorial.py b/tutorials/movielens_tutorial.py index 035e119..a5c31c2 100644 --- a/tutorials/movielens_tutorial.py +++ b/tutorials/movielens_tutorial.py @@ -30,7 +30,7 @@ from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer -from privacy_accountants import * +from GDprivacy_accountants import * #### FLAGS tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' From 47a984dc2596895d005d7c593d000c1658417319 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Thu, 2 Jan 2020 16:41:42 +0800 Subject: [PATCH 04/18] Delete --- tutorials/adult_tutorial.py | 179 ------------------------------------ 1 file changed, 179 deletions(-) delete mode 100644 tutorials/adult_tutorial.py diff --git a/tutorials/adult_tutorial.py b/tutorials/adult_tutorial.py deleted file mode 100644 index 0323875..0000000 --- a/tutorials/adult_tutorial.py +++ /dev/null @@ -1,179 +0,0 @@ -# Copyright 2015 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================= - -"""Training a one-layer NN on Adult data with differentially private SGD optimizer.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import numpy as np -import tensorflow as tf -from scipy.stats import norm - -from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp -from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent -from tensorflow_privacy.privacy.optimizers import dp_optimizer - -from GDprivacy_accountants import * -#### FLAGS -tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' - 'train with vanilla SGD.') -tf.flags.DEFINE_float('learning_rate', .15, 'Learning rate for training') -tf.flags.DEFINE_float('noise_multiplier', 0.55, - 'Ratio of the standard deviation to the clipping norm') -tf.flags.DEFINE_float('l2_norm_clip', 1, 'Clipping norm') -tf.flags.DEFINE_integer('epochs', 20, 'Number of epochs') -tf.flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') -tf.flags.DEFINE_string('model_dir', None, 'Model directory') - -FLAGS = tf.flags.FLAGS - -microbatches=256 -np.random.seed(0) -tf.set_random_seed(0) - -def nn_model_fn(features, labels, mode): - - # Define CNN architecture using tf.keras.layers. - input_layer = tf.reshape(features['x'], [-1,123]) - y = tf.keras.layers.Dense(16,activation='relu').apply(input_layer) - logits = tf.keras.layers.Dense(2).apply(y) - - # Calculate loss as a vector (to support microbatches in DP-SGD). - vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( - labels=labels, logits=logits) - # Define mean of loss across minibatch (for reporting through tf.Estimator). - scalar_loss = tf.reduce_mean(vector_loss) - - # Configure the training op (for TRAIN mode). - if mode == tf.estimator.ModeKeys.TRAIN: - - if FLAGS.dpsgd: - # Use DP version of GradientDescentOptimizer. Other optimizers are - # available in dp_optimizer. Most optimizers inheriting from - # tf.train.Optimizer should be wrappable in differentially private - # counterparts by calling dp_optimizer.optimizer_from_args(). - optimizer = dp_optimizer.DPGradientDescentGaussianOptimizer( - l2_norm_clip=FLAGS.l2_norm_clip, - noise_multiplier=FLAGS.noise_multiplier, - num_microbatches=microbatches, - learning_rate=FLAGS.learning_rate) - opt_loss = vector_loss - else: - optimizer = tf.train.GradientDescentOptimizer( - learning_rate=FLAGS.learning_rate) - opt_loss = scalar_loss - global_step = tf.train.get_global_step() - train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) - # In the following, we pass the mean of the loss (scalar_loss) rather than - # the vector_loss because tf.estimator requires a scalar loss. This is only - # used for evaluation and debugging by tf.estimator. The actual loss being - # minimized is opt_loss defined above and passed to optimizer.minimize(). - return tf.estimator.EstimatorSpec(mode=mode, - loss=scalar_loss, - train_op=train_op) - - # Add evaluation metrics (for EVAL mode). - elif mode == tf.estimator.ModeKeys.EVAL: - eval_metric_ops = { - 'accuracy': - tf.metrics.accuracy( - labels=labels, - predictions=tf.argmax(input=logits, axis=1)) - } - return tf.estimator.EstimatorSpec(mode=mode, - loss=scalar_loss, - eval_metric_ops=eval_metric_ops) - - -def load_adult(): - """Loads ADULT a2a as in LIBSVM and preprocesses to combine training and validation data.""" - """https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html""" - import pandas as pd - from sklearn.model_selection import KFold - - X=pd.read_csv("adult.csv") - kf = KFold(n_splits=10) - for train_index, test_index in kf.split(X): - train, test = X.iloc[train_index,:], X.iloc[test_index,:] - train_data = train.iloc[:,range(X.shape[1]-1)].values.astype('float32') - test_data = test.iloc[:,range(X.shape[1]-1)].values.astype('float32') - - train_labels = (train.iloc[:,X.shape[1]-1]==1).astype('int32').values - test_labels = (test.iloc[:,X.shape[1]-1]==1).astype('int32').values - - return train_data, train_labels, test_data, test_labels - - -def main(unused_argv): - tf.logging.set_verbosity(3) - - # Load training and test data. - train_data, train_labels, test_data, test_labels = load_adult() - - # Instantiate the tf.Estimator. - adult_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, - model_dir=FLAGS.model_dir) - - # Create tf.Estimator input functions for the training and test data. - eval_input_fn = tf.estimator.inputs.numpy_input_fn( - x={'x': test_data}, - y=test_labels, - num_epochs=1, - shuffle=False) - - # Training loop. - steps_per_epoch = 29305 // 256 - test_accuracy_list = [] - for epoch in range(1, FLAGS.epochs + 1): - np.random.seed(epoch) - for step in range(steps_per_epoch): - tf.set_random_seed(0) - whether=np.random.random_sample(29305)>(1-256/29305) - subsampling=[i for i in np.arange(29305) if whether[i]] - global microbatches - microbatches=len(subsampling) - - train_input_fn = tf.estimator.inputs.numpy_input_fn( - x={'x': train_data[subsampling]}, - y=train_labels[subsampling], - batch_size=len(subsampling), - num_epochs=1, - shuffle=True) - # Train the model for one step. - adult_classifier.train(input_fn=train_input_fn, steps=1) - - # Evaluate the model and print results - eval_results = adult_classifier.evaluate(input_fn=eval_input_fn) - test_accuracy = eval_results['accuracy'] - test_accuracy_list.append(test_accuracy) - print('Test accuracy after %d epochs is: %.3f' % (epoch, test_accuracy)) - - # Compute the privacy budget expended so far. - if FLAGS.dpsgd: - eps = compute_epsP(epoch,FLAGS.noise_multiplier,29305,256,1e-5) - mu= compute_muP(epoch,FLAGS.noise_multiplier,29305,256) - print('For delta=1e-5, the current epsilon is: %.2f' % eps) - print('For delta=1e-5, the current mu is: %.2f' % mu) - - if mu>FLAGS.max_mu: - break - else: - print('Trained with vanilla non-private SGD optimizer') - - -if __name__ == '__main__': - tf.app.run() From 1d5c5ac2fc5373c60f12a8b0497d97a3a08c04be Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Sun, 19 Jan 2020 20:27:35 +0800 Subject: [PATCH 05/18] Add files via upload --- tutorials/adult_tutorial.py | 178 +++++++++++++++++++++ tutorials/imdb_tutorial.py | 248 ++++++++++++++--------------- tutorials/movielens_tutorial.py | 267 ++++++++++++++++---------------- 3 files changed, 435 insertions(+), 258 deletions(-) create mode 100644 tutorials/adult_tutorial.py diff --git a/tutorials/adult_tutorial.py b/tutorials/adult_tutorial.py new file mode 100644 index 0000000..b92b352 --- /dev/null +++ b/tutorials/adult_tutorial.py @@ -0,0 +1,178 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +"""Training a one-layer NN on Adult data with differentially private SGD optimizer.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from absl import app +from absl import flags + +import numpy as np +import tensorflow as tf +import pandas as pd +from sklearn.model_selection import KFold + +# from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp +# from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent +from tensorflow_privacy.privacy.optimizers import dp_optimizer + +from tensorflow_privacy.privacy.analysis.gdp_accountant import * + +#### FLAGS +FLAGS = flags.FLAGS +flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD.' + 'If False, train with vanilla SGD.') +flags.DEFINE_float('learning_rate', .15, 'Learning rate for training') +flags.DEFINE_float('noise_multiplier', 0.55, + 'Ratio of the standard deviation to the clipping norm') +flags.DEFINE_float('l2_norm_clip', 1, 'Clipping norm') +flags.DEFINE_integer('epochs', 20, 'Number of epochs') +flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') +flags.DEFINE_string('model_dir', None, 'Model directory') + +microbatches = 256 + +def nn_model_fn(features, labels, mode): + ''' Define CNN architecture using tf.keras.layers.''' + input_layer = tf.reshape(features['x'], [-1, 123]) + y = tf.keras.layers.Dense(16, activation='relu').apply(input_layer) + logits = tf.keras.layers.Dense(2).apply(y) + + # Calculate loss as a vector (to support microbatches in DP-SGD). + vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( + labels=labels, logits=logits) + # Define mean of loss across minibatch (for reporting through tf.Estimator). + scalar_loss = tf.reduce_mean(vector_loss) + + # Configure the training op (for TRAIN mode). + if mode == tf.estimator.ModeKeys.TRAIN: + if FLAGS.dpsgd: + # Use DP version of GradientDescentOptimizer. Other optimizers are + # available in dp_optimizer. Most optimizers inheriting from + # tf.train.Optimizer should be wrappable in differentially private + # counterparts by calling dp_optimizer.optimizer_from_args(). + optimizer = dp_optimizer.DPGradientDescentGaussianOptimizer( + l2_norm_clip=FLAGS.l2_norm_clip, + noise_multiplier=FLAGS.noise_multiplier, + num_microbatches=microbatches, + learning_rate=FLAGS.learning_rate) + opt_loss = vector_loss + else: + optimizer = tf.compat.v1.train.GradientDescentOptimizer( + learning_rate=FLAGS.learning_rate) + opt_loss = scalar_loss + global_step = tf.compat.v1.train.get_global_step() + train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) + # In the following, we pass the mean of the loss (scalar_loss) rather than + # the vector_loss because tf.estimator requires a scalar loss. This is only + # used for evaluation and debugging by tf.estimator. The actual loss being + # minimized is opt_loss defined above and passed to optimizer.minimize(). + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + train_op=train_op) + + # Add evaluation metrics (for EVAL mode). + if mode == tf.estimator.ModeKeys.EVAL: + eval_metric_ops = { + 'accuracy': + tf.compat.v1.metrics.accuracy( + labels=labels, + predictions=tf.argmax(input=logits, axis=1)) + } + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + eval_metric_ops=eval_metric_ops) + + return None + + +def load_adult(): + """Loads ADULT a2a as in LIBSVM and preprocesses to combine training and validation data.""" + # https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary.html + + X = pd.read_csv("adult.csv") + kf = KFold(n_splits=10) + for train_index, test_index in kf.split(X): + train, test = X.iloc[train_index, :], X.iloc[test_index, :] + train_data = train.iloc[:, range(X.shape[1]-1)].values.astype('float32') + test_data = test.iloc[:, range(X.shape[1]-1)].values.astype('float32') + + train_labels = (train.iloc[:, X.shape[1]-1] == 1).astype('int32').values + test_labels = (test.iloc[:, X.shape[1]-1] == 1).astype('int32').values + + return train_data, train_labels, test_data, test_labels + + +def main(unused_argv): + '''main''' + tf.compat.v1.logging.set_verbosity(0) + + # Load training and test data. + train_data, train_labels, test_data, test_labels = load_adult() + + # Instantiate the tf.Estimator. + adult_classifier = tf.compat.v1.estimator.Estimator(model_fn=nn_model_fn, + model_dir=FLAGS.model_dir) + + # Create tf.Estimator input functions for the training and test data. + eval_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn( + x={'x': test_data}, + y=test_labels, + num_epochs=1, + shuffle=False) + + # Training loop. + steps_per_epoch = 29305 // 256 + test_accuracy_list = [] + for epoch in range(1, FLAGS.epochs + 1): + for step in range(steps_per_epoch): + whether = np.random.random_sample(29305) > (1-256/29305) + subsampling = [i for i in np.arange(29305) if whether[i]] + global microbatches + microbatches = len(subsampling) + + train_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn( + x={'x': train_data[subsampling]}, + y=train_labels[subsampling], + batch_size=len(subsampling), + num_epochs=1, + shuffle=True) + # Train the model for one step. + adult_classifier.train(input_fn=train_input_fn, steps=1) + + # Evaluate the model and print results + eval_results = adult_classifier.evaluate(input_fn=eval_input_fn) + test_accuracy = eval_results['accuracy'] + test_accuracy_list.append(test_accuracy) + print('Test accuracy after %d epochs is: %.3f' % (epoch, test_accuracy)) + + # Compute the privacy budget expended so far. + if FLAGS.dpsgd: + eps = compute_eps_Poisson(epoch, FLAGS.noise_multiplier, 29305, 256, 1e-5) + mu = compute_mu_Poisson(epoch, FLAGS.noise_multiplier, 29305, 256) + print('For delta=1e-5, the current epsilon is: %.2f' % eps) + print('For delta=1e-5, the current mu is: %.2f' % mu) + + if mu > FLAGS.max_mu: + break + else: + print('Trained with vanilla non-private SGD optimizer') + + +if __name__ == '__main__': + app.run(main) diff --git a/tutorials/imdb_tutorial.py b/tutorials/imdb_tutorial.py index cdb94c3..2b37e7b 100644 --- a/tutorials/imdb_tutorial.py +++ b/tutorials/imdb_tutorial.py @@ -19,161 +19,163 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function +from absl import app +from absl import flags + import numpy as np import tensorflow as tf -from scipy.stats import norm +from keras.preprocessing import sequence -from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp -from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent +#from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp +#from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer -from GDprivacy_accountants import * +from tensorflow_privacy.privacy.analysis.gdp_accountant import * + -from keras.preprocessing import sequence #### FLAGS -tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' - 'train with vanilla SGD.') -tf.flags.DEFINE_float('learning_rate', 0.02, 'Learning rate for training') -tf.flags.DEFINE_float('noise_multiplier', 0.56, - 'Ratio of the standard deviation to the clipping norm') -tf.flags.DEFINE_float('l2_norm_clip', 1, 'Clipping norm') -tf.flags.DEFINE_integer('epochs', 25, 'Number of epochs') -tf.flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') -tf.flags.DEFINE_string('model_dir', None, 'Model directory') +FLAGS = flags.FLAGS +flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' + 'train with vanilla SGD.') +flags.DEFINE_float('learning_rate', 0.02, 'Learning rate for training') +flags.DEFINE_float('noise_multiplier', 0.56, + 'Ratio of the standard deviation to the clipping norm') +flags.DEFINE_float('l2_norm_clip', 1, 'Clipping norm') +flags.DEFINE_integer('epochs', 25, 'Number of epochs') +flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') +flags.DEFINE_string('model_dir', None, 'Model directory') -FLAGS = tf.flags.FLAGS -microbatches=512 -np.random.seed(0) -tf.set_random_seed(0) +microbatches = 512 max_features = 10000 # cut texts after this number of words (among top max_features most common words) maxlen = 256 -def rnn_model_fn(features, labels, mode): - # Define CNN architecture using tf.keras.layers. - input_layer = tf.reshape(features['x'], [-1,maxlen]) - y = tf.keras.layers.Embedding(max_features,16).apply(input_layer) - y=tf.keras.layers.GlobalAveragePooling1D().apply(y) - y= tf.keras.layers.Dense(16, activation='relu').apply(y) - logits= tf.keras.layers.Dense(2).apply(y) - - # Calculate loss as a vector (to support microbatches in DP-SGD). - vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( - labels=labels, logits=logits) - # Define mean of loss across minibatch (for reporting through tf.Estimator). - scalar_loss = tf.reduce_mean(vector_loss) +def nn_model_fn(features, labels, mode): + '''Define NN architecture using tf.keras.layers.''' + input_layer = tf.reshape(features['x'], [-1, maxlen]) + y = tf.keras.layers.Embedding(max_features, 16).apply(input_layer) + y = tf.keras.layers.GlobalAveragePooling1D().apply(y) + y = tf.keras.layers.Dense(16, activation='relu').apply(y) + logits = tf.keras.layers.Dense(2).apply(y) - # Configure the training op (for TRAIN mode). - if mode == tf.estimator.ModeKeys.TRAIN: + # Calculate loss as a vector (to support microbatches in DP-SGD). + vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits( + labels=labels, logits=logits) + # Define mean of loss across minibatch (for reporting through tf.Estimator). + scalar_loss = tf.reduce_mean(vector_loss) - if FLAGS.dpsgd: - # Use DP version of GradientDescentOptimizer. Other optimizers are - # available in dp_optimizer. Most optimizers inheriting from - # tf.train.Optimizer should be wrappable in differentially private - # counterparts by calling dp_optimizer.optimizer_from_args(). - optimizer = dp_optimizer.DPAdamGaussianOptimizer( - l2_norm_clip=FLAGS.l2_norm_clip, - noise_multiplier=FLAGS.noise_multiplier, - num_microbatches=microbatches, - learning_rate=FLAGS.learning_rate) - opt_loss = vector_loss - else: - optimizer = tf.train.AdamOptimizer( - learning_rate=FLAGS.learning_rate) - opt_loss = scalar_loss - - global_step = tf.train.get_global_step() - train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) - # In the following, we pass the mean of the loss (scalar_loss) rather than - # the vector_loss because tf.estimator requires a scalar loss. This is only - # used for evaluation and debugging by tf.estimator. The actual loss being - # minimized is opt_loss defined above and passed to optimizer.minimize(). - return tf.estimator.EstimatorSpec(mode=mode, - loss=scalar_loss, - train_op=train_op) + # Configure the training op (for TRAIN mode). + if mode == tf.estimator.ModeKeys.TRAIN: + if FLAGS.dpsgd: + # Use DP version of GradientDescentOptimizer. Other optimizers are + # available in dp_optimizer. Most optimizers inheriting from + # tf.train.Optimizer should be wrappable in differentially private + # counterparts by calling dp_optimizer.optimizer_from_args(). + optimizer = dp_optimizer.DPAdamGaussianOptimizer( + l2_norm_clip=FLAGS.l2_norm_clip, + noise_multiplier=FLAGS.noise_multiplier, + num_microbatches=microbatches, + learning_rate=FLAGS.learning_rate) + opt_loss = vector_loss + else: + optimizer = tf.compat.v1.train.AdamOptimizer( + learning_rate=FLAGS.learning_rate) + opt_loss = scalar_loss - # Add evaluation metrics (for EVAL mode). - elif mode == tf.estimator.ModeKeys.EVAL: - eval_metric_ops = { - 'accuracy': - tf.metrics.accuracy( - labels=labels, - predictions=tf.argmax(input=logits, axis=1)) - } - return tf.estimator.EstimatorSpec(mode=mode, - loss=scalar_loss, - eval_metric_ops=eval_metric_ops) + global_step = tf.compat.v1.train.get_global_step() + train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) + # In the following, we pass the mean of the loss (scalar_loss) rather than + # the vector_loss because tf.estimator requires a scalar loss. This is only + # used for evaluation and debugging by tf.estimator. The actual loss being + # minimized is opt_loss defined above and passed to optimizer.minimize(). + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + train_op=train_op) + + # Add evaluation metrics (for EVAL mode). + if mode == tf.estimator.ModeKeys.EVAL: + eval_metric_ops = { + 'accuracy': + tf.compat.v1.metrics.accuracy( + labels=labels, + predictions=tf.argmax(input=logits, axis=1)) + } + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + eval_metric_ops=eval_metric_ops) + return None def load_imdb(): - (train_data,train_labels), (test_data,test_labels) = tf.keras.datasets.imdb.load_data(num_words=max_features) + '''Load IMDB movie reviews data''' + (train_data, train_labels), (test_data, test_labels) = \ + tf.keras.datasets.imdb.load_data(num_words=max_features) - train_data = sequence.pad_sequences(train_data, maxlen=maxlen).astype('float32') - test_data = sequence.pad_sequences(test_data, maxlen=maxlen).astype('float32') - return train_data,train_labels,test_data,test_labels + train_data = sequence.pad_sequences(train_data, maxlen=maxlen).astype('float32') + test_data = sequence.pad_sequences(test_data, maxlen=maxlen).astype('float32') + return train_data, train_labels, test_data, test_labels def main(unused_argv): - tf.logging.set_verbosity(3) + '''main''' + tf.compat.v1.logging.set_verbosity(3) - # Load training and test data. - train_data,train_labels,test_data,test_labels = load_imdb() + # Load training and test data. + train_data, train_labels, test_data, test_labels = load_imdb() - # Instantiate the tf.Estimator. - imdb_classifier = tf.estimator.Estimator(model_fn=rnn_model_fn, - model_dir=FLAGS.model_dir) + # Instantiate the tf.Estimator. + imdb_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, + model_dir=FLAGS.model_dir) - # Create tf.Estimator input functions for the training and test data. - eval_input_fn = tf.estimator.inputs.numpy_input_fn( - x={'x': test_data}, - y=test_labels, - num_epochs=1, - shuffle=False) + # Create tf.Estimator input functions for the training and test data. + eval_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn( + x={'x': test_data}, + y=test_labels, + num_epochs=1, + shuffle=False) - # Training loop. - steps_per_epoch = 25000 // 512 - test_accuracy_list = [] + # Training loop. + steps_per_epoch = 25000 // 512 + test_accuracy_list = [] - for epoch in range(1, FLAGS.epochs + 1): - np.random.seed(epoch) - for step in range(steps_per_epoch): - tf.set_random_seed(0) - whether=np.random.random_sample(25000)>(1-512/25000) - subsampling=[i for i in np.arange(25000) if whether[i]] - global microbatches - microbatches=len(subsampling) + for epoch in range(1, FLAGS.epochs + 1): + for step in range(steps_per_epoch): + whether = np.random.random_sample(25000) > (1-512/25000) + subsampling = [i for i in np.arange(25000) if whether[i]] + global microbatches + microbatches = len(subsampling) - train_input_fn = tf.estimator.inputs.numpy_input_fn( - x={'x': train_data[subsampling]}, - y=train_labels[subsampling], - batch_size=len(subsampling), - num_epochs=1, - shuffle=False) - # Train the model for one step. - imdb_classifier.train(input_fn=train_input_fn, steps=1) + train_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn( + x={'x': train_data[subsampling]}, + y=train_labels[subsampling], + batch_size=len(subsampling), + num_epochs=1, + shuffle=False) + # Train the model for one step. + imdb_classifier.train(input_fn=train_input_fn, steps=1) + + # Evaluate the model and print results + eval_results = imdb_classifier.evaluate(input_fn=eval_input_fn) + test_accuracy = eval_results['accuracy'] + test_accuracy_list.append(test_accuracy) + print('Test accuracy after %d epochs is: %.3f' % (epoch, test_accuracy)) + + # Compute the privacy budget expended so far. + if FLAGS.dpsgd: + eps = compute_eps_Poisson(epoch, FLAGS.noise_multiplier, 25000, 512, 1e-5) + mu = compute_mu_Poisson(epoch, FLAGS.noise_multiplier, 25000, 512) + print('For delta=1e-5, the current epsilon is: %.2f' % eps) + print('For delta=1e-5, the current mu is: %.2f' % mu) + + if mu > FLAGS.max_mu: + break + else: + print('Trained with vanilla non-private SGD optimizer') - # Evaluate the model and print results - eval_results = imdb_classifier.evaluate(input_fn=eval_input_fn) - test_accuracy = eval_results['accuracy'] - test_accuracy_list.append(test_accuracy) - print('Test accuracy after %d epochs is: %.3f' % (epoch, test_accuracy)) - - # Compute the privacy budget expended so far. - if FLAGS.dpsgd: - eps = compute_epsP(epoch,FLAGS.noise_multiplier,25000,512,1e-5) - mu= compute_muP(epoch,FLAGS.noise_multiplier,25000,512) - print('For delta=1e-5, the current epsilon is: %.2f' % eps) - print('For delta=1e-5, the current mu is: %.2f' % mu) - - if mu>FLAGS.max_mu: - break - else: - print('Trained with vanilla non-private SGD optimizer') - if __name__ == '__main__': - tf.app.run() + app.run(main) diff --git a/tutorials/movielens_tutorial.py b/tutorials/movielens_tutorial.py index a5c31c2..31ae7d1 100644 --- a/tutorials/movielens_tutorial.py +++ b/tutorials/movielens_tutorial.py @@ -24,48 +24,46 @@ from absl import flags import numpy as np import tensorflow as tf -from scipy.stats import norm +import pandas as pd +from scipy.stats import rankdata +from sklearn.model_selection import train_test_split -from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp -from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent +#from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp +#from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer -from GDprivacy_accountants import * +from tensorflow_privacy.privacy.analysis.gdp_accountant import * #### FLAGS -tf.flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' - 'train with vanilla SGD.') -tf.flags.DEFINE_float('learning_rate', .01, 'Learning rate for training') -tf.flags.DEFINE_float('noise_multiplier', 0.55, - 'Ratio of the standard deviation to the clipping norm') -tf.flags.DEFINE_float('l2_norm_clip', 5, 'Clipping norm') -tf.flags.DEFINE_integer('epochs', 25, 'Number of epochs') -tf.flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') -tf.flags.DEFINE_string('model_dir', None, 'Model directory') +FLAGS = flags.FLAGS +flags.DEFINE_boolean('dpsgd', True, 'If True, train with DP-SGD. If False, ' + 'train with vanilla SGD.') +flags.DEFINE_float('learning_rate', .01, 'Learning rate for training') +flags.DEFINE_float('noise_multiplier', 0.55, + 'Ratio of the standard deviation to the clipping norm') +flags.DEFINE_float('l2_norm_clip', 5, 'Clipping norm') +flags.DEFINE_integer('epochs', 25, 'Number of epochs') +flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') +flags.DEFINE_string('model_dir', None, 'Model directory') -FLAGS = tf.flags.FLAGS -microbatches=10000 -np.random.seed(0) -tf.set_random_seed(0) - -n_users=6040 -n_movies=3706 +microbatches = 10000 def nn_model_fn(features, labels, mode): -# Adapted from https://github.com/hexiangnan/neural_collaborative_filtering + '''NN adapted from github.com/hexiangnan/neural_collaborative_filtering''' n_latent_factors_user = 10 n_latent_factors_movie = 10 n_latent_factors_mf = 5 - - user_input = tf.reshape(features['user'], [-1,1]) - item_input = tf.reshape(features['movie'], [-1,1]) - mf_embedding_user = tf.keras.layers.Embedding(n_users,n_latent_factors_mf,input_length=1) - mf_embedding_item = tf.keras.layers.Embedding(n_movies,n_latent_factors_mf,input_length=1) - mlp_embedding_user = tf.keras.layers.Embedding(n_users,n_latent_factors_user,input_length=1) - mlp_embedding_item = tf.keras.layers.Embedding(n_movies,n_latent_factors_movie,input_length=1) - + user_input = tf.reshape(features['user'], [-1, 1]) + item_input = tf.reshape(features['movie'], [-1, 1]) + + # number of users: 6040; number of movies: 3706 + mf_embedding_user = tf.keras.layers.Embedding(6040, n_latent_factors_mf, input_length=1) + mf_embedding_item = tf.keras.layers.Embedding(3706, n_latent_factors_mf, input_length=1) + mlp_embedding_user = tf.keras.layers.Embedding(6040, n_latent_factors_user, input_length=1) + mlp_embedding_item = tf.keras.layers.Embedding(3706, n_latent_factors_movie, input_length=1) + # GMF part # Flatten the embedding vector as latent features in GMF mf_user_latent = tf.keras.layers.Flatten()(mf_embedding_user(user_input)) @@ -79,138 +77,137 @@ def nn_model_fn(features, labels, mode): mlp_item_latent = tf.keras.layers.Flatten()(mlp_embedding_item(item_input)) # Concatenation of two latent features mlp_vector = tf.keras.layers.concatenate([mlp_user_latent, mlp_item_latent]) - + predict_vector = tf.keras.layers.concatenate([mf_vector, mlp_vector]) - - logits = tf.keras.layers.Dense(5)(predict_vector) + + logits = tf.keras.layers.Dense(5)(predict_vector) # Calculate loss as a vector (to support microbatches in DP-SGD). vector_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) # Define mean of loss across minibatch (for reporting through tf.Estimator). scalar_loss = tf.reduce_mean(vector_loss) - + # Configure the training op (for TRAIN mode). if mode == tf.estimator.ModeKeys.TRAIN: - - if FLAGS.dpsgd: - # Use DP version of GradientDescentOptimizer. Other optimizers are - # available in dp_optimizer. Most optimizers inheriting from - # tf.train.Optimizer should be wrappable in differentially private - # counterparts by calling dp_optimizer.optimizer_from_args(). - optimizer = dp_optimizer.DPAdamGaussianOptimizer( - l2_norm_clip=FLAGS.l2_norm_clip, - noise_multiplier=FLAGS.noise_multiplier, - num_microbatches=microbatches, - learning_rate=FLAGS.learning_rate) - opt_loss = vector_loss - else: - optimizer = tf.train.AdamOptimizer( - learning_rate=FLAGS.learning_rate) - opt_loss = scalar_loss - - global_step = tf.train.get_global_step() - train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) - # In the following, we pass the mean of the loss (scalar_loss) rather than - # the vector_loss because tf.estimator requires a scalar loss. This is only - # used for evaluation and debugging by tf.estimator. The actual loss being - # minimized is opt_loss defined above and passed to optimizer.minimize(). - return tf.estimator.EstimatorSpec(mode=mode, - loss=scalar_loss, - train_op=train_op) + if FLAGS.dpsgd: + # Use DP version of GradientDescentOptimizer. Other optimizers are + # available in dp_optimizer. Most optimizers inheriting from + # tf.train.Optimizer should be wrappable in differentially private + # counterparts by calling dp_optimizer.optimizer_from_args(). + optimizer = dp_optimizer.DPAdamGaussianOptimizer( + l2_norm_clip=FLAGS.l2_norm_clip, + noise_multiplier=FLAGS.noise_multiplier, + num_microbatches=microbatches, + learning_rate=FLAGS.learning_rate) + opt_loss = vector_loss + else: + optimizer = tf.compat.v1.train.AdamOptimizer( + learning_rate=FLAGS.learning_rate) + opt_loss = scalar_loss + + global_step = tf.compat.v1.train.get_global_step() + train_op = optimizer.minimize(loss=opt_loss, global_step=global_step) + # In the following, we pass the mean of the loss (scalar_loss) rather than + # the vector_loss because tf.estimator requires a scalar loss. This is only + # used for evaluation and debugging by tf.estimator. The actual loss being + # minimized is opt_loss defined above and passed to optimizer.minimize(). + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + train_op=train_op) # Add evaluation metrics (for EVAL mode). - elif mode == tf.estimator.ModeKeys.EVAL: - eval_metric_ops = { - 'rmse': - tf.metrics.root_mean_squared_error( - labels=tf.cast(labels, tf.float32), - predictions=tf.tensordot(a=tf.nn.softmax(logits,axis=1),b=tf.constant(np.array([0,1,2,3,4]),dtype=tf.float32),axes=1)) - } - return tf.estimator.EstimatorSpec(mode=mode, - loss=scalar_loss, - eval_metric_ops=eval_metric_ops) + if mode == tf.estimator.ModeKeys.EVAL: + eval_metric_ops = { + 'rmse': + tf.compat.v1.metrics.root_mean_squared_error( + labels=tf.cast(labels, tf.float32), + predictions=tf.tensordot(a=tf.nn.softmax(logits, axis=1), + b=tf.constant(np.array([0, 1, 2, 3, 4]), + dtype=tf.float32), + axes=1)) + } + return tf.estimator.EstimatorSpec(mode=mode, + loss=scalar_loss, + eval_metric_ops=eval_metric_ops) + return None def load_adult(): - import pandas as pd - import numpy as np - - data = pd.read_csv('ratings.dat', sep='::', header=None,names=["userId", "movieId", "rating", "timestamp"]) - n_users=len(set(data['userId'])) - n_movies=len(set(data['movieId'])) - print('number of movie: ',n_movies) - print('number of user: ',n_users) + """Loads MovieLens 1M as from https://grouplens.org/datasets/movielens/1m""" + data = pd.read_csv('ratings.dat', sep='::', header=None, + names=["userId", "movieId", "rating", "timestamp"]) + n_users = len(set(data['userId'])) + n_movies = len(set(data['movieId'])) + print('number of movie: ', n_movies) + print('number of user: ', n_users) # give unique dense movie index to movieId - from scipy.stats import rankdata - data['movieIndex']=rankdata(data['movieId'], method='dense') + data['movieIndex'] = rankdata(data['movieId'], method='dense') # minus one to reduce the minimum value to 0, which is the start of col index - print('number of ratings:',data.shape[0]) - print('percentage of sparsity:',(1-data.shape[0]/n_users/n_movies)*100,'%') + print('number of ratings:', data.shape[0]) + print('percentage of sparsity:', (1-data.shape[0]/n_users/n_movies)*100, '%') + + train, test = train_test_split(data, test_size=0.2, random_state=100) - from sklearn.model_selection import train_test_split - train,test=train_test_split(data,test_size=0.2,random_state=100) - return train.values-1, test.values-1, np.mean(train['rating']) def main(unused_argv): - tf.logging.set_verbosity(3) + '''main''' + tf.compat.v1.logging.set_verbosity(3) - # Load training and test data. - train_data, test_data, mean = load_adult() + # Load training and test data. + train_data, test_data, mean = load_adult() - # Instantiate the tf.Estimator. - adult_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, - model_dir=FLAGS.model_dir) + # Instantiate the tf.Estimator. + ml_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, + model_dir=FLAGS.model_dir) - # Create tf.Estimator input functions for the training and test data. - eval_input_fn = tf.estimator.inputs.numpy_input_fn( - x={'user': test_data[:,0], 'movie': test_data[:,4]}, - y=test_data[:,2], - num_epochs=1, - shuffle=False) + # Create tf.Estimator input functions for the training and test data. + eval_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn( + x={'user': test_data[:, 0], 'movie': test_data[:, 4]}, + y=test_data[:, 2], + num_epochs=1, + shuffle=False) - # Training loop. - steps_per_epoch = 800167 // 10000 - test_accuracy_list = [] - for epoch in range(1, FLAGS.epochs + 1): - np.random.seed(epoch) - for step in range(steps_per_epoch): - tf.set_random_seed(0) - whether=np.random.random_sample(800167)>(1-10000/800167) - subsampling=[i for i in np.arange(800167) if whether[i]] - global microbatches - microbatches=len(subsampling) + # Training loop. + steps_per_epoch = 800167 // 10000 + test_accuracy_list = [] + for epoch in range(1, FLAGS.epochs + 1): + for step in range(steps_per_epoch): + whether = np.random.random_sample(800167) > (1-10000/800167) + subsampling = [i for i in np.arange(800167) if whether[i]] + global microbatches + microbatches = len(subsampling) + + train_input_fn = tf.compat.v1.estimator.inputs.numpy_input_fn( + x={'user': train_data[subsampling, 0], 'movie': train_data[subsampling, 4]}, + y=train_data[subsampling, 2], + batch_size=len(subsampling), + num_epochs=1, + shuffle=True) + # Train the model for one step. + ml_classifier.train(input_fn=train_input_fn, steps=1) + + # Evaluate the model and print results + eval_results = ml_classifier.evaluate(input_fn=eval_input_fn) + test_accuracy = eval_results['rmse'] + test_accuracy_list.append(test_accuracy) + print('Test RMSE after %d epochs is: %.3f' % (epoch, test_accuracy)) + + # Compute the privacy budget expended so far. + if FLAGS.dpsgd: + eps = compute_eps_Poisson(epoch, FLAGS.noise_multiplier, 800167, 10000, 1e-6) + mu = compute_mu_Poisson(epoch, FLAGS.noise_multiplier, 800167, 10000) + print('For delta=1e-6, the current epsilon is: %.2f' % eps) + print('For delta=1e-6, the current mu is: %.2f' % mu) + + if mu > FLAGS.max_mu: + break + else: + print('Trained with vanilla non-private SGD optimizer') - train_input_fn = tf.estimator.inputs.numpy_input_fn( - x={'user': train_data[subsampling,0], 'movie': train_data[subsampling,4]}, - y=train_data[subsampling,2], - batch_size=len(subsampling), - num_epochs=1, - shuffle=True) - # Train the model for one step. - adult_classifier.train(input_fn=train_input_fn, steps=1) - # Evaluate the model and print results - eval_results = adult_classifier.evaluate(input_fn=eval_input_fn) - test_accuracy = eval_results['rmse'] - test_accuracy_list.append(test_accuracy) - print('Test RMSE after %d epochs is: %.3f' % (epoch, test_accuracy)) - - # Compute the privacy budget expended so far. - if FLAGS.dpsgd: - eps = compute_epsP(epoch,FLAGS.noise_multiplier,800167,10000,1e-6) - mu= compute_muP(epoch,FLAGS.noise_multiplier,800167,10000) - print('For delta=1e-6, the current epsilon is: %.2f' % eps) - print('For delta=1e-6, the current mu is: %.2f' % mu) - - if mu>FLAGS.max_mu: - break - else: - print('Trained with vanilla non-private SGD optimizer') - - if __name__ == '__main__': - tf.app.run() + app.run(main) From 0b01471497af0607b81cc493e1be8587b40a35e2 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Sun, 19 Jan 2020 20:28:05 +0800 Subject: [PATCH 06/18] Delete GDprivacy_accountants.py --- .../privacy/analysis/GDprivacy_accountants.py | 59 ------------------- 1 file changed, 59 deletions(-) delete mode 100644 tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py diff --git a/tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py b/tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py deleted file mode 100644 index ba56dac..0000000 --- a/tensorflow_privacy/privacy/analysis/GDprivacy_accountants.py +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright 2015 The TensorFlow Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================= - -r"""This code applies the Dual and Central Limit -Theorem (CLT) to estimate privacy budget of an iterated subsampled -Gaussian Mechanism (by either uniform or Poisson subsampling). -""" - - -import numpy as np -from scipy.stats import norm -from scipy import optimize - -# Total number of examples:N -# batch size:batch_size -# Noise multiplier for DP-SGD/DP-Adam:noise_multiplier -# current epoch:epoch -# Target delta:delta - -# Compute mu from uniform subsampling -def compute_muU(epoch,noise_multi,N,batch_size): - T=epoch*N/batch_size - c=batch_size*np.sqrt(T)/N - return(np.sqrt(2)*c*np.sqrt(np.exp(noise_multi**(-2))*norm.cdf(1.5/noise_multi)+3*norm.cdf(-0.5/noise_multi)-2)) - -# Compute mu from Poisson subsampling -def compute_muP(epoch,noise_multi,N,batch_size): - T=epoch*N/batch_size - return(np.sqrt(np.exp(noise_multi**(-2))-1)*np.sqrt(T)*batch_size/N) - -# Dual between mu-GDP and (epsilon,delta)-DP -def delta_eps_mu(eps,mu): - return norm.cdf(-eps/mu+mu/2)-np.exp(eps)*norm.cdf(-eps/mu-mu/2) - -# inverse Dual -def eps_from_mu(mu,delta): - def f(x): - return delta_eps_mu(x,mu)-delta - return optimize.root_scalar(f, bracket=[0, 500], method='brentq').root - -# inverse Dual of uniform subsampling -def compute_epsU(epoch,noise_multi,N,batch_size,delta): - return(eps_from_mu(compute_muU(epoch,noise_multi,N,batch_size),delta)) - -# inverse Dual of Poisson subsampling -def compute_epsP(epoch,noise_multi,N,batch_size,delta): - return(eps_from_mu(compute_muP(epoch,noise_multi,N,batch_size),delta)) \ No newline at end of file From 2ef5c6e332af1180a62108a4d2815f97f6d3cffd Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Sun, 19 Jan 2020 20:29:37 +0800 Subject: [PATCH 07/18] Add files via upload --- .../privacy/analysis/gdp_accountant.py | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 tensorflow_privacy/privacy/analysis/gdp_accountant.py diff --git a/tensorflow_privacy/privacy/analysis/gdp_accountant.py b/tensorflow_privacy/privacy/analysis/gdp_accountant.py new file mode 100644 index 0000000..5ac82f8 --- /dev/null +++ b/tensorflow_privacy/privacy/analysis/gdp_accountant.py @@ -0,0 +1,61 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= + +r"""This code applies the Dual and Central Limit +Theorem (CLT) to estimate privacy budget of an iterated subsampled +Gaussian Mechanism (by either uniform or Poisson subsampling). +""" + + +import numpy as np +from scipy.stats import norm +from scipy import optimize + +# Total number of examples:N +# batch size:batch_size +# Noise multiplier for DP-SGD/DP-Adam:noise_multiplier +# current epoch:epoch +# Target delta:delta + +def compute_mu_uniform(epoch, noise_multi, N, batch_size): + '''Compute mu from uniform subsampling''' + T = epoch*N/batch_size + c = batch_size*np.sqrt(T)/N + return np.sqrt(2)*c*np.sqrt(np.exp(noise_multi**(-2))*\ + norm.cdf(1.5/noise_multi)+3*norm.cdf(-0.5/noise_multi)-2) + +def compute_mu_Poisson(epoch, noise_multi, N, batch_size): + '''Compute mu from Poisson subsampling''' + T = epoch*N/batch_size + return np.sqrt(np.exp(noise_multi**(-2))-1)*np.sqrt(T)*batch_size/N + +def delta_eps_mu(eps, mu): + '''Dual between mu-GDP and (epsilon, delta)-DP''' + return norm.cdf(-eps/mu+mu/2)-np.exp(eps)*norm.cdf(-eps/mu-mu/2) + +def eps_from_mu(mu, delta): + '''inverse Dual''' + def f(x): + '''reversely solving dual''' + return delta_eps_mu(x, mu) - delta + return optimize.root_scalar(f, bracket=[0, 500], method='brentq').root + +def compute_eps_uniform(epoch, noise_multi, N, batch_size, delta): + '''inverse Dual of uniform subsampling''' + return eps_from_mu(compute_mu_uniform(epoch, noise_multi, N, batch_size), delta) + +def compute_eps_Poisson(epoch, noise_multi, N, batch_size, delta): + '''inverse Dual of Poisson subsampling''' + return eps_from_mu(compute_mu_Poisson(epoch, noise_multi, N, batch_size), delta) From 239827251afd0514c09b3cb3d739c318fdcdfc83 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Wed, 22 Jan 2020 10:28:09 +0800 Subject: [PATCH 08/18] Add files via upload --- tutorials/adult_tutorial.py | 15 +++++++-------- tutorials/imdb_tutorial.py | 14 ++++++-------- tutorials/movielens_tutorial.py | 17 ++++++++--------- 3 files changed, 21 insertions(+), 25 deletions(-) diff --git a/tutorials/adult_tutorial.py b/tutorials/adult_tutorial.py index b92b352..0e6c546 100644 --- a/tutorials/adult_tutorial.py +++ b/tutorials/adult_tutorial.py @@ -27,8 +27,6 @@ import tensorflow as tf import pandas as pd from sklearn.model_selection import KFold -# from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp -# from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer from tensorflow_privacy.privacy.analysis.gdp_accountant import * @@ -46,9 +44,10 @@ flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') flags.DEFINE_string('model_dir', None, 'Model directory') microbatches = 256 +num_examples = 29305 def nn_model_fn(features, labels, mode): - ''' Define CNN architecture using tf.keras.layers.''' + '''Define CNN architecture using tf.keras.layers.''' input_layer = tf.reshape(features['x'], [-1, 123]) y = tf.keras.layers.Dense(16, activation='relu').apply(input_layer) logits = tf.keras.layers.Dense(2).apply(y) @@ -137,12 +136,12 @@ def main(unused_argv): shuffle=False) # Training loop. - steps_per_epoch = 29305 // 256 + steps_per_epoch = num_examples // microbatches test_accuracy_list = [] for epoch in range(1, FLAGS.epochs + 1): for step in range(steps_per_epoch): - whether = np.random.random_sample(29305) > (1-256/29305) - subsampling = [i for i in np.arange(29305) if whether[i]] + whether = np.random.random_sample(num_examples) > (1-microbatches/num_examples) + subsampling = [i for i in np.arange(num_examples) if whether[i]] global microbatches microbatches = len(subsampling) @@ -163,8 +162,8 @@ def main(unused_argv): # Compute the privacy budget expended so far. if FLAGS.dpsgd: - eps = compute_eps_Poisson(epoch, FLAGS.noise_multiplier, 29305, 256, 1e-5) - mu = compute_mu_Poisson(epoch, FLAGS.noise_multiplier, 29305, 256) + eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, 256, 1e-5) + mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, 256) print('For delta=1e-5, the current epsilon is: %.2f' % eps) print('For delta=1e-5, the current mu is: %.2f' % mu) diff --git a/tutorials/imdb_tutorial.py b/tutorials/imdb_tutorial.py index 2b37e7b..babf0ad 100644 --- a/tutorials/imdb_tutorial.py +++ b/tutorials/imdb_tutorial.py @@ -26,8 +26,6 @@ import numpy as np import tensorflow as tf from keras.preprocessing import sequence -#from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp -#from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer from tensorflow_privacy.privacy.analysis.gdp_accountant import * @@ -51,7 +49,7 @@ microbatches = 512 max_features = 10000 # cut texts after this number of words (among top max_features most common words) maxlen = 256 - +num_examples = 25000 def nn_model_fn(features, labels, mode): '''Define NN architecture using tf.keras.layers.''' @@ -139,13 +137,13 @@ def main(unused_argv): shuffle=False) # Training loop. - steps_per_epoch = 25000 // 512 + steps_per_epoch = num_examples // microbatches test_accuracy_list = [] for epoch in range(1, FLAGS.epochs + 1): for step in range(steps_per_epoch): - whether = np.random.random_sample(25000) > (1-512/25000) - subsampling = [i for i in np.arange(25000) if whether[i]] + whether = np.random.random_sample(num_examples) > (1-microbatches/num_examples) + subsampling = [i for i in np.arange(num_examples) if whether[i]] global microbatches microbatches = len(subsampling) @@ -166,8 +164,8 @@ def main(unused_argv): # Compute the privacy budget expended so far. if FLAGS.dpsgd: - eps = compute_eps_Poisson(epoch, FLAGS.noise_multiplier, 25000, 512, 1e-5) - mu = compute_mu_Poisson(epoch, FLAGS.noise_multiplier, 25000, 512) + eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches, 1e-5) + mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches) print('For delta=1e-5, the current epsilon is: %.2f' % eps) print('For delta=1e-5, the current mu is: %.2f' % mu) diff --git a/tutorials/movielens_tutorial.py b/tutorials/movielens_tutorial.py index 31ae7d1..2dc625a 100644 --- a/tutorials/movielens_tutorial.py +++ b/tutorials/movielens_tutorial.py @@ -28,8 +28,6 @@ import pandas as pd from scipy.stats import rankdata from sklearn.model_selection import train_test_split -#from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp -#from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer from tensorflow_privacy.privacy.analysis.gdp_accountant import * @@ -48,6 +46,7 @@ flags.DEFINE_string('model_dir', None, 'Model directory') microbatches = 10000 +num_examples = 800167 def nn_model_fn(features, labels, mode): '''NN adapted from github.com/hexiangnan/neural_collaborative_filtering''' @@ -132,7 +131,7 @@ def nn_model_fn(features, labels, mode): return None -def load_adult(): +def load_movielens(): """Loads MovieLens 1M as from https://grouplens.org/datasets/movielens/1m""" data = pd.read_csv('ratings.dat', sep='::', header=None, names=["userId", "movieId", "rating", "timestamp"]) @@ -158,7 +157,7 @@ def main(unused_argv): tf.compat.v1.logging.set_verbosity(3) # Load training and test data. - train_data, test_data, mean = load_adult() + train_data, test_data, mean = load_movielens() # Instantiate the tf.Estimator. ml_classifier = tf.estimator.Estimator(model_fn=nn_model_fn, @@ -172,12 +171,12 @@ def main(unused_argv): shuffle=False) # Training loop. - steps_per_epoch = 800167 // 10000 + steps_per_epoch = num_examples // microbatches test_accuracy_list = [] for epoch in range(1, FLAGS.epochs + 1): for step in range(steps_per_epoch): - whether = np.random.random_sample(800167) > (1-10000/800167) - subsampling = [i for i in np.arange(800167) if whether[i]] + whether = np.random.random_sample(num_examples) > (1-microbatches/num_examples) + subsampling = [i for i in np.arange(num_examples) if whether[i]] global microbatches microbatches = len(subsampling) @@ -198,8 +197,8 @@ def main(unused_argv): # Compute the privacy budget expended so far. if FLAGS.dpsgd: - eps = compute_eps_Poisson(epoch, FLAGS.noise_multiplier, 800167, 10000, 1e-6) - mu = compute_mu_Poisson(epoch, FLAGS.noise_multiplier, 800167, 10000) + eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches, 1e-6) + mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches) print('For delta=1e-6, the current epsilon is: %.2f' % eps) print('For delta=1e-6, the current mu is: %.2f' % mu) From 7b72e8a11b8b84fb4116ba0ca23ea9f426e6a418 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Wed, 22 Jan 2020 10:29:25 +0800 Subject: [PATCH 09/18] Add files via upload --- .../privacy/analysis/gdp_accountant.py | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tensorflow_privacy/privacy/analysis/gdp_accountant.py b/tensorflow_privacy/privacy/analysis/gdp_accountant.py index 5ac82f8..d7133b4 100644 --- a/tensorflow_privacy/privacy/analysis/gdp_accountant.py +++ b/tensorflow_privacy/privacy/analysis/gdp_accountant.py @@ -30,32 +30,32 @@ from scipy import optimize # Target delta:delta def compute_mu_uniform(epoch, noise_multi, N, batch_size): - '''Compute mu from uniform subsampling''' + '''Compute mu from uniform subsampling.''' T = epoch*N/batch_size c = batch_size*np.sqrt(T)/N return np.sqrt(2)*c*np.sqrt(np.exp(noise_multi**(-2))*\ norm.cdf(1.5/noise_multi)+3*norm.cdf(-0.5/noise_multi)-2) -def compute_mu_Poisson(epoch, noise_multi, N, batch_size): - '''Compute mu from Poisson subsampling''' +def compute_mu_poisson(epoch, noise_multi, N, batch_size): + '''Compute mu from Poisson subsampling.''' T = epoch*N/batch_size return np.sqrt(np.exp(noise_multi**(-2))-1)*np.sqrt(T)*batch_size/N def delta_eps_mu(eps, mu): - '''Dual between mu-GDP and (epsilon, delta)-DP''' + '''Compute dual between mu-GDP and (epsilon, delta)-DP.''' return norm.cdf(-eps/mu+mu/2)-np.exp(eps)*norm.cdf(-eps/mu-mu/2) def eps_from_mu(mu, delta): - '''inverse Dual''' + '''Compute epsilon from mu given delta via inverse dual.''' def f(x): - '''reversely solving dual''' + '''Reversely solve dual by matching delta.''' return delta_eps_mu(x, mu) - delta return optimize.root_scalar(f, bracket=[0, 500], method='brentq').root def compute_eps_uniform(epoch, noise_multi, N, batch_size, delta): - '''inverse Dual of uniform subsampling''' + '''Compute epsilon given delta from inverse dual of uniform subsampling.''' return eps_from_mu(compute_mu_uniform(epoch, noise_multi, N, batch_size), delta) -def compute_eps_Poisson(epoch, noise_multi, N, batch_size, delta): - '''inverse Dual of Poisson subsampling''' - return eps_from_mu(compute_mu_Poisson(epoch, noise_multi, N, batch_size), delta) +def compute_eps_poisson(epoch, noise_multi, N, batch_size, delta): + '''Compute epsilon given delta from inverse dual of Poisson subsampling.''' + return eps_from_mu(compute_mu_poisson(epoch, noise_multi, N, batch_size), delta) From bcbb0c9553d3e15470ef78b18c697d9f8be945e3 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Wed, 22 Jan 2020 10:42:27 +0800 Subject: [PATCH 10/18] Add files via upload --- tutorials/adult_tutorial.py | 9 +++++---- tutorials/imdb_tutorial.py | 10 +++++----- tutorials/movielens_tutorial.py | 10 +++++----- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/tutorials/adult_tutorial.py b/tutorials/adult_tutorial.py index 0e6c546..4867792 100644 --- a/tutorials/adult_tutorial.py +++ b/tutorials/adult_tutorial.py @@ -43,6 +43,7 @@ flags.DEFINE_integer('epochs', 20, 'Number of epochs') flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') flags.DEFINE_string('model_dir', None, 'Model directory') +sampling_batch = 256 microbatches = 256 num_examples = 29305 @@ -136,11 +137,11 @@ def main(unused_argv): shuffle=False) # Training loop. - steps_per_epoch = num_examples // microbatches + steps_per_epoch = num_examples // sampling_batch test_accuracy_list = [] for epoch in range(1, FLAGS.epochs + 1): for step in range(steps_per_epoch): - whether = np.random.random_sample(num_examples) > (1-microbatches/num_examples) + whether = np.random.random_sample(num_examples) > (1-sampling_batch/num_examples) subsampling = [i for i in np.arange(num_examples) if whether[i]] global microbatches microbatches = len(subsampling) @@ -162,8 +163,8 @@ def main(unused_argv): # Compute the privacy budget expended so far. if FLAGS.dpsgd: - eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, 256, 1e-5) - mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, 256) + eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, sampling_batch, 1e-5) + mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, sampling_batch) print('For delta=1e-5, the current epsilon is: %.2f' % eps) print('For delta=1e-5, the current mu is: %.2f' % mu) diff --git a/tutorials/imdb_tutorial.py b/tutorials/imdb_tutorial.py index babf0ad..03a1a34 100644 --- a/tutorials/imdb_tutorial.py +++ b/tutorials/imdb_tutorial.py @@ -43,7 +43,7 @@ flags.DEFINE_integer('epochs', 25, 'Number of epochs') flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') flags.DEFINE_string('model_dir', None, 'Model directory') - +sampling_batch = 512 microbatches = 512 max_features = 10000 @@ -137,12 +137,12 @@ def main(unused_argv): shuffle=False) # Training loop. - steps_per_epoch = num_examples // microbatches + steps_per_epoch = num_examples // sampling_batch test_accuracy_list = [] for epoch in range(1, FLAGS.epochs + 1): for step in range(steps_per_epoch): - whether = np.random.random_sample(num_examples) > (1-microbatches/num_examples) + whether = np.random.random_sample(num_examples) > (1-sampling_batch/num_examples) subsampling = [i for i in np.arange(num_examples) if whether[i]] global microbatches microbatches = len(subsampling) @@ -164,8 +164,8 @@ def main(unused_argv): # Compute the privacy budget expended so far. if FLAGS.dpsgd: - eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches, 1e-5) - mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches) + eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, sampling_batch, 1e-5) + mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, sampling_batch) print('For delta=1e-5, the current epsilon is: %.2f' % eps) print('For delta=1e-5, the current mu is: %.2f' % mu) diff --git a/tutorials/movielens_tutorial.py b/tutorials/movielens_tutorial.py index 2dc625a..af4e189 100644 --- a/tutorials/movielens_tutorial.py +++ b/tutorials/movielens_tutorial.py @@ -44,7 +44,7 @@ flags.DEFINE_integer('epochs', 25, 'Number of epochs') flags.DEFINE_integer('max_mu', 2, 'GDP upper limit') flags.DEFINE_string('model_dir', None, 'Model directory') - +sampling_batch = 10000 microbatches = 10000 num_examples = 800167 @@ -171,11 +171,11 @@ def main(unused_argv): shuffle=False) # Training loop. - steps_per_epoch = num_examples // microbatches + steps_per_epoch = num_examples // sampling_batch test_accuracy_list = [] for epoch in range(1, FLAGS.epochs + 1): for step in range(steps_per_epoch): - whether = np.random.random_sample(num_examples) > (1-microbatches/num_examples) + whether = np.random.random_sample(num_examples) > (1-sampling_batch/num_examples) subsampling = [i for i in np.arange(num_examples) if whether[i]] global microbatches microbatches = len(subsampling) @@ -197,8 +197,8 @@ def main(unused_argv): # Compute the privacy budget expended so far. if FLAGS.dpsgd: - eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches, 1e-6) - mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, microbatches) + eps = compute_eps_poisson(epoch, FLAGS.noise_multiplier, num_examples, sampling_batch, 1e-6) + mu = compute_mu_poisson(epoch, FLAGS.noise_multiplier, num_examples, sampling_batch) print('For delta=1e-6, the current epsilon is: %.2f' % eps) print('For delta=1e-6, the current mu is: %.2f' % mu) From 5d69c692e18d78493ea965ad14024297c3cacce3 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 00:48:16 -0500 Subject: [PATCH 11/18] Move tutorial for adult dataset to research folder --- {tutorials => research}/adult_tutorial.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {tutorials => research}/adult_tutorial.py (100%) diff --git a/tutorials/adult_tutorial.py b/research/adult_tutorial.py similarity index 100% rename from tutorials/adult_tutorial.py rename to research/adult_tutorial.py From f29f101b23d61275a48546518eeb52639df949d9 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 00:49:02 -0500 Subject: [PATCH 12/18] Move tutorial for IMDB dataset to research folder --- {tutorials => research}/imdb_tutorial.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {tutorials => research}/imdb_tutorial.py (100%) diff --git a/tutorials/imdb_tutorial.py b/research/imdb_tutorial.py similarity index 100% rename from tutorials/imdb_tutorial.py rename to research/imdb_tutorial.py From 681a156f3f88f47eba25a3c68b8b78313d64f6ae Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 00:50:42 -0500 Subject: [PATCH 13/18] Rename research/adult_tutorial.py to research/GDP_2019/adult_tutorial.py --- research/{ => GDP_2019}/adult_tutorial.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename research/{ => GDP_2019}/adult_tutorial.py (100%) diff --git a/research/adult_tutorial.py b/research/GDP_2019/adult_tutorial.py similarity index 100% rename from research/adult_tutorial.py rename to research/GDP_2019/adult_tutorial.py From fe82de2cfed77da62add5e755dd93aa1a6a32c28 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 00:50:57 -0500 Subject: [PATCH 14/18] Rename research/imdb_tutorial.py to research/GDP_2019/imdb_tutorial.py --- research/{ => GDP_2019}/imdb_tutorial.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename research/{ => GDP_2019}/imdb_tutorial.py (100%) diff --git a/research/imdb_tutorial.py b/research/GDP_2019/imdb_tutorial.py similarity index 100% rename from research/imdb_tutorial.py rename to research/GDP_2019/imdb_tutorial.py From b9b2e8670fc3e7f0fc9fa56c557a58261a1ebf95 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 09:30:30 -0500 Subject: [PATCH 15/18] Move doc str below functions --- .../privacy/analysis/gdp_accountant.py | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/tensorflow_privacy/privacy/analysis/gdp_accountant.py b/tensorflow_privacy/privacy/analysis/gdp_accountant.py index d7133b4..8c66892 100644 --- a/tensorflow_privacy/privacy/analysis/gdp_accountant.py +++ b/tensorflow_privacy/privacy/analysis/gdp_accountant.py @@ -23,14 +23,14 @@ import numpy as np from scipy.stats import norm from scipy import optimize -# Total number of examples:N -# batch size:batch_size -# Noise multiplier for DP-SGD/DP-Adam:noise_multiplier -# current epoch:epoch -# Target delta:delta def compute_mu_uniform(epoch, noise_multi, N, batch_size): '''Compute mu from uniform subsampling.''' + # Total number of examples:N + # batch size:batch_size + # Noise multiplier for DP-SGD/DP-Adam:noise_multi + # current epoch:epoch + T = epoch*N/batch_size c = batch_size*np.sqrt(T)/N return np.sqrt(2)*c*np.sqrt(np.exp(noise_multi**(-2))*\ @@ -38,6 +38,11 @@ def compute_mu_uniform(epoch, noise_multi, N, batch_size): def compute_mu_poisson(epoch, noise_multi, N, batch_size): '''Compute mu from Poisson subsampling.''' + # Total number of examples:N + # batch size:batch_size + # Noise multiplier for DP-SGD/DP-Adam:noise_multi + # current epoch:epoch + T = epoch*N/batch_size return np.sqrt(np.exp(noise_multi**(-2))-1)*np.sqrt(T)*batch_size/N @@ -47,6 +52,8 @@ def delta_eps_mu(eps, mu): def eps_from_mu(mu, delta): '''Compute epsilon from mu given delta via inverse dual.''' + # Target delta:delta + def f(x): '''Reversely solve dual by matching delta.''' return delta_eps_mu(x, mu) - delta @@ -54,8 +61,20 @@ def eps_from_mu(mu, delta): def compute_eps_uniform(epoch, noise_multi, N, batch_size, delta): '''Compute epsilon given delta from inverse dual of uniform subsampling.''' + # Total number of examples:N + # batch size:batch_size + # Noise multiplier for DP-SGD/DP-Adam:noise_multi + # current epoch:epoch + # Target delta:delta + return eps_from_mu(compute_mu_uniform(epoch, noise_multi, N, batch_size), delta) def compute_eps_poisson(epoch, noise_multi, N, batch_size, delta): '''Compute epsilon given delta from inverse dual of Poisson subsampling.''' + # Total number of examples:N + # batch size:batch_size + # Noise multiplier for DP-SGD/DP-Adam:noise_multi + # current epoch:epoch + # Target delta:delta + return eps_from_mu(compute_mu_poisson(epoch, noise_multi, N, batch_size), delta) From fd51a6e32c25c85a04d50b9c188a18196b42f763 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 09:34:28 -0500 Subject: [PATCH 16/18] Update movielens_tutorial.py Remove empty line in import sections and import explicitly --- tutorials/movielens_tutorial.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tutorials/movielens_tutorial.py b/tutorials/movielens_tutorial.py index af4e189..fb64496 100644 --- a/tutorials/movielens_tutorial.py +++ b/tutorials/movielens_tutorial.py @@ -27,10 +27,9 @@ import tensorflow as tf import pandas as pd from scipy.stats import rankdata from sklearn.model_selection import train_test_split - from tensorflow_privacy.privacy.optimizers import dp_optimizer - -from tensorflow_privacy.privacy.analysis.gdp_accountant import * +from tensorflow_privacy.privacy.analysis.gdp_accountant import compute_eps_poisson +from tensorflow_privacy.privacy.analysis.gdp_accountant import compute_mu_poisson #### FLAGS FLAGS = flags.FLAGS From b13f2f60677eedb075f9f782ed371fbb93271c5d Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 09:35:18 -0500 Subject: [PATCH 17/18] Update adult_tutorial.py --- research/GDP_2019/adult_tutorial.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/research/GDP_2019/adult_tutorial.py b/research/GDP_2019/adult_tutorial.py index 4867792..2b1af75 100644 --- a/research/GDP_2019/adult_tutorial.py +++ b/research/GDP_2019/adult_tutorial.py @@ -28,8 +28,8 @@ import pandas as pd from sklearn.model_selection import KFold from tensorflow_privacy.privacy.optimizers import dp_optimizer - -from tensorflow_privacy.privacy.analysis.gdp_accountant import * +from tensorflow_privacy.privacy.analysis.gdp_accountant import compute_eps_poisson +from tensorflow_privacy.privacy.analysis.gdp_accountant import compute_mu_poisson #### FLAGS FLAGS = flags.FLAGS From d06340e1cf4944faa065644efb5e95950fbaf487 Mon Sep 17 00:00:00 2001 From: woodyx218 Date: Fri, 21 Feb 2020 09:35:47 -0500 Subject: [PATCH 18/18] Update imdb_tutorial.py --- research/GDP_2019/imdb_tutorial.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/research/GDP_2019/imdb_tutorial.py b/research/GDP_2019/imdb_tutorial.py index 03a1a34..cc9ee42 100644 --- a/research/GDP_2019/imdb_tutorial.py +++ b/research/GDP_2019/imdb_tutorial.py @@ -27,9 +27,8 @@ import tensorflow as tf from keras.preprocessing import sequence from tensorflow_privacy.privacy.optimizers import dp_optimizer - -from tensorflow_privacy.privacy.analysis.gdp_accountant import * - +from tensorflow_privacy.privacy.analysis.gdp_accountant import compute_eps_poisson +from tensorflow_privacy.privacy.analysis.gdp_accountant import compute_mu_poisson #### FLAGS FLAGS = flags.FLAGS