""" A series of helper functions used throughout the course. If a function gets defined once and could be used over and over, it'll go in here. """ import torch import matplotlib.pyplot as plt from torch import nn # Plot linear data or training and test and predictions (optional) def plot_predictions(train_data, train_labels, test_data, test_labels, predictions=None): """ Plots linear training data and test data and compares predictions. """ plt.figure(figsize=(10, 7)) # Plot training data in blue plt.scatter(train_data, train_labels, c="b", s=4, label="Training data") # Plot test data in green plt.scatter(test_data, test_labels, c="g", s=4, label="Testing data") if predictions is not None: # Plot the predictions in red (predictions were made on the test data) plt.scatter(test_data, predictions, c="r", s=4, label="Predictions") # Show the legend plt.legend(prop={"size": 14}); # Calculate accuracy (a classification metric) def accuracy_fn(y_true, y_pred): """Calculates accuracy between truth labels and predictions. Args: y_true (torch.Tensor): Truth labels for predictions. y_pred (torch.Tensor): Predictions to be compared to predictions. Returns: [torch.float]: Accuracy value between y_true and y_pred, e.g. 78.45 """ correct = torch.eq(y_true, y_pred).sum().item() acc = (correct / len(y_pred)) * 100 return acc def print_train_time(start, end, device=None): """Prints difference between start and end time. Args: start (float): Start time of computation (preferred in timeit format). end (float): End time of computation. device ([type], optional): Device that compute is running on. Defaults to None. Returns: float: time between start and end in seconds (higher is longer). """ total_time = end - start print(f"\nTrain time on {device}: {total_time:.3f} seconds") return total_time # Plot loss curves of a model def plot_loss_curves(results): """Plots training curves of a results dictionary. Args: results (dict): dictionary containing list of values, e.g. {"train_loss": [...], "train_acc": [...], "test_loss": [...], "test_acc": [...]} """ loss = results["train_loss"] test_loss = results["test_loss"] accuracy = results["train_acc"] test_accuracy = results["test_acc"] epochs = range(len(results["train_loss"])) plt.figure(figsize=(15, 7)) # Plot loss plt.subplot(1, 2, 1) plt.plot(epochs, loss, label="train_loss") plt.plot(epochs, test_loss, label="test_loss") plt.title("Loss") plt.xlabel("Epochs") plt.legend() # Plot accuracy plt.subplot(1, 2, 2) plt.plot(epochs, accuracy, label="train_accuracy") plt.plot(epochs, test_accuracy, label="test_accuracy") plt.title("Accuracy") plt.xlabel("Epochs") plt.legend()