plot_metrics.py 2.0 KB

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