{ "cells": [ { "cell_type": "markdown", "id": "65854a65", "metadata": {}, "source": [ "# MLflow with Optuna: Hyperparameter Optimization and Tracking\n", "\n", "A critical part of building production-grade models is ensuring that a given model's parameters are selected to create the best inference set possible. However, the sheer number of combinations and their resultant metrics can become overwhelming to track manually. That's where tools like MLflow and Optuna come into play.\n", "\n", "### Objective: \n", "In this notebook, you'll learn how to integrate MLflow with Optuna for hyperparameter optimization. We'll guide you through the process of:\n", "\n", "* Setting up your environment with MLflow tracking.\n", "* Generating our training and evaluation data sets.\n", "* Defining a partial function that fits a machine learning model.\n", "* Using Optuna for hyperparameter tuning.\n", "* Leveraging child runs within MLflow to keep track of each iteration during the hyperparameter tuning process.\n", "\n", "### Why Optuna?\n", "Optuna is an open-source hyperparameter optimization framework in Python. It provides an efficient approach to searching over hyperparameters, incorporating the latest research and techniques. With its integration into MLflow, every trial can be systematically recorded.\n", "\n", "### Child Runs in MLflow:\n", "One of the core features we will be emphasizing is the concept of 'child runs' in MLflow. When performing hyperparameter tuning, each iteration (or trial) in Optuna can be considered a 'child run'. This allows us to group all the runs under one primary 'parent run', ensuring that the MLflow UI remains organized and interpretable. Each child run will track the specific hyperparameters used and the resulting metrics, providing a consolidated view of the entire optimization process.\n", "\n", "### What's Ahead?\n", "\n", "**Data Preparation**: We'll start by loading and preprocessing our dataset.\n", "\n", "**Model Definition**: Defining a machine learning model that we aim to optimize.\n", "\n", "**Optuna Study**: Setting up an Optuna study to find the best hyperparameters for our model.\n", "\n", "**MLflow Integration**: Tracking each Optuna trial as a child run in MLflow.\n", "\n", "**Analysis**: Reviewing the tracked results in the MLflow UI.\n", "\n", "By the end of this notebook, you'll have hands-on experience in setting up an advanced hyperparameter tuning workflow, emphasizing best practices and clean organization using MLflow and Optuna. \n", "\n", "**Let's dive in!**" ] }, { "cell_type": "code", "execution_count": 1, "id": "db63d641", "metadata": {}, "outputs": [], "source": [ "import math\n", "from datetime import datetime, timedelta\n", "\n", "import numpy as np\n", "import optuna\n", "import pandas as pd\n", "import xgboost as xgb\n", "from sklearn.metrics import mean_squared_error\n", "from sklearn.model_selection import train_test_split\n", "\n", "import mlflow" ] }, { "cell_type": "markdown", "id": "6162d0f3", "metadata": {}, "source": [ "### Configure the tracking server uri\n", "\n", "Depending on where you are running this notebook, your configuration may vary for how you initialize the interface with the MLflow Tracking Server. \n", "\n", "For this example, we're using a locally running tracking server, but other options are available (The easiest is to use the free managed service within [Databricks Free Trial](https://mlflow.org/docs/latest/getting-started/databricks-trial.html)). \n", "\n", "Please see [the guide to running notebooks here](https://www.mlflow.org/docs/latest/getting-started/running-notebooks/) for more information on setting the tracking server uri and configuring access to either managed or self-managed MLflow tracking servers." ] }, { "cell_type": "code", "execution_count": 2, "id": "7f72ec55", "metadata": {}, "outputs": [], "source": [ "# NOTE: review the links mentioned above for guidance on connecting to a managed tracking server, such as the Databricks managed MLflow\n", "\n", "mlflow.set_tracking_uri(\"http://localhost:8080\")" ] }, { "cell_type": "markdown", "id": "8395e8d7", "metadata": {}, "source": [ "### Generate our synthetic training data\n", "\n", "If you've followed along with the introductory tutorial \"Logging your first model with MLflow\", then you're familiar with the apples sales data generator that we created for that tutorial. \n", "\n", "Here, we're expanding upon the data to create a slightly more complex dataset that should have improved correlation effects between the features and the target variable (the demand). " ] }, { "cell_type": "code", "execution_count": 3, "id": "4cc3d2d6", "metadata": {}, "outputs": [], "source": [ "def generate_apple_sales_data_with_promo_adjustment(\n", " base_demand: int = 1000,\n", " n_rows: int = 5000,\n", " competitor_price_effect: float = -50.0,\n", "):\n", " \"\"\"\n", " Generates a synthetic dataset for predicting apple sales demand with multiple\n", " influencing factors.\n", "\n", " This function creates a pandas DataFrame with features relevant to apple sales.\n", " The features include date, average_temperature, rainfall, weekend flag, holiday flag,\n", " promotional flag, price_per_kg, competitor's price, marketing intensity, stock availability,\n", " and the previous day's demand. The target variable, 'demand', is generated based on a\n", " combination of these features with some added noise.\n", "\n", " Args:\n", " base_demand (int, optional): Base demand for apples. Defaults to 1000.\n", " n_rows (int, optional): Number of rows (days) of data to generate. Defaults to 5000.\n", " competitor_price_effect (float, optional): Effect of competitor's price being lower\n", " on our sales. Defaults to -50.\n", "\n", " Returns:\n", " pd.DataFrame: DataFrame with features and target variable for apple sales prediction.\n", "\n", " Example:\n", " >>> df = generate_apple_sales_data_with_promo_adjustment(base_demand=1200, n_rows=6000)\n", " >>> df.head()\n", " \"\"\"\n", "\n", " # Set seed for reproducibility\n", " np.random.seed(9999)\n", "\n", " # Create date range\n", " dates = [datetime.now() - timedelta(days=i) for i in range(n_rows)]\n", " dates.reverse()\n", "\n", " # Generate features\n", " df = pd.DataFrame({\n", " \"date\": dates,\n", " \"average_temperature\": np.random.uniform(10, 35, n_rows),\n", " \"rainfall\": np.random.exponential(5, n_rows),\n", " \"weekend\": [(date.weekday() >= 5) * 1 for date in dates],\n", " \"holiday\": np.random.choice([0, 1], n_rows, p=[0.97, 0.03]),\n", " \"price_per_kg\": np.random.uniform(0.5, 3, n_rows),\n", " \"month\": [date.month for date in dates],\n", " })\n", "\n", " # Introduce inflation over time (years)\n", " df[\"inflation_multiplier\"] = 1 + (df[\"date\"].dt.year - df[\"date\"].dt.year.min()) * 0.03\n", "\n", " # Incorporate seasonality due to apple harvests\n", " df[\"harvest_effect\"] = np.sin(2 * np.pi * (df[\"month\"] - 3) / 12) + np.sin(\n", " 2 * np.pi * (df[\"month\"] - 9) / 12\n", " )\n", "\n", " # Modify the price_per_kg based on harvest effect\n", " df[\"price_per_kg\"] = df[\"price_per_kg\"] - df[\"harvest_effect\"] * 0.5\n", "\n", " # Adjust promo periods to coincide with periods lagging peak harvest by 1 month\n", " peak_months = [4, 10] # months following the peak availability\n", " df[\"promo\"] = np.where(\n", " df[\"month\"].isin(peak_months),\n", " 1,\n", " np.random.choice([0, 1], n_rows, p=[0.85, 0.15]),\n", " )\n", "\n", " # Generate target variable based on features\n", " base_price_effect = -df[\"price_per_kg\"] * 50\n", " seasonality_effect = df[\"harvest_effect\"] * 50\n", " promo_effect = df[\"promo\"] * 200\n", "\n", " df[\"demand\"] = (\n", " base_demand\n", " + base_price_effect\n", " + seasonality_effect\n", " + promo_effect\n", " + df[\"weekend\"] * 300\n", " + np.random.normal(0, 50, n_rows)\n", " ) * df[\"inflation_multiplier\"] # adding random noise\n", "\n", " # Add previous day's demand\n", " df[\"previous_days_demand\"] = df[\"demand\"].shift(1)\n", " df[\"previous_days_demand\"].fillna(method=\"bfill\", inplace=True) # fill the first row\n", "\n", " # Introduce competitor pricing\n", " df[\"competitor_price_per_kg\"] = np.random.uniform(0.5, 3, n_rows)\n", " df[\"competitor_price_effect\"] = (\n", " df[\"competitor_price_per_kg\"] < df[\"price_per_kg\"]\n", " ) * competitor_price_effect\n", "\n", " # Stock availability based on past sales price (3 days lag with logarithmic decay)\n", " log_decay = -np.log(df[\"price_per_kg\"].shift(3) + 1) + 2\n", " df[\"stock_available\"] = np.clip(log_decay, 0.7, 1)\n", "\n", " # Marketing intensity based on stock availability\n", " # Identify where stock is above threshold\n", " high_stock_indices = df[df[\"stock_available\"] > 0.95].index\n", "\n", " # For each high stock day, increase marketing intensity for the next week\n", " for idx in high_stock_indices:\n", " df.loc[idx : min(idx + 7, n_rows - 1), \"marketing_intensity\"] = np.random.uniform(0.7, 1)\n", "\n", " # If the marketing_intensity column already has values, this will preserve them;\n", " # if not, it sets default values\n", " fill_values = pd.Series(np.random.uniform(0, 0.5, n_rows), index=df.index)\n", " df[\"marketing_intensity\"].fillna(fill_values, inplace=True)\n", "\n", " # Adjust demand with new factors\n", " df[\"demand\"] = df[\"demand\"] + df[\"competitor_price_effect\"] + df[\"marketing_intensity\"]\n", "\n", " # Drop temporary columns\n", " df.drop(\n", " columns=[\n", " \"inflation_multiplier\",\n", " \"harvest_effect\",\n", " \"month\",\n", " \"competitor_price_effect\",\n", " \"stock_available\",\n", " ],\n", " inplace=True,\n", " )\n", "\n", " return df" ] }, { "cell_type": "code", "execution_count": 4, "id": "4f2f19e2", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
| \n", " | date | \n", "average_temperature | \n", "rainfall | \n", "weekend | \n", "holiday | \n", "price_per_kg | \n", "promo | \n", "demand | \n", "previous_days_demand | \n", "competitor_price_per_kg | \n", "marketing_intensity | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "2010-01-14 11:52:20.662955 | \n", "30.584727 | \n", "1.199291 | \n", "0 | \n", "0 | \n", "1.726258 | \n", "0 | \n", "851.375336 | \n", "851.276659 | \n", "1.935346 | \n", "0.098677 | \n", "
| 1 | \n", "2010-01-15 11:52:20.662954 | \n", "15.465069 | \n", "1.037626 | \n", "0 | \n", "0 | \n", "0.576471 | \n", "0 | \n", "906.855943 | \n", "851.276659 | \n", "2.344720 | \n", "0.019318 | \n", "
| 2 | \n", "2010-01-16 11:52:20.662954 | \n", "10.786525 | \n", "5.656089 | \n", "1 | \n", "0 | \n", "2.513328 | \n", "0 | \n", "1108.304909 | \n", "906.836626 | \n", "0.998803 | \n", "0.409485 | \n", "
| 3 | \n", "2010-01-17 11:52:20.662953 | \n", "23.648154 | \n", "12.030937 | \n", "1 | \n", "0 | \n", "1.839225 | \n", "0 | \n", "1099.833810 | \n", "1157.895424 | \n", "0.761740 | \n", "0.872803 | \n", "
| 4 | \n", "2010-01-18 11:52:20.662952 | \n", "13.861391 | \n", "4.303812 | \n", "0 | \n", "0 | \n", "1.531772 | \n", "0 | \n", "983.949061 | \n", "1148.961007 | \n", "2.123436 | \n", "0.820779 | \n", "
| ... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "
| 4995 | \n", "2023-09-18 11:52:20.659592 | \n", "21.643051 | \n", "3.821656 | \n", "0 | \n", "0 | \n", "2.391010 | \n", "0 | \n", "1140.210762 | \n", "1563.064082 | \n", "1.504432 | \n", "0.756489 | \n", "
| 4996 | \n", "2023-09-19 11:52:20.659591 | \n", "13.808813 | \n", "1.080603 | \n", "0 | \n", "1 | \n", "0.898693 | \n", "0 | \n", "1285.149505 | \n", "1189.454273 | \n", "1.343586 | \n", "0.742145 | \n", "
| 4997 | \n", "2023-09-20 11:52:20.659590 | \n", "11.698227 | \n", "1.911000 | \n", "0 | \n", "0 | \n", "2.839860 | \n", "0 | \n", "965.171368 | \n", "1284.407359 | \n", "2.771896 | \n", "0.742145 | \n", "
| 4998 | \n", "2023-09-21 11:52:20.659589 | \n", "18.052081 | \n", "1.000521 | \n", "0 | \n", "0 | \n", "1.188440 | \n", "0 | \n", "1368.369501 | \n", "1014.429223 | \n", "2.564075 | \n", "0.742145 | \n", "
| 4999 | \n", "2023-09-22 11:52:20.659584 | \n", "17.017294 | \n", "0.650213 | \n", "0 | \n", "0 | \n", "2.131694 | \n", "0 | \n", "1261.301286 | \n", "1367.627356 | \n", "0.785727 | \n", "0.833140 | \n", "
5000 rows × 11 columns
\n", "| \n", " | date | \n", "average_temperature | \n", "rainfall | \n", "weekend | \n", "holiday | \n", "price_per_kg | \n", "promo | \n", "demand | \n", "previous_days_demand | \n", "competitor_price_per_kg | \n", "marketing_intensity | \n", "predicted_demand | \n", "
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", "2010-01-14 11:52:20.662955 | \n", "30.584727 | \n", "1.199291 | \n", "0 | \n", "0 | \n", "1.726258 | \n", "0 | \n", "851.375336 | \n", "851.276659 | \n", "1.935346 | \n", "0.098677 | \n", "953.708496 | \n", "
| 1 | \n", "2010-01-15 11:52:20.662954 | \n", "15.465069 | \n", "1.037626 | \n", "0 | \n", "0 | \n", "0.576471 | \n", "0 | \n", "906.855943 | \n", "851.276659 | \n", "2.344720 | \n", "0.019318 | \n", "1013.409973 | \n", "
| 2 | \n", "2010-01-16 11:52:20.662954 | \n", "10.786525 | \n", "5.656089 | \n", "1 | \n", "0 | \n", "2.513328 | \n", "0 | \n", "1108.304909 | \n", "906.836626 | \n", "0.998803 | \n", "0.409485 | \n", "1152.382446 | \n", "
| 3 | \n", "2010-01-17 11:52:20.662953 | \n", "23.648154 | \n", "12.030937 | \n", "1 | \n", "0 | \n", "1.839225 | \n", "0 | \n", "1099.833810 | \n", "1157.895424 | \n", "0.761740 | \n", "0.872803 | \n", "1352.879272 | \n", "
| 4 | \n", "2010-01-18 11:52:20.662952 | \n", "13.861391 | \n", "4.303812 | \n", "0 | \n", "0 | \n", "1.531772 | \n", "0 | \n", "983.949061 | \n", "1148.961007 | \n", "2.123436 | \n", "0.820779 | \n", "1121.233032 | \n", "
| ... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "... | \n", "
| 4995 | \n", "2023-09-18 11:52:20.659592 | \n", "21.643051 | \n", "3.821656 | \n", "0 | \n", "0 | \n", "2.391010 | \n", "0 | \n", "1140.210762 | \n", "1563.064082 | \n", "1.504432 | \n", "0.756489 | \n", "1070.676636 | \n", "
| 4996 | \n", "2023-09-19 11:52:20.659591 | \n", "13.808813 | \n", "1.080603 | \n", "0 | \n", "1 | \n", "0.898693 | \n", "0 | \n", "1285.149505 | \n", "1189.454273 | \n", "1.343586 | \n", "0.742145 | \n", "1156.580688 | \n", "
| 4997 | \n", "2023-09-20 11:52:20.659590 | \n", "11.698227 | \n", "1.911000 | \n", "0 | \n", "0 | \n", "2.839860 | \n", "0 | \n", "965.171368 | \n", "1284.407359 | \n", "2.771896 | \n", "0.742145 | \n", "1086.527710 | \n", "
| 4998 | \n", "2023-09-21 11:52:20.659589 | \n", "18.052081 | \n", "1.000521 | \n", "0 | \n", "0 | \n", "1.188440 | \n", "0 | \n", "1368.369501 | \n", "1014.429223 | \n", "2.564075 | \n", "0.742145 | \n", "1085.064087 | \n", "
| 4999 | \n", "2023-09-22 11:52:20.659584 | \n", "17.017294 | \n", "0.650213 | \n", "0 | \n", "0 | \n", "2.131694 | \n", "0 | \n", "1261.301286 | \n", "1367.627356 | \n", "0.785727 | \n", "0.833140 | \n", "1047.954102 | \n", "
5000 rows × 12 columns
\n", "