dp_pca.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Differentially private optimizers.
  16. """
  17. import tensorflow as tf
  18. from differential_privacy.dp_sgd.dp_optimizer import sanitizer as san
  19. def ComputeDPPrincipalProjection(data, projection_dims,
  20. sanitizer, eps_delta, sigma):
  21. """Compute differentially private projection.
  22. Args:
  23. data: the input data, each row is a data vector.
  24. projection_dims: the projection dimension.
  25. sanitizer: the sanitizer used for acheiving privacy.
  26. eps_delta: (eps, delta) pair.
  27. sigma: if not None, use noise sigma; otherwise compute it using
  28. eps_delta pair.
  29. Returns:
  30. A projection matrix with projection_dims columns.
  31. """
  32. eps, delta = eps_delta
  33. # Normalize each row.
  34. normalized_data = tf.nn.l2_normalize(data, 1)
  35. covar = tf.matmul(tf.transpose(normalized_data), normalized_data)
  36. saved_shape = tf.shape(covar)
  37. num_examples = tf.slice(tf.shape(data), [0], [1])
  38. if eps > 0:
  39. # Since the data is already normalized, there is no need to clip
  40. # the covariance matrix.
  41. assert delta > 0
  42. saned_covar = sanitizer.sanitize(
  43. tf.reshape(covar, [1, -1]), eps_delta, sigma=sigma,
  44. option=san.ClipOption(1.0, False), num_examples=num_examples)
  45. saned_covar = tf.reshape(saned_covar, saved_shape)
  46. # Symmetrize saned_covar. This also reduces the noise variance.
  47. saned_covar = 0.5 * (saned_covar + tf.transpose(saned_covar))
  48. else:
  49. saned_covar = covar
  50. # Compute the eigen decomposition of the covariance matrix, and
  51. # return the top projection_dims eigen vectors, represented as columns of
  52. # the projection matrix.
  53. eigvals, eigvecs = tf.self_adjoint_eig(saned_covar)
  54. _, topk_indices = tf.nn.top_k(eigvals, projection_dims)
  55. topk_indices = tf.reshape(topk_indices, [projection_dims])
  56. # Gather and return the corresponding eigenvectors.
  57. return tf.transpose(tf.gather(tf.transpose(eigvecs), topk_indices))