inference.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright 2016 Google Inc. 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. """Class for variational inference."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import tensorflow as tf
  20. sg = tf.contrib.bayesflow.stochastic_graph
  21. distributions = tf.contrib.distributions
  22. class VariationalInference(object):
  23. """VariationalInference class."""
  24. def __init__(self, model, variational, data):
  25. """Initializes the VariationalInference class.
  26. Args:
  27. model: the probability model. an object with a log_prob and sample method.
  28. variational: the variational family for the model. an object with
  29. log_prob and sampling methods.
  30. data: the observations we use to fit the model.
  31. """
  32. self.model = model
  33. self.variational = variational
  34. self.data = data
  35. def build_graph(self):
  36. """Builds the graph for variational inference."""
  37. q_samples = self.variational.sample
  38. log_p = self.model.log_prob(q_samples, self.data['x'])
  39. log_q = self.variational.log_prob(q_samples)
  40. elbo = log_p - log_q
  41. if elbo.get_shape().ndims > 1:
  42. # first dimension is samples, second is batch_size
  43. self.scalar_elbo = tf.reduce_mean(tf.reduce_mean(elbo, 0), 0)
  44. else:
  45. self.scalar_elbo = tf.reduce_sum(elbo, 0)
  46. self.elbo = elbo
  47. self.log_p = log_p
  48. self.log_q = log_q