|
| 1 | +import pandas as pd |
| 2 | +import torch |
| 3 | +import torch.nn as nn |
| 4 | +from sklearn.datasets import load_iris |
| 5 | +from sklearn.model_selection import train_test_split |
| 6 | + |
| 7 | +import mlflow |
| 8 | +import mlflow.pytorch |
| 9 | +from mlflow.entities import Dataset |
| 10 | + |
| 11 | +mlflow.set_tracking_uri("https://ard-mlflow.slac.stanford.edu") |
| 12 | + |
| 13 | +# Helper function to prepare data |
| 14 | +def prepare_data(df): |
| 15 | + X = torch.tensor(df.iloc[:, :-1].values, dtype=torch.float32) |
| 16 | + y = torch.tensor(df.iloc[:, -1].values, dtype=torch.long) |
| 17 | + return X, y |
| 18 | + |
| 19 | + |
| 20 | +# Helper function to compute accuracy |
| 21 | +def compute_accuracy(model, X, y): |
| 22 | + with torch.no_grad(): |
| 23 | + outputs = model(X) |
| 24 | + _, predicted = torch.max(outputs, 1) |
| 25 | + accuracy = (predicted == y).sum().item() / y.size(0) |
| 26 | + return accuracy |
| 27 | + |
| 28 | + |
| 29 | +# Define a basic PyTorch classifier |
| 30 | +class IrisClassifier(nn.Module): |
| 31 | + def __init__(self, input_size, hidden_size, output_size): |
| 32 | + super().__init__() |
| 33 | + self.fc1 = nn.Linear(input_size, hidden_size) |
| 34 | + self.relu = nn.ReLU() |
| 35 | + self.fc2 = nn.Linear(hidden_size, output_size) |
| 36 | + |
| 37 | + def forward(self, x): |
| 38 | + x = self.fc1(x) |
| 39 | + x = self.relu(x) |
| 40 | + x = self.fc2(x) |
| 41 | + return x |
| 42 | + |
| 43 | + |
| 44 | +# Load Iris dataset and prepare the DataFrame |
| 45 | +iris = load_iris() |
| 46 | +iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names) |
| 47 | +iris_df["target"] = iris.target |
| 48 | + |
| 49 | +# Split into training and testing datasets |
| 50 | +train_df, test_df = train_test_split(iris_df, test_size=0.2, random_state=42) |
| 51 | + |
| 52 | +# Prepare training data |
| 53 | +train_dataset = mlflow.data.from_pandas(train_df, name="train") |
| 54 | +X_train, y_train = prepare_data(train_dataset.df) |
| 55 | + |
| 56 | +# Define the PyTorch model and move it to the device |
| 57 | +input_size = X_train.shape[1] |
| 58 | +hidden_size = 16 |
| 59 | +output_size = len(iris.target_names) |
| 60 | +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 61 | +scripted_model = IrisClassifier(input_size, hidden_size, output_size).to(device) |
| 62 | +scripted_model = torch.jit.script(scripted_model) |
| 63 | + |
| 64 | +# Start a run to represent the training job |
| 65 | +with mlflow.start_run() as run: |
| 66 | + # Load the training dataset with MLflow. We will link training metrics to this dataset. |
| 67 | + train_dataset: Dataset = mlflow.data.from_pandas(train_df, name="train") |
| 68 | + X_train, y_train = prepare_data(train_dataset.df) |
| 69 | + |
| 70 | + criterion = nn.CrossEntropyLoss() |
| 71 | + optimizer = torch.optim.Adam(scripted_model.parameters(), lr=0.01) |
| 72 | + |
| 73 | + for epoch in range(101): |
| 74 | + X_train = X_train.to(device) |
| 75 | + y_train = y_train.to(device) |
| 76 | + out = scripted_model(X_train) |
| 77 | + loss = criterion(out, y_train) |
| 78 | + optimizer.zero_grad() |
| 79 | + loss.backward() |
| 80 | + optimizer.step() |
| 81 | + |
| 82 | + # Log a checkpoint with metrics every 10 epochs |
| 83 | + if epoch % 10 == 0: |
| 84 | + # Each newly created LoggedModel checkpoint is linked with its name and step |
| 85 | + model_info = mlflow.pytorch.log_model( |
| 86 | + pytorch_model=scripted_model, |
| 87 | + name=f"torch-iris-{epoch}", |
| 88 | + step=epoch, |
| 89 | + input_example=X_train.numpy(), |
| 90 | + ) |
| 91 | + # log params to the run, LoggedModel inherits those params |
| 92 | + mlflow.log_params( |
| 93 | + params={ |
| 94 | + "n_layers": 3, |
| 95 | + "activation": "ReLU", |
| 96 | + "criterion": "CrossEntropyLoss", |
| 97 | + "optimizer": "Adam", |
| 98 | + } |
| 99 | + ) |
| 100 | + # Log metric on training dataset at step and link to LoggedModel |
| 101 | + mlflow.log_metric( |
| 102 | + key="accuracy", |
| 103 | + value=compute_accuracy(scripted_model, X_train, y_train), |
| 104 | + step=epoch, |
| 105 | + model_id=model_info.model_id, |
| 106 | + dataset=train_dataset, |
| 107 | + ) |
| 108 | + |
| 109 | +ranked_checkpoints = mlflow.search_logged_models( |
| 110 | + filter_string=f"source_run_id='{run.info.run_id}'", |
| 111 | + order_by=[{"field_name": "metrics.accuracy", "ascending": False}], |
| 112 | + output_format="list", |
| 113 | +) |
| 114 | + |
| 115 | +best_checkpoint = ranked_checkpoints[0] |
| 116 | +print(f"Best model: {best_checkpoint}") |
| 117 | +print(best_checkpoint.metrics) |
| 118 | + |
| 119 | +# Best model: <LoggedModel: artifact_location='file:///Users/serena.ruan/Documents/repos/mlflow-3-doc/mlruns/0/models/41bd5a16-25a6-447b-90e0-0f7b7e5cb6cf/artifacts', creation_timestamp=1743734069924, experiment_id='0', last_updated_timestamp=1743734075018, metrics=[<Metric: dataset_digest='1f1c13b5', dataset_name='train', key='accuracy', model_id='41bd5a16-25a6-447b-90e0-0f7b7e5cb6cf', run_id='12f143a7fda1461e9240d7ffad4ea5bd', step=100, timestamp=1743734075029, value=0.975>], model_id='41bd5a16-25a6-447b-90e0-0f7b7e5cb6cf', model_type='', model_uri='models:/41bd5a16-25a6-447b-90e0-0f7b7e5cb6cf', name='torch-iris-100', params={'activation': 'ReLU', |
| 120 | +# 'criterion': 'CrossEntropyLoss', |
| 121 | +# 'n_layers': '3', |
| 122 | +# 'optimizer': 'Adam'}, source_run_id='12f143a7fda1461e9240d7ffad4ea5bd', status=<LoggedModelStatus.READY: 'READY'>, status_message='', tags={'mlflow.source.git.commit': '7324c807f07a1766d4b951733e3d723504b4576e', |
| 123 | +# 'mlflow.source.name': 'a.py', |
| 124 | +# 'mlflow.source.type': 'LOCAL', |
| 125 | +# 'mlflow.user': 'serena.ruan'}> |
| 126 | +# [<Metric: dataset_digest='1f1c13b5', dataset_name='train', key='accuracy', model_id='41bd5a16-25a6-447b-90e0-0f7b7e5cb6cf', run_id='12f143a7fda1461e9240d7ffad4ea5bd', step=100, timestamp=1743734075029, value=0.975>] |
| 127 | + |
| 128 | +worst_checkpoint = ranked_checkpoints[-1] |
| 129 | +print(f"Worst model: {worst_checkpoint}") |
| 130 | +print(worst_checkpoint.metrics) |
| 131 | + |
| 132 | +# Worst model: <LoggedModel: artifact_location='file:///Users/serena.ruan/Documents/repos/mlflow-3-doc/mlruns/0/models/0d789084-9a3b-4b85-9d43-6a148c014b7e/artifacts', creation_timestamp=1743734016290, experiment_id='0', last_updated_timestamp=1743734022728, metrics=[<Metric: dataset_digest='1f1c13b5', dataset_name='train', key='accuracy', model_id='0d789084-9a3b-4b85-9d43-6a148c014b7e', run_id='12f143a7fda1461e9240d7ffad4ea5bd', step=0, timestamp=1743734022737, value=0.3>], model_id='0d789084-9a3b-4b85-9d43-6a148c014b7e', model_type='', model_uri='models:/0d789084-9a3b-4b85-9d43-6a148c014b7e', name='torch-iris-0', params={}, source_run_id='12f143a7fda1461e9240d7ffad4ea5bd', status=<LoggedModelStatus.READY: 'READY'>, status_message='', tags={'mlflow.source.git.commit': '7324c807f07a1766d4b951733e3d723504b4576e', |
| 133 | +# 'mlflow.source.name': 'a.py', |
| 134 | +# 'mlflow.source.type': 'LOCAL', |
| 135 | +# 'mlflow.user': 'serena.ruan'}> |
| 136 | +# [<Metric: dataset_digest='1f1c13b5', dataset_name='train', key='accuracy', model_id='0d789084-9a3b-4b85-9d43-6a148c014b7e', run_id='12f143a7fda1461e9240d7ffad4ea5bd', step=0, timestamp=1743734022737, value=0.3>] |
| 137 | + |
0 commit comments