Below is a beginner-to-intermediate “recipe” for building your own AI/ML model from scratch, including:
• Project folder structure
• How/where to get or make a dataset
• Code for loading data, defining the network, training, evaluating, and saving the model
• Explanations of every major step & option (e.g., supervised vs. unsupervised, augmentation, transfer-learning, etc.)
I’ll demonstrate with an image-classification example in PyTorch (easy to adapt to text or tabular data—notes included). Feel free to copy-paste the code as-is, then tweak it for your own use-case.
⚙️ 1. Project Layout
my_ai_project/
├── data/ # put raw files here (jpg, png, txt, csv, …)
│ ├── raw/
│ └── processed/ # gets auto-filled by DataLoader transform
├── models/ # saved weights (.pt files) & logs
├── notebooks/ # Jupyter exploratory work
├── src/
│ ├── config.yaml # hyper-parameters
│ ├── datasets.py # dataset + transforms
│ ├── model.py # NN architecture(s)
│ ├── train.py # training loop
│ ├── evaluate.py # validation / test loop
│ └── utils.py # misc helpers (seed, metrics, etc.)
└── README.md
📦 2. Setting up your environment
conda create -n myai python=3.10
conda activate myai
pip install torch torchvision torchaudio torchmetrics
pip install pyyaml tqdm matplotlib # utils/plotting
📑 3. config.yaml (central hyper-parameter file)
# config.yaml
seed: 42
data_dir: "../data/raw"
img_size: 224
batch_size: 32
num_epochs: 20
lr: 1e-3
num_classes: 10 # change to match your dataset
model_name: "resnet18"
device: "cuda" # or "cpu"
save_dir: "../models"
🗂️ 4. datasets.py
import os, random, torch
from torchvision import datasets, transforms
def get_transforms(img_size):
train_tf = transforms.Compose([
transforms.Resize((img_size, img_size)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.5]*3, [0.5]*3)
])
test_tf = transforms.Compose([
transforms.Resize((img_size, img_size)),
transforms.ToTensor(),
transforms.Normalize([0.5]*3, [0.5]*3)
])
return train_tf, test_tf
def get_dataloaders(data_dir, batch_size, img_size, seed):
train_tf, test_tf = get_transforms(img_size)
# torchvision's ImageFolder expects directory per class
train_ds = datasets.ImageFolder(os.path.join(data_dir,'train'), transform=train_tf)
val_ds = datasets.ImageFolder(os.path.join(data_dir,'val'), transform=test_tf)
test_ds = datasets.ImageFolder(os.path.join(data_dir,'test'), transform=test_tf)
g = torch.Generator().manual_seed(seed)
train_loader = torch.utils.data.DataLoader(train_ds, batch_size, shuffle=True, generator=g)
val_loader = torch.utils.data.DataLoader(val_ds, batch_size, shuffle=False)
test_loader = torch.utils.data.DataLoader(test_ds, batch_size, shuffle=False)
return train_loader, val_loader, test_loader
🧠 5. model.py
import torch
import torch.nn as nn
from torchvision import models
def build_model(model_name, num_classes, pretrained=True):
if model_name == "resnet18":
net = models.resnet18(pretrained=pretrained)
in_feats = net.fc.in_features
net.fc = nn.Linear(in_feats, num_classes)
elif model_name == "custom_cnn":
net = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32,64,3,padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear((img_size//4)*(img_size//4)*64, 128), nn.ReLU(),
nn.Linear(128, num_classes)
)
else:
raise NotImplementedError
return net
🏋️♂️ 6. train.py
import torch, yaml, os
from tqdm import tqdm
from datasets import get_dataloaders
from model import build_model
from utils import set_seed, accuracy_score
def train_one_epoch(model, loader, loss_fn, opt, device):
model.train()
running_loss = 0; running_acc = 0
for x,y in tqdm(loader, leave=False):
x,y = x.to(device), y.to(device)
opt.zero_grad()
out = model(x)
loss = loss_fn(out, y)
loss.backward()
opt.step()
running_loss += loss.item()*x.size(0)
running_acc += accuracy_score(out,y)*x.size(0)
n = len(loader.dataset)
return running_loss/n, running_acc/n
def eval_model(model, loader, loss_fn, device):
model.eval()
loss=0; acc=0
with torch.no_grad():
for x,y in loader:
x,y = x.to(device), y.to(device)
out = model(x)
loss += loss_fn(out,y).item()*x.size(0)
acc += accuracy_score(out,y)*x.size(0)
n=len(loader.dataset)
return loss/n, acc/n
if __name__=="__main__":
cfg = yaml.safe_load(open("config.yaml"))
set_seed(cfg["seed"])
train_dl, val_dl, test_dl = get_dataloaders(cfg["data_dir"], cfg["batch_size"],
cfg["img_size"], cfg["seed"])
device = cfg["device"] if torch.cuda.is_available() else "cpu"
model = build_model(cfg["model_name"], cfg["num_classes"]).to(device)
loss_fn = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=cfg["lr"])
best_val_acc = 0
for epoch in range(cfg["num_epochs"]):
tr_loss,tr_acc = train_one_epoch(model, train_dl, loss_fn, optimizer, device)
v_loss, v_acc = eval_model(model, val_dl, loss_fn, device)
print(f"Epoch {epoch+1}/{cfg['num_epochs']} | "
f"train_loss={tr_loss:.4f} acc={tr_acc:.4f} | "
f"val_loss={v_loss:.4f} acc={v_acc:.4f}")
if v_acc > best_val_acc:
best_val_acc = v_acc
os.makedirs(cfg["save_dir"], exist_ok=True)
torch.save(model.state_dict(), f"{cfg['save_dir']}/best.pt")
print("✓ Saved new best model")
# test
model.load_state_dict(torch.load(f"{cfg['save_dir']}/best.pt"))
test_loss, test_acc = eval_model(model, test_dl, loss_fn, device)
print(f"TEST loss={test_loss:.4f} acc={test_acc:.4f}")
🧰 7. utils.py
import torch, random, numpy as np
def set_seed(seed=42):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed); torch.backends.cudnn.deterministic=True
def accuracy_score(logits, y_true):
preds = torch.argmax(logits, dim=1)
return (preds==y_true).float().mean().item()
🚀 8. Running training
cd src
python train.py # reads config.yaml by default
Training logs appear in console; the best weights land in ../models/best.pt.
🧐 9. Tips, Variations & Explanations
-
Dataset types
• Supervised (labels given) – easiest (what we just did).
• Self-supervised / Contrastive – e.g., SimCLR, Masked Language Modeling. Requires larger data, but fewer labels.
• Unsupervised – clustering, autoencoders.
• Transfer-Learning – start from a pretrained backbone (pretrained=True) then fine-tune on your small dataset (very common).
-
File-based datasets
• Images: ImageFolder expects class_name/xxx.jpg.
• Text: use torchtext, HuggingFace datasets. Replace CNN with Transformer or LSTM.
• Tabular: load via pandas, wrap in torch.utils.data.Dataset.
-
Data splits
train (≈70%) / val (≈15%) / test (≈15%). Keep test untouched until final evaluation.
-
Evaluations & Metrics
Accuracy, F1, precision/recall, confusion matrix (for multi-class). For regression: MAE, MSE, R².
-
Regularisation
Weight decay, dropout layers, data augmentation.
-
Hyper-parameter tuning
Manual grid, Optuna, Ray Tune, or WandB sweeps. Log metrics and compare.
-
Checkpoints & Resume
Save state_dict and optimizer state to resume training if interrupted.
-
GPU / TPU
Model and data to .to("cuda"); monitor GPU memory with nvidia-smi.
-
Deployment
• TorchScript: torch.jit.trace → C++/mobile.
• ONNX: torch.onnx.export → run in Triton or TF-Serving.
• Web: Convert to TensorFlow.js or run a Flask/FastAPI endpoint around .pt model.
-
Experiment tracking
Use Weights & Biases, TensorBoard (add writer in training loop), MLflow.
🔄 10. Extending to other domains
• NLP text classification
Replace datasets.ImageFolder with a HuggingFace Dataset; tokenizer returns input_ids & attention_mask; swap model.py to transformers.AutoModelForSequenceClassification.
Quick stub:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased",
num_labels=cfg["num_classes"])
• Object detection / segmentation
Use torchvision.models.detection (Faster-RCNN, Mask-RCNN) or YOLOv8 (Ultralytics).
• Time-series forecasting
Either 1-D CNNs, RNNs, or Prophet. Create custom Dataset windows.
🌟 Key Takeaways
- Keep your project modular (separate data, model, train).
- Always track seeds & hyper-params for reproducibility.
- Start with a pretrained backbone; only build from scratch if you have lots of data & compute.
- Use a validation set for early stopping and hyper-tuning; keep test data unseen until final.
- Save best checkpoints + code snapshot (e.g., using Git) so you can reproduce results later.
That’s the end-to-end blueprint!
Clone the skeleton, drop your dataset into data/raw/train|val|test, adjust config.yaml, and hit python train.py. 🔥
Feel free to ask follow-ups (e.g., “How do I convert this to an LSTM for text?”, “How do I deploy on AWS Lambda?”, etc.).