Demand prediction and Optimization with scikit-learn & Amplpy#
Description: In this notebook, we will:
Train a linear regression model to predict product demand based on price and marketing spend.
Use the predicted demand in a simple optimization model with AMPL to determine the optimal production quantity that maximizes profit under given constraints.
Tags: amplpy, machine-learning, scikit-learn, gurobi
Notebook author: Marcos Dominguez Velad <marcos@ampl.com>
Model author: N/A
# Install dependencies
%pip install -q amplpy numpy scikit-learn
# Google Colab & Kaggle integration
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["gurobi"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
Train the Demand Prediction Model#
We’ll start by using historical data to train a linear regression model that predicts demand based on price and marketing spend.
from sklearn.linear_model import LinearRegression
import numpy as np
# Historical dataset: [price, marketing spend] → demand
X = np.array([[10, 1000], [12, 1500], [14, 800], [13, 1200], [11, 1100]])
y = np.array([120, 115, 90, 110, 118]) # Observed demand
# Fit linear regression model
model = LinearRegression()
model.fit(X, y)
LinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| fit_intercept | True | |
| copy_X | True | |
| tol | 1e-06 | |
| n_jobs | None | |
| positive | False |
Predict demand for a new case#
Now we use the trained model to predict the demand for a product given a specific price and marketing spend.
# New input values
price = 13
marketing_spend = 1300
# Predict demand
predicted_demand = model.predict([[price, marketing_spend]])[0]
print(f"Predicted demand: {predicted_demand:.2f}")
Predicted demand: 107.77
Formulate the Optimization Problem in AMPL#
We’ll use AMPL to define and solve a profit-maximizing problem:
Objective: Maximize profit = (price - unit cost) × quantity
Subject to:
Quantity must not exceed capacity
Quantity must not exceed predicted demand
%%writefile demand.mod
param predicted_demand;
param unit_cost;
param price;
param capacity;
var quantity >= 0, <= capacity;
maximize profit: (price - unit_cost) * quantity;
s.t. DemandLimit: quantity <= predicted_demand;
Overwriting demand.mod
Load data and Solve#
We assign values to model parameters and solve the optimization problem using the Gurobi solver.
# Define optimization model in AMPL
ampl.read("demand.mod")
unit_cost = 5
capacity = 150
# Load data
ampl.param["price"] = price
ampl.param["unit_cost"] = unit_cost
ampl.param["capacity"] = capacity
ampl.param["predicted_demand"] = predicted_demand
# Solve the model
ampl.solve(solver="gurobi")
assert ampl.solve_result == "solved", ampl.solve_result
Gurobi 12.0.1:Gurobi 12.0.1: optimal solution; objective 862.1837838
0 simplex iterations
Display results#
Let’s retrieve and print the optimal production quantity and the expected profit.
# Get results from AMPL
quantity = ampl.var["quantity"].value()
profit = ampl.obj["profit"].value()
print(f"Optimal quantity to produce: {quantity:.2f}")
print(f"Expected profit: {profit:.2f}")
Optimal quantity to produce: 107.77
Expected profit: 862.18
🚀 Dive Deeper into Optimization#
Explore our open-source model repository:
🔗 colab.ampl.com
📘 Supercharge your skills with our new book featuring 50+ real-world optimization case studies using Amplpy:
🔗 mobook.ampl.com
Start building smarter, faster, and more optimized Python solutions today!