plot_metrics.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import json
  2. import matplotlib.pyplot as plt
  3. import argparse
  4. import os
  5. def plot_metric(data, metric_name, x_label, y_label, title, colors):
  6. plt.figure(figsize=(7, 6))
  7. plt.plot(data[f'train_epoch_{metric_name}'], label=f'Train Epoch {metric_name.capitalize()}', color=colors[0])
  8. plt.plot(data[f'val_epoch_{metric_name}'], label=f'Validation Epoch {metric_name.capitalize()}', color=colors[1])
  9. plt.xlabel(x_label)
  10. plt.ylabel(y_label)
  11. plt.title(f'Train and Validation Epoch {title}')
  12. plt.legend()
  13. plt.tight_layout()
  14. def plot_single_metric_by_step(data, metric_name, x_label, y_label, title, color):
  15. plt.plot(data[f'{metric_name}'], label=f'{title}', color=color)
  16. plt.xlabel(x_label)
  17. plt.ylabel(y_label)
  18. plt.title(title)
  19. plt.legend()
  20. plt.tight_layout()
  21. def plot_metrics_by_step(data, metric_name, x_label, y_label, colors):
  22. plt.figure(figsize=(14, 6))
  23. plt.subplot(1, 2, 1)
  24. plot_single_metric_by_step(data, f'train_step_{metric_name}', x_label, y_label, f'Train Step {metric_name.capitalize()}', colors[0])
  25. plt.subplot(1, 2, 2)
  26. plot_single_metric_by_step(data, f'val_step_{metric_name}', x_label, y_label, f'Validation Step {metric_name.capitalize()}', colors[1])
  27. plt.tight_layout()
  28. def plot_metrics(file_path):
  29. if not os.path.exists(file_path):
  30. print(f"File {file_path} does not exist.")
  31. return
  32. with open(file_path, 'r') as f:
  33. try:
  34. data = json.load(f)
  35. except json.JSONDecodeError:
  36. print("Invalid JSON file.")
  37. return
  38. directory = os.path.dirname(file_path)
  39. filename_prefix = os.path.basename(file_path).split('.')[0]
  40. plot_metric(data, 'loss', 'Epoch', 'Loss', 'Loss', ['b', 'r'])
  41. plt.savefig(os.path.join(directory, f"{filename_prefix}_train_and_validation_loss.png"))
  42. plt.close()
  43. plot_metric(data, 'perplexity', 'Epoch', 'Perplexity', 'Perplexity', ['g', 'm'])
  44. plt.savefig(os.path.join(directory, f"{filename_prefix}_train_and_validation_perplexity.png"))
  45. plt.close()
  46. plot_metrics_by_step(data, 'loss', 'Step', 'Loss', ['b', 'r'])
  47. plt.savefig(os.path.join(directory, f"{filename_prefix}_train_and_validation_loss_by_step.png"))
  48. plt.close()
  49. plot_metrics_by_step(data, 'perplexity', 'Step', 'Loss', ['g', 'm'])
  50. plt.savefig(os.path.join(directory, f"{filename_prefix}_train_and_validation_perplexity_by_step.png"))
  51. plt.close()
  52. if __name__ == "__main__":
  53. parser = argparse.ArgumentParser(description='Plot metrics from JSON file.')
  54. parser.add_argument('--file_path', required=True, type=str, help='Path to the metrics JSON file.')
  55. args = parser.parse_args()
  56. plot_metrics(args.file_path)