Skip to content

Instantly share code, notes, and snippets.

@HemersonTacon
Last active November 1, 2018 18:00
Show Gist options
  • Save HemersonTacon/e2793be37e7f694625d1b178eb36be39 to your computer and use it in GitHub Desktop.
Save HemersonTacon/e2793be37e7f694625d1b178eb36be39 to your computer and use it in GitHub Desktop.
import os
import matplotlib.pyplot as plt
def plot_and_save(history, name, show_plots=False, folder="imgs"):
"""
Create a charts comparing accuracy and loss of training and validation
phases for each epoch
Args:
history (Hisotry): The History object returned from a fit function
name (str): Prefix name for the created images
show_plots (bool): Plot charts when True, otherwise just save on disk
folder (str): Local folder name to save created images. If doesn't
exists, it will be created
Returns:
str[]: Names of created images
Raises:
None: This function don't raise any exception
"""
plt.switch_backend('agg')
os.makedirs(folder, exist_ok=True)
# summarize history for accuracy
fig, ax = plt.subplots()
plt.plot(history.history['acc'])
if 'val_acc' in history.history:
plt.plot(history.history['val_acc'])
plt.legend(['train', 'test'])
else:
plt.legend(['train'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
if show_plots:
plt.show()
# summarize history for loss
fig2, ax2 = plt.subplots()
plt.plot(history.history['loss'])
if 'val_acc' in history.history:
plt.plot(history.history['val_loss'])
plt.legend(['train', 'test'])
else:
plt.legend(['train'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
if show_plots:
plt.show()
fig.savefig(os.path.join(folder, name[:-3]+"_acc.jpg"))
fig2.savefig(os.path.join(folder, name[:-3]+"_loss.jpg")
return name[:-3]+"_acc.jpg", name[:-3]+"_loss.jpg"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment