kishorkukreja/awesome-supply-chain/ml-supply-chain

Claude Code and agent skill by kishorkukreja/awesome-supply-chain

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

When the user wants to apply machine learning to supply chain problems, build ML models, or use AI for predictions. Also use when the user mentions "machine learning," "deep learning," "neural networks," "AI supply chain," "predictive models," "classification models," "regression models," "anomaly detection," "computer vision," or "NLP for supply chain." For traditional forecasting, see demand-forecasting. For optimization, see optimization-modeling.

Install

npx vskill@latest install kishorkukreja/awesome-supply-chain/ml-supply-chain

SKILL.md

Machine Learning for Supply Chain

You are an expert in applying machine learning and artificial intelligence to supply chain problems. Your goal is to help build, train, and deploy ML models that improve forecasting, classification, optimization, and decision-making across supply chain operations.

Initial Assessment

Before applying ML to supply chain problems, understand:

  1. Business Problem
  • What problem needs solving? (demand forecasting, quality prediction, route optimization)
  • What decisions will ML model support?
  • Current approach and its limitations?
  • Expected improvement and ROI?
  1. Data Availability
  • What data is available? (structured, unstructured, images, text)
  • Historical data quantity? (ML typically needs 1000+ samples)
  • Data quality? (missing values, outliers, noise)
  • Feature availability? (predictive variables)
  • Real-time data access?
  1. ML Problem Type
  • Supervised learning? (labeled data available)
  • Unsupervised learning? (clustering, anomaly detection)
  • Reinforcement learning? (sequential decision-making)
  • Time series forecasting?
  1. Technical Environment
  • ML expertise in team?
  • Computational resources? (CPU, GPU, cloud)
  • Deployment environment? (batch, real-time API, edge)
  • MLOps capabilities?

ML Problem Types in Supply Chain

Supervised Learning

Regression (Continuous Output)

  • Demand forecasting
  • Lead time prediction
  • Price optimization
  • Inventory level prediction
  • Delivery time estimation

Classification (Categorical Output)

  • Product categorization
  • Supplier risk classification
  • Quality defect detection
  • Shipment delay prediction (on-time vs. late)
  • Customer churn prediction
Unsupervised Learning

Clustering

  • Customer segmentation
  • Product grouping
  • Route clustering
  • Anomaly detection in operations

Dimensionality Reduction

  • Feature extraction
  • Data visualization
  • Noise reduction
Reinforcement Learning

Sequential Decision-Making

  • Inventory control policies
  • Dynamic pricing
  • Warehouse robot navigation
  • Order dispatching

Demand Forecasting with ML

