Adapted to Movie lens dataset
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helper.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """
  2. Helper functions.
  3. """
  4. import os
  5. import json
  6. import argparse
  7. ### IO
  8. def check_dir(d):
  9. if not os.path.exists(d):
  10. print("Directory {} does not exist. Exit.".format(d))
  11. exit(1)
  12. def check_files(files):
  13. for f in files:
  14. if f is not None and not os.path.exists(f):
  15. print("File {} does not exist. Exit.".format(f))
  16. exit(1)
  17. def ensure_dir(d, verbose=True):
  18. if not os.path.exists(d):
  19. if verbose:
  20. print("Directory {} do not exist; creating...".format(d))
  21. os.makedirs(d)
  22. def save_config(config, path, verbose=True):
  23. with open(path, 'w') as outfile:
  24. json.dump(config, outfile, indent=2)
  25. if verbose:
  26. print("Config saved to file {}".format(path))
  27. return config
  28. def load_config(path, verbose=True):
  29. with open(path) as f:
  30. config = json.load(f)
  31. if verbose:
  32. print("Config loaded from file {}".format(path))
  33. return config
  34. def print_config(config):
  35. info = "Running with the following configs:\n"
  36. for k, v in config.items():
  37. info += "\t{} : {}\n".format(k, str(v))
  38. print("\n" + info + "\n")
  39. return
  40. class FileLogger(object):
  41. """
  42. A file logger that opens the file periodically and write to it.
  43. """
  44. def __init__(self, filename, header=None):
  45. self.filename = filename
  46. if os.path.exists(filename):
  47. # remove the old file
  48. os.remove(filename)
  49. if header is not None:
  50. with open(filename, 'w') as out:
  51. print(header, file=out)
  52. def log(self, message):
  53. with open(self.filename, 'a') as out:
  54. print(message)
  55. print(message, file=out)