tf_lib.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. """Utility functions for working with TensorFlow."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import ast
  20. class HParams(object):
  21. """Creates an object for passing around hyperparameter values.
  22. Use the parse method to overwrite the default hyperparameters with values
  23. passed in as a string representation of a Python dictionary mapping
  24. hyperparameters to values.
  25. Ex.
  26. hparams = tf_lib.HParams(batch_size=128, hidden_size=256)
  27. hparams.parse('{"hidden_size":512}')
  28. assert hparams.batch_size == 128
  29. assert hparams.hidden_size == 512
  30. """
  31. def __init__(self, **init_hparams):
  32. object.__setattr__(self, 'keyvals', init_hparams)
  33. def __getattr__(self, key):
  34. return self.keyvals.get(key)
  35. def __setattr__(self, key, value):
  36. """Returns None if key does not exist."""
  37. self.keyvals[key] = value
  38. def parse(self, string):
  39. new_hparams = ast.literal_eval(string)
  40. return HParams(**dict(self.keyvals, **new_hparams))
  41. def values(self):
  42. return self.keyvals