Chapter 14 — Assignment Project: How Much Stock to Order?
Overview¶
A small shop sells one product. Every morning the owner decides how many units to order; they arrive at once, then customers come. Ordering too little loses sales and annoys customers; ordering too much ties up money and shelf space. The owner asks: what is the best ordering rule, and how much better is it than what I do now?
You will model the problem as an MDP, solve it exactly, compare it with simple rules of thumb, and then let a Q-learning agent discover a rule from experience alone, as it would have to if the demand were unknown.
The rules of the shop (per day)
| Item | Value |
|---|---|
| Shelf capacity | 20 units (stock + order ≤ 20) |
| Daily demand | random, Poisson with mean 4 |
| Selling price | 10 per unit sold |
| Purchase cost | 4 per unit ordered |
| Delivery fee | 10 for any order (0 if nothing is ordered) |
| Holding cost | 0.5 per unit left on the shelf at the end of the day |
| Lost-sale penalty | 2 per customer turned away (lost goodwill) |
| Discount factor | γ = 0.95 |
| Part | Task | Points |
|---|---|---|
| A | Model the shop as an MDP | 20 |
| B | Solve it exactly with value iteration | 20 |
| C | Simulate the policies; compare with rules of thumb | 15 |
| D | Learn from experience with Q-learning | 25 |
| E | Report for the owner | 20 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import poisson
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
CAPACITY, MEAN_DEMAND = 20, 4.0
PRICE, UNIT_COST, DELIVERY_FEE, HOLDING, LOST_SALE, GAMMA = 10.0, 4.0, 10.0, 0.5, 2.0, 0.95Part A — The MDP (20 points)¶
The state is the stock in the morning (0–20), the action the number of units ordered (0 to 20 − stock).
A1 (checked). Complete one_day(stock, order, demand), returning (stock left at the end of the day, profit of the day) according to the table.
def one_day(stock, order, demand):
raise NotImplementedError # TODOcheck('A1: 2 in stock, order 5, 4 customers', lambda: one_day(2, 5, 4) == (3, 40 - 20 - 10 - 1.5))
check('A1: nothing ordered, 3 in stock, 6 customers', lambda: one_day(3, 0, 6) == (0, 30 - 6))A2 (checked). Complete build_model(max_demand=30), returning P[s][a] as a list of (probability, next_state, expected_reward, False) tuples, one per distinct next state (several demands can lead to the same next state: add their probabilities, and average their profits weighted by probability). Use poisson.pmf(d, MEAN_DEMAND) for max_demand − 1, and put all the remaining probability on the last value.
def build_model(max_demand=30):
p_demand = poisson.pmf(np.arange(max_demand), MEAN_DEMAND)
p_demand[-1] += 1 - p_demand.sum()
raise NotImplementedError # TODOdef _model_ok():
P = build_model()
sizes = all(len(P[s]) == CAPACITY - s + 1 for s in P)
sums = all(np.isclose(sum(p for p, *_ in P[s][a]), 1) for s in P for a in P[s])
p_d = poisson.pmf(np.arange(30), MEAN_DEMAND); p_d[-1] += 1 - p_d.sum()
expected = sum(p * one_day(0, 10, d)[1] for d, p in enumerate(p_d))
return sizes and sums and np.isclose(sum(p * r for p, _, r, _ in P[0][10]), expected)
check('A2: actions per state, probabilities, expected profit', _model_ok)
P = build_model()Part B — The Optimal Policy (20 points)¶
B1. Solve the MDP with value iteration (your function from the lab, adapted, is fine). Print the number of sweeps and the optimal order for every stock level.
# TODOB2. Plot the optimal order and the resulting order-up-to level (stock + order) against the morning stock. Describe the rule in one sentence a shop owner would understand.
# TODOThe rule:
Part C — Simulation and Rules of Thumb (15 points)¶
C1 (checked). Complete simulate(policy, days, seed): start with an empty shelf, draw each day’s demand with rng.poisson(MEAN_DEMAND) from rng = np.random.default_rng(seed), apply policy(stock) and one_day, and return the average daily profit.
def simulate(policy, days=20000, seed=0):
raise NotImplementedError # TODOcheck('C1: never ordering earns nothing but penalties', lambda: np.isclose(simulate(lambda s: 0, 1000), -2 * np.mean(np.random.default_rng(0).poisson(MEAN_DEMAND, 1000))))
check('C1: the optimal policy earns more than ordering 4 a day', lambda: simulate(lambda s: optimal[s]) > simulate(lambda s: min(4, CAPACITY - s)))C2. Compare in one table: the optimal policy; “order 4 units every day (as many as fit)”; “order up to every day” for the best ; the best rule you can find by trying every and ; and the optimal policy for . Choose the best and on simulations with seed 0, then score every policy on 50,000 new days (seed 1): choosing and scoring on the same random days would flatter the chosen rules.
# TODOC3. The “optimal” policy of Part B is not the top of your table. Explain why that is not a contradiction.
Your answer:
Part D — Learning from Experience (25 points)¶
Suppose the owner does not know that demand is Poisson with mean 4. A Q-learning agent can still learn by living through simulated days (in practice, a simulator fitted to the shop’s sales history).
D1. Implement tabular Q-learning over 300,000 simulated days: , , ε decaying linearly from 1 to 0.05 over the first 100,000 days, only valid orders (stock + order ≤ 20), demand from rng.poisson(MEAN_DEMAND) with seed 1. Every 25,000 days, evaluate the current greedy policy with simulate(..., days=5000), and plot this learning curve against the optimal profit.
# TODOD2. Compare the learnt policy with the optimal one (order for each stock level, and average daily profit over 20,000 days). Where do they differ, and why there?
# TODOYour answer:
D3. Learning by trial and error in the real shop would mean ordering random quantities for months. In two or three sentences: what would that cost, and what do companies do instead?
Your answer:
Part E — Report for the Owner (20 points)¶
Write 250–350 words for the shop owner:
The recommended rule, in one sentence, and why ordering in batches beats ordering a little every day.
The gain: average daily profit of the rule against the simple rules (your table), and what that means per year.
How the rule was found: exactly from a model of demand, and again by a learning agent that did not know the model.
Limits: what assumptions it rests on (demand pattern, prices, instant delivery), and when to recompute it.
Your report:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (20) | the daily rule and the model are correct (checked) |
| B (20) | value iteration converges; the policy is plotted and described as an rule |
| C (15) | the simulator is correct (checked); a fair table including the best simple rules |
| D (25) | Q-learning with valid actions and decaying ε; a learning curve; an explained comparison with the optimal policy; D3 answered |
| E (20) | clear for a non-specialist; numbers match the notebook; assumptions stated |