Feature Engineering for Demand Forecasting
python
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
def create_demand_features(df, target_col='demand'):
"""
Create comprehensive feature set for demand forecasting
df: DataFrame with columns ['date', 'sku', 'demand']
"""
df = df.copy()
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values(['sku', 'date'])
# Time-based features
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df['day_of_week'] = df['date'].dt.dayofweek
df['day_of_year'] = df['date'].dt.dayofyear
df['week_of_year'] = df['date'].dt.isocalendar().week
df['quarter'] = df['date'].dt.quarter
df['is_weekend'] = (df['day_of_week'] >= 5).astype(int)
df['is_month_start'] = df['date'].dt.is_month_start.astype(int)
df['is_month_end'] = df['date'].dt.is_month_end.astype(int)
# Lag features (previous demand)
for lag in [1, 7, 14, 28, 365]:
df[f'lag_{lag}'] = df.groupby('sku')[target_col].shift(lag)
# Rolling statistics
for window in [7, 14, 28, 90]:
df[f'rolling_mean_{window}'] = (
df.groupby('sku')[target_col]
.rolling(window, min_periods=1)
.mean()
.reset_index(0, drop=True)
)
df[f'rolling_std_{window}'] = (
df.groupby('sku')[target_col]
.rolling(window, min_periods=1)
.std()
.reset_index(0, drop=True)
)
df[f'rolling_min_{window}'] = (
df.groupby('sku')[target_col]
.rolling(window, min_periods=1)
.min()
.reset_index(0, drop=True)
)
df[f'rolling_max_{window}'] = (
df.groupby('sku')[target_col]
.rolling(window, min_periods=1)
.max()
.reset_index(0, drop=True)
)
# Exponential weighted moving average
df['ewm_7'] = (
df.groupby('sku')[target_col]
.transform(lambda x: x.ewm(span=7).mean())
)
df['ewm_28'] = (
df.groupby('sku')[target_col]
.transform(lambda x: x.ewm(span=28).mean())
)
# Trend features
df['demand_trend_7'] = df[f'lag_7'] - df[f'lag_14']
df['demand_trend_28'] = df[f'lag_28'] - df[f'lag_56']
# Cyclical encoding for seasonal features
df['month_sin'] = np.sin(2 * np.pi * df['month'] / 12)
df['month_cos'] = np.cos(2 * np.pi * df['month'] / 12)
df['day_sin'] = np.sin(2 * np.pi * df['day_of_week'] / 7)
df['day_cos'] = np.cos(2 * np.pi * df['day_of_week'] / 7)
return df
# Example usage
demand_df = pd.DataFrame({
'date': pd.date_range('2022-01-01', '2024-12-31', freq='D'),
'sku': 'SKU_001',
'demand': np.random.poisson(100, 1096)
})
features_df = create_demand_features(demand_df)
print(f"Features created: {len(features_df.columns)} columns")
Gradient Boosting for Demand Forecasting
python
import xgboost as xgb
import lightgbm as lgb
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
class MLDemandForecaster:
"""
Machine learning demand forecasting using gradient boosting
"""
def __init__(self, model_type='xgboost'):
self.model_type = model_type
self.model = None
self.feature_importance = None
def prepare_data(self, df, target_col='demand', test_size=90):
"""
Prepare train/test split for time series
test_size: number of days to hold out for testing
"""
# Remove rows with NaN (due to lag features)
df_clean = df.dropna()
# Identify feature columns (exclude date, sku, target)
feature_cols = [col for col in df_clean.columns
if col not in ['date', 'sku', target_col]]
# Time-based split
split_date = df_clean['date'].max() - timedelta(days=test_size)
train = df_clean[df_clean['date'] <= split_date]
test = df_clean[df_clean['date'] > split_date]
X_train = train[feature_cols]
y_train = train[target_col]
X_test = test[feature_cols]
y_test = test[target_col]
return X_train, X_test, y_train, y_test, feature_cols
def train(self, X_train, y_train, params=None):
"""
Train gradient boosting model
"""
if self.model_type == 'xgboost':
default_params = {
'objective': 'reg:squarederror',
'n_estimators': 1000,
'learning_rate': 0.05,
'max_depth': 6,
'subsample': 0.8,
'colsample_bytree': 0.8,
'random_state': 42,
'early_stopping_rounds': 50
}
if params:
default_params.update(params)
self.model = xgb.XGBRegressor(**default_params)
elif self.model_type == 'lightgbm':
default_params = {
'objective': 'regression',
'n_estimators': 1000,
'learning_rate': 0.05,
'num_leaves': 31,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'random_state': 42
}
if params:
default_params.update(params)
self.model = lgb.LGBMRegressor(**default_params)
# Train
self.model.fit(
X_train, y_train,
eval_set=[(X_train, y_train)],
verbose=100
)
# Store feature importance
self.feature_importance = pd.DataFrame({
'feature': X_train.columns,
'importance': self.model.feature_importances_
}).sort_values('importance', ascending=False)
def predict(self, X):
"""Make predictions"""
return self.model.predict(X)
def evaluate(self, X_test, y_test):
"""
Evaluate model performance
"""
y_pred = self.predict(X_test)
metrics = {
'MAE': mean_absolute_error(y_test, y_pred),
'RMSE': np.sqrt(mean_squared_error(y_test, y_pred)),
'MAPE': np.mean(np.abs((y_test - y_pred) / y_test)) * 100,
'Bias': np.mean(y_pred - y_test)
}
return metrics, y_pred
def plot_results(self, y_test, y_pred, dates=None):
"""
Visualize predictions vs actuals
"""
fig, axes = plt.subplots(2, 1, figsize=(14, 8))
# Time series plot
if dates is not None:
axes[0].plot(dates, y_test.values, label='Actual', linewidth=2)
axes[0].plot(dates, y_pred, label='Predicted', linewidth=2, alpha=0.7)
else:
axes[0].plot(y_test.values, label='Actual', linewidth=2)
axes[0].plot(y_pred, label='Predicted', linewidth=2, alpha=0.7)
axes[0].set_title('Demand Forecast: Actual vs Predicted')
axes[0].set_xlabel('Time')
axes[0].set_ylabel('Demand')
axes[0].legend()
axes[0].grid(True, alpha=0.3)
# Scatter plot
axes[1].scatter(y_test, y_pred, alpha=0.5)
axes[1].plot([y_test.min(), y_test.max()],
[y_test.min(), y_test.max()],
'r--', linewidth=2, label='Perfect Prediction')
axes[1].set_xlabel('Actual Demand')
axes[1].set_ylabel('Predicted Demand')
axes[1].set_title('Prediction Accuracy')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def plot_feature_importance(self, top_n=20):
"""
Plot feature importance
"""
top_features = self.feature_importance.head(top_n)
plt.figure(figsize=(10, 8))
plt.barh(range(len(top_features)), top_features['importance'])
plt.yticks(range(len(top_features)), top_features['feature'])
plt.xlabel('Importance')
plt.title(f'Top {top_n} Feature Importance')
plt.gca().invert_yaxis()
plt.tight_layout()
plt.show()
# Example usage
forecaster = MLDemandForecaster(model_type='xgboost')
# Prepare data
X_train, X_test, y_train, y_test, feature_cols = forecaster.prepare_data(
features_df,
test_size=90
)
# Train model
forecaster.train(X_train, y_train)
# Evaluate
metrics, y_pred = forecaster.evaluate(X_test, y_test)
print("\nModel Performance:")
for metric, value in metrics.items():
print(f"{metric}: {value:.2f}")
# Visualize
test_dates = features_df[features_df['date'] > features_df['date'].max() - timedelta(days=90)]['date']
forecaster.plot_results(y_test, y_pred, dates=test_dates)
forecaster.plot_feature_importance(top_n=20)
Deep Learning with LSTM
python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.preprocessing import StandardScaler
class LSTMForecaster:
"""
LSTM neural network for demand forecasting
"""
def __init__(self, lookback=30, forecast_horizon=7):
"""
lookback: number of historical time steps to use
forecast_horizon: number of future steps to predict
"""
self.lookback = lookback
self.forecast_horizon = forecast_horizon
self.model = None
self.scaler = StandardScaler()
def create_sequences(self, data, target):
"""
Create sequences for LSTM training
data: feature array
target: target array
"""
X, y = [], []

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
74
Repository forks
18
7-day trend score
22

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/kishorkukreja/awesome-supply-chain/ml-supply-chain/badge)](https://verified-skill.com/skills/kishorkukreja/awesome-supply-chain/ml-supply-chain)

Something wrong with this skill or its page? Tell us.