helper.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. '''
  2. Created on Aug 19, 2016
  3. @author: Xiang Wang (xiangwang@u.nus.edu)
  4. '''
  5. __author__ = "xiangwang"
  6. import os
  7. import re
  8. def txt2list(file_src):
  9. orig_file = open(file_src, "r")
  10. lines = orig_file.readlines()
  11. return lines
  12. def ensureDir(dir_path):
  13. d = os.path.dirname(dir_path)
  14. if not os.path.exists(d):
  15. os.makedirs(d)
  16. def uni2str(unicode_str):
  17. return str(unicode_str.encode('ascii', 'ignore')).replace('\n', '').strip()
  18. def hasNumbers(inputString):
  19. return bool(re.search(r'\d', inputString))
  20. def delMultiChar(inputString, chars):
  21. for ch in chars:
  22. inputString = inputString.replace(ch, '')
  23. return inputString
  24. def merge_two_dicts(x, y):
  25. z = x.copy() # start with x's keys and values
  26. z.update(y) # modifies z with y's keys and values & returns None
  27. return z
  28. def early_stopping(log_value, best_value, stopping_step, expected_order='acc', flag_step=100):
  29. # early stopping strategy:
  30. assert expected_order in ['acc', 'dec']
  31. if (expected_order == 'acc' and log_value >= best_value) or (expected_order == 'dec' and log_value <= best_value):
  32. stopping_step = 0
  33. best_value = log_value
  34. else:
  35. stopping_step += 1
  36. if stopping_step >= flag_step:
  37. print("Early stopping is trigger at step: {} log:{}".format(flag_step, log_value))
  38. should_stop = True
  39. else:
  40. should_stop = False
  41. return best_value, stopping_step, should_stop