Monday, 13 October 2025

Machine Learning: Nearest Neighbor (NN) algorithm for stock transfers between warehouses

 

🏭 Scenario: Nearest Neighbor Algorithm for Warehouse Stock Transfer

Background

A company, GrapheneTech, distributes graphene sheets across 5 regional warehouses in Southeast Asia:

WarehouseLocationAverage Daily Demand (units)Average Lead Time (days)Current Inventory (units)
W1Kuala Lumpur952200
W2Penang75170
W3Johor902110
W4Singapore120350
W5Bangkok605300

Problem

  • Warehouse W4 (Singapore) is facing a stock shortage because of sudden demand increase.

  • The replenishment lead time from the supplier is 7 days, which is too slow.

  • The company wants to transfer stocks from another warehouse temporarily to maintain W4’s 95% service level.

But which warehouse should W4 get help from?


Step 1: Define the Features for Similarity

Each warehouse is described by quantitative features that influence stock movement feasibility:

FeatureMeaning
DDAverage daily demand
LLLead time from supplier
SSCurrent stock level
DistDist
Transportation distance (km) from W4

Suppose distances from W4 are:

From → W4Distance (km)
W1350
W2600
W3250
W51400

Step 2: Represent Each Warehouse as a Feature Vector

Each warehouse = [D,L,S,Dist][D, L, S, Dist]

WarehouseVector [D,L,S,Dist][D, L, S, Dist]
W1[95, 2, 200, 350]
W2[75, 1, 70, 600]
W3[90, 2, 110, 250]
W5[60, 5, 300, 1400]
W4 (Target)[120, 3, 50, 0]

Step 3: Apply Nearest Neighbor (Euclidean Distance)

We compute the “distance” between W4 and every other warehouse:

d(Wi,W4)=(DiD4)2+(LiL4)2+(SiS4)2+(Disti0)2d(W_i, W4) = \sqrt{(D_i - D_4)^2 + (L_i - L_4)^2 + (S_i - S_4)^2 + (Dist_i - 0)^2}

Let’s calculate digit by digit for clarity:


For W1:381.7


For W2:602.0


For W3:258.8


For W5:1423.4


Step 4: Find the Nearest Neighbor

WarehouseDistance to W4Rank
W3 (Johor)258.8🥇 Nearest
W1381.72
W2602.03
W51423.44

Nearest Neighbor = W3 (Johor)


Step 5: Decision and Action

Since W3 is most similar and geographically close:

  • W3 can transfer 40 units of graphene sheets to W4 immediately.

  • This transfer minimizes cost and maintains regional balance.


Step 6: Result

Warehouse    Inventory Before    Transfer    Inventory After
W3        110        −40            70
W4        50        +40            90
  • W4’s shortage problem solved.

  • W3 still has sufficient inventory for its demand.


🧠 Interpretation

The nearest neighbor algorithm here:

  • Quantifies warehouse similarity (in demand, stock, lead time, and distance).

  • Chooses the most appropriate source warehouse for emergency stock transfer.

  • Avoids manual guesswork or arbitrary selection.






Python Code


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# --- Step 1: Define warehouse data ---
data = {
    "Warehouse": ["W1", "W2", "W3", "W5"],   # W4 is the target
    "Demand": [95, 75, 90, 60],
    "LeadTime": [2, 1, 2, 5],
    "Stock": [200, 70, 110, 300],
    "DistanceToW4": [350, 600, 250, 1400]  # distance from each to W4
}

warehouses = pd.DataFrame(data)

# Target warehouse (W4)
target = np.array([120, 3, 50, 0])  # Demand, LeadTime, Stock, Distance
target_name = "W4"

# --- Step 2: Compute Euclidean distances ---
def euclidean_distance(row, target):
    return np.sqrt(((row - target) ** 2).sum())

features = warehouses[["Demand", "LeadTime", "Stock", "DistanceToW4"]].values
warehouses["NN_Distance"] = [euclidean_distance(row, target) for row in features]

# --- Step 3: Find nearest neighbor ---
nearest = warehouses.loc[warehouses["NN_Distance"].idxmin()]

print("Nearest warehouse to W4 (for stock transfer):")
print(nearest[["Warehouse", "NN_Distance"]])

# --- Step 4: Optional: simulate transfer ---
transfer_qty = 40
warehouses.loc[warehouses["Warehouse"] == nearest["Warehouse"], "Stock"] -= transfer_qty
w4_stock_after = 50 + transfer_qty

print("\nAfter transfer:")
print(f"{nearest['Warehouse']} new stock: {int(warehouses.loc[warehouses['Warehouse']==nearest['Warehouse'],'Stock'])}")
print(f"W4 new stock: {w4_stock_after}")

# --- Step 5: Visualization ---
plt.figure(figsize=(8,6))
plt.scatter(warehouses["DistanceToW4"], warehouses["Stock"], color="skyblue", s=100, label="Other Warehouses")

# Highlight nearest neighbor
plt.scatter(nearest["DistanceToW4"], nearest["Stock"], color="orange", s=200, edgecolors="black", label=f"Nearest: {nearest['Warehouse']}")

# Target warehouse (W4)
plt.scatter(0, 50, color="red", s=200, marker="*", label="Target: W4")

# Labels
for _, row in warehouses.iterrows():
    plt.text(row["DistanceToW4"]+10, row["Stock"]+5, row["Warehouse"], fontsize=10)

plt.text(10, 50+10, "W4", color="red", fontsize=11, weight="bold")

plt.title("Graphene Warehouse Stock vs Distance (Nearest Neighbor Transfer)")
plt.xlabel("Distance to W4 (km)")
plt.ylabel("Current Stock (units)")
plt.legend()
plt.grid(True, linestyle="--", alpha=0.6)
plt.tight_layout()
plt.show()


No comments:

Post a Comment

Machine Learning: Nearest Neighbor (NN) algorithm for stock transfers between warehouses

  🏭 Scenario: Nearest Neighbor Algorithm for Warehouse Stock Transfer Background A company, GrapheneTech , distributes graphene sheets a...