<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by LL-Monkey on Medium]]></title>
        <description><![CDATA[Stories by LL-Monkey on Medium]]></description>
        <link>https://medium.com/@ll-monkey?source=rss-5a15a144aae0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_-oyjd98_NPXDWDL3K0R_A.jpeg</url>
            <title>Stories by LL-Monkey on Medium</title>
            <link>https://medium.com/@ll-monkey?source=rss-5a15a144aae0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:12:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ll-monkey/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why “Thai LLM” Doesn’t Mean What You Think — A Tokenizer Deep Dive]]></title>
            <link>https://ll-monkey.medium.com/why-thai-llm-doesnt-mean-what-you-think-a-tokenizer-deep-dive-d1048df33085?source=rss-5a15a144aae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1048df33085</guid>
            <category><![CDATA[thai-nlp]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[legal-ai]]></category>
            <dc:creator><![CDATA[LL-Monkey]]></dc:creator>
            <pubDate>Thu, 14 May 2026 11:25:29 GMT</pubDate>
            <atom:updated>2026-05-14T12:05:22.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*8Uzul18U--CRHuJwDJq5aw.png" /></figure><p>There are so many LLMs out there now. Every few months, a new one claims to be better, faster, cheaper. But I kept wondering about a much more specific question: <em>what happens when you use any of these models on Thai government documents?</em></p><p>Not casual Thai. Not Thai social media. The dense, formal, unforgiving language of regulations, ministerial orders, and court rulings — full of agency names that span half a sentence and act titles that nobody outside the legal system ever memorizes.</p><h3>Tokenization: What even is a token?</h3><p>Before I could answer my own question, I had to understand something most LLM tutorials skip over.</p><p>LLMs don’t read text the way you do. Before your text reaches the model, a component called a <strong>tokenizer</strong> breaks it into chunks called <strong>tokens</strong>. A token might be a full word, a syllable, or just a character. The model only ever sees these token IDs but never the original text. This process is called <strong>tokenization</strong>.</p><p>For English, this usually works fine. For instance, Gemma-2 (9B) seesparliament as two tokens, while Llama-3 (8B) sees it as three tokens. Still, acceptable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*2AJrqKFQ9bde6tkAd4RV2w.png" /></figure><p>For Thai legal text, things fall apart fast — for reasons we’ll get into right now.</p><h3>Three Failure Patterns I Kept Seeing in Thai Legal Language</h3><h4>1. Named Entity Fragmentation: Agency Names Get Shredded</h4><p>Thai government agency names are notoriously long <strong>named entities</strong>. A tokenizer without Thai legal training data has no idea these are meaningful units, so it fragments them at the character or subword level.</p><p>Take this:</p><blockquote>คณะกรรมการป้องกันและปราบปรามการฟอกเงิน<em> (Anti-Money Laundering Board)</em></blockquote><p>A Thai-aware tokenizer handles this in roughly 7–16 tokens, treating compound words as units. A general-purpose tokenizer fragments the same phrase into individual characters with no semantic meaning. The model then has to reconstruct somehow that this chaotic string of tokens is a proper noun referring to a specific government body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1wmm7vFmCjiqhld52tAoQ.png" /></figure><p>It often doesn’t. You get hallucinated agency names, confused <strong>entity references</strong>, and extraction errors. That’s why we’re starting to see AI-generated Thai text with incorrect agency names.</p><h4>2. Cross-Chunk Reference Loss: Section Citations Break Apart</h4><p>Thai legal documents use a specific citation structure: มาตรา (section), ข้อ (clause), วรรค (paragraph) — written with Thai numerals.</p><blockquote>มาตรา ๑๒๓ วรรคสอง<em> (“Section 123, paragraph two”)</em></blockquote><p>A bad tokenizer treats ๑๒๓ as three separate tokens (one per Thai digit), and splits วรรคสอง mid-word. After unstrategically chunking, มาตรา ๑๒๓ might end up in one chunk while วรรคสอง ends up in the next — and your retrieval step pulls back half-references that point nowhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEUGO9CTIh_sOhu7RFd9gw.png" /></figure><h4>3. Long-Form Named Entity Collapse: Act Names Become Noise</h4><p>Thai legislation names are extremely long <strong>compound proper nouns</strong> — meant to be treated as a single named entity.</p><blockquote>พระราชบัญญัติป้องกันและปราบปรามการฟอกเงิน พ.ศ. ๒๕๔๒<em> (“Anti-Money Laundering Act B.E. 2542”)</em></blockquote><p>A model without Thai legal training data fragments this into an unreasonably large number of tokens and fails to recognize it as a named entity at all. When you ask “what does this regulation say about X”, the model may not even correctly identify <em>which regulation</em> it’s reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6J7Bb1mI2dfSwrpSksoJw.png" /></figure><h3>Once I Understood Tokenization, the Chunking Problem Made Sense</h3><p>Most <strong>RAG (Retrieval-Augmented Generation)</strong> pipelines split documents into chunks before retrieval. Standard <strong>chunking strategies</strong> split on whitespace, newlines, or punctuation.</p><p>Thai legal documents have almost none of those in the right places. A chunking strategy optimized for English will slice right through:</p><ul><li>the middle of an act name</li><li>between a section number and its paragraph reference</li><li>mid-clause in legal conditionals like <em>โดยอนุโลม</em> (“by analogy”) or <em>แล้วแต่กรณี</em> (“as the case may be”)</li></ul><p>The result: your retrieved <strong>context window</strong> is filled with semantically broken fragments. The model hallucinates the missing pieces.</p><h3>The Test — And the Result I Didn’t Expect</h3><p>I’m a novice in this area and wanted to see it for myself. So I built a small tool — <strong>Thai LLM Token Comparison</strong> — that lets you paste Thai text and compare how different models tokenize it side by side.</p><p><a href="https://huggingface.co/spaces/ll-monkey/Thai-LLM-Token-Comparison"><strong>Thai Tokenizer Multi-Benchmark</strong></a></p><p>I expected Thai-specific LLMs to win easily. The actual results were more interesting than that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6nEgzPlrW85438GBVUf_w.png" /></figure><p>WangchanBERTa won by a significant margin — nearly half the tokens of Llama-3, and far fewer than the dedicated Thai LLMs. This result surprised me. To understand why, you have to look at the tokenizer architecture.</p><h3>Why Tokenizer Architecture Matters More Than “Thai Model” Labels</h3><p>There are two main tokenizer types behind most modern LLMs, and understanding the difference explained everything.</p><ul><li><strong>B-BPE (Byte-Level BPE) </strong>is used by most large generative models — <strong>Llama, Mistral, Typhoon, OpenThaiGPT, and GPT-4</strong>. This algorithm starts from raw bytes and merges frequent pairs. While models like <strong>Typhoon</strong> and <strong>OpenThaiGPT</strong> have extended their vocabularies to include more Thai, most generalist models were trained on massive English-centric datasets. Because Thai legal or technical terms appear less frequently there, the tokenizer hasn’t learned them as single units. Instead, it breaks a single Thai word into 3–5 tiny “fragments.”</li><li><strong>SentencePiece (Unigram)</strong> is the framework behind <strong>WangchanBERTa</strong>. Unlike BPE, WangchanBERTa’s <strong>Unigram</strong> approach starts with a massive list of potential Thai words and prunes them down based on a specific Thai corpus. Because it was built by Thai linguists for Thai text, it recognizes complex word boundaries and formal terminology as single tokens from the start</li></ul><p>So the gap I found isn’t really “Thai LLM vs non-Thai LLM.” It’s <em>“what language was the tokenizer vocabulary built from?”</em></p><p><strong>What this means practically:</strong> for <strong>RAG pipelines</strong> on Thai documents, consider using a Thai-specific <strong>embedding model </strong>like WangchanBERTa at the retrieval layer, where tokenization efficiency directly affects <strong>semantic similarity search</strong>. At the generative layer, the tokenization problem largely persists across all current Thai LLMs — something worth knowing before you assume a “Thai LLM” will handle your legal documents cleanly.</p><h3>One Honest Caveat</h3><p>This tool measures <strong>tokenization efficiency</strong> — not downstream task performance. Efficient tokenization is a necessary condition, not a sufficient one. You still need to evaluate your model on your actual documents and tasks.</p><p>But it’s a fast, free, and underrated diagnostic signal. If a model fragments <em>คณะกรรมการป้องกันและปราบปรามการฟอกเงิน</em> into 40 character-level tokens, it’s telling you something meaningful about its Thai legal vocabulary coverage. And usually, what it’s telling you isn’t great.</p><p>Try pasting some of your actual documents — act names, agency names, section references with Thai numerals. The differences are usually pretty eye-opening.</p><p><a href="https://huggingface.co/spaces/ll-monkey/Thai-LLM-Token-Comparison"><strong>Thai Tokenizer Multi-Benchmark</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1048df33085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brushstrokes and Bytes: Experimenting with Fine-tuned ResNet50 on Classifying Artwork Images]]></title>
            <link>https://ll-monkey.medium.com/brushstrokes-and-bytes-experimenting-with-fine-tuned-resnet50-on-classifying-artwork-images-953c9700f660?source=rss-5a15a144aae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/953c9700f660</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[resnet50]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[LL-Monkey]]></dc:creator>
            <pubDate>Wed, 13 May 2026 04:27:22 GMT</pubDate>
            <atom:updated>2026-05-13T04:37:23.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyYuIVSYdpxpIRRM4J-_Gw.png" /></figure><p>In the digital age, museums are more than just physical spaces; they are massive datasets of human creations. But can a computer differentiate a pencil drawing from a vintage photograph or a detailed print from a charcoal sketch?</p><p>As part of my journey into deep learning, I decided to experiment with this idea using the <strong>Museum of Modern Art (MoMA) collection</strong>. My goal was simple: learn to build a model that can automatically classify digitized artworks into three distinct categories — <strong>Photographs, Drawings, and Printings</strong>.</p><p>The final model achieved a validation accuracy of <strong>88.4%</strong> and an <strong>F1 score of 0.88</strong>, indicating that it is balanced and performs consistently across all three classes. Try the model on the Streamlit app: <a href="https://huggingface.co/spaces/ll-monkey/ARTWORKS-CLASSIFIER"><strong>ARTWORKS CLASSIFIER on Hugging Face</strong></a></p><h3>The Challenge: When Art Blurs the Lines</h3><p>Art is subjective, and its digital representation can be even more so. Some high-contrast prints can easily be mistaken for photographs, while certain photographs look like drawings. I wanted to see if a pre-trained neural network could pick up on these nuanced stylistic differences.</p><p>The project was inspired by <a href="https://medium.com/@alaeddine.grine/artwork-classification-in-pytorch-b4f3395b877e">Alaeddine Grine’s article: Artwork Classification in PyTorch</a>. In his work, Grine focused on classifying artworks by artistic style (e.g., painting, mural, sculpture) using a curated dataset that spans from the 14th to the 21st century. His project showed how deep learning can be applied to art history, helping us understand the evolution of artistic styles.</p><h3>Step 1: Setting Up the Environment</h3><p>I import the necessary libraries. I’m using PyTorch for the model and DataLoaders, and Scikit-learn for evaluation metrics. I also set random seeds across PyTorch, NumPy, and CuDNN to make the experiment reproducible.</p><pre># data handling<br>import os<br>import pandas as pd<br>import numpy as np<br>import random<br>import glob<br>import pickle<br><br># PyTorch<br>import torch<br>import torch.nn as nn<br>from torch.utils.data import Dataset, DataLoader<br>from torchvision import models, transforms<br><br># metrics and evaluation<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score</pre><pre># Set seed<br><br>def set_seed(seed=50):<br>    os.environ[&#39;PYTHONHASHSEED&#39;] = str(seed)<br>    random.seed(seed)<br>    np.random.seed(seed)<br>    torch.manual_seed(seed)<br>    torch.cuda.manual_seed_all(seed)<br>    torch.backends.cudnn.deterministic = True<br>    torch.backends.cudnn.benchmark = False<br><br>set_seed(50)</pre><h3>Step 2: Preparing the Data</h3><p>I started with a dataset obtained from <a href="https://mavenanalytics.io/data-playground/the-museum-of-modern-art-(moma)-collection">Maven Analytics’ Data Playground</a>, which contains over 150,000 records of artworks with metadata such as title, artist, medium, classification, and image links. After some data cleaning (e.g., dropping rows with empty URLs), I focused on the top three classifications: Photographs, Prints, and Drawings. I set aside 60 images (20 per class) as a separate demo set, so they never appear in the training or evaluation pipeline. Also, to keep the experiment controlled and doable, I sampled 3,000 images for each category.</p><pre>art = pd.read_csv(&quot;PATH_TO_DATASET&quot;)<br>art.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vyj_jE8RR6SZQ22YMGV90A.png" /></figure><pre># Focus on top three classifications - Photographs, Prints, and Drawings<br>top_three_class = art_df[&quot;Classification&quot;].value_counts().nlargest(3).index.tolist()<br><br># filter for the top three<br>art_filtered = art_df[art_df[&quot;Classification&quot;] \<br>                      .isin(top_three_class)] \<br>                      .sort_values(by=[&quot;Classification&quot;, &quot;ObjectID&quot;]) \<br>                      .reset_index(drop=True)</pre><pre># reserve 60 images for demo<br>demo_df = art_filtered.sample(n=60, random_state=seed).reset_index(drop=True)<br><br># drop these 60 out of the dataset for train/val set<br>art_filtered = art_filtered.drop(demo_df.index).reset_index(drop=True)<br><br>print(f&quot;Number of arts in demo set: {len(demo_df)}&quot;)<br>print(f&quot;Number of arts left: {len(art_filtered)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZQ4YaiLP1Y8PuHzPis77A.png" /></figure><pre># Sample 3000 per class<br>n_samples_per_class = 3000<br><br>sampling_df = (<br>    art_filtered<br>    .groupby(&quot;Classification&quot;)<br>    .apply(lambda x: x.sample(n=min(len(x), n_samples_per_class), random_state=seed))<br>    .reset_index(drop=True)<br>)<br><br>print(f&quot;Number of arts in sampling set: {len(sampling_df)}&quot;)<br>print(sampling_df[&quot;Classification&quot;].value_counts())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZC1m0lW_tLy_BMRte-fyw.png" /></figure><p><em>(Note: To speed up training, I wrote a quick script to download these 9,000 images locally rather than fetching them via HTTP during every training epoch.)</em></p><h3>Step 3: Preparing Images for ResNet50</h3><p>Convolutional Neural Networks (CNNs) are picky. They expect images to be in a very specific format. Because raw MoMA artwork images come in completely different sizes, pixel ranges, and color profiles, feeding them directly into the model would lead to poor performance.</p><p>I used torchvision.transforms to resize everything to 224×224 pixels, convert to PyTorch tensors, and normalize pixel values using the standard ImageNet mean and standard deviation.</p><pre>import torchvision.transforms<br><br>transform = transforms.Compose([<br>    transforms.Resize((224, 224)),<br>    transforms.ToTensor(),<br>    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),<br>])</pre><h3>Step 4: Building a Custom Dataset Class</h3><p>The images and labels are currently in different places, so I created a custom PyTorch Dataset class to load them together. Each sample returns a (image_tensor, label_id) tuple.</p><pre>class MoMADataset(Dataset):<br><br>  def __init__(self, df, image_path, label_col, transform=None, class_index=None):<br>    self.df = df<br>    self.image_path = image_path<br>    self.label_col = label_col<br>    self.transform = transform<br><br>    if class_index is None:<br>      classes = sorted(df[label_col].unique())<br>      self.class_index = {c: index for index, c in enumerate(classes)}<br>    else:<br>      self.class_index = class_index<br><br>  def __len__(self):<br>    return len(self.df)<br><br>  def __getitem__(self, index):<br>    img_name = os.path.join(self.image_path, f&quot;{self.df.iloc[index][&#39;ObjectID&#39;]}.jpg&quot;)<br>    image = Image.open(img_name).convert(&quot;RGB&quot;)<br><br>    if self.transform:<br>      image = self.transform(image)<br><br>    label_name = self.df.iloc[index][self.label_col]<br>    label = self.class_index[label_name]<br>    label = torch.tensor(label, dtype=torch.long)<br><br>    return image, label</pre><p>I split the data into 85% training and 15% testing (7,650 train / 1,350 test), then wrapped them in DataLoaders with a batch size of 32.</p><pre>train_df, test_df = train_test_split(sampling_df, test_size=0.15, random_state=seed)<br>print(f&quot;Number of training samples: {len(train_df)}&quot;)<br>print(f&quot;Number of testing samples: {len(test_df)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsIA8lXvio4yBoLKxgmoLA.png" /></figure><pre>batch_size = 32<br>train_dataset = MoMADataset(train_df, image_path, label_col=&quot;Classification&quot;,<br>                            transform=transform, class_index=class_index)<br>test_dataset = MoMADataset(test_df, image_path, label_col=&quot;Classification&quot;,<br>                           transform=transform, class_index=class_index)<br><br># create DataLoaders to handle batching and shuffling<br>g = torch.Generator()<br>g.manual_seed(seed)<br>train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, generator=g,<br>                          worker_init_fn=lambda worker_id: np.random.seed(seed + worker_id))<br>test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)<br>images, targets = next(iter(train_loader))<br><br>print(f&quot;Batch image shape: {images.shape}&quot;)<br>print(f&quot;Batch target shape: {targets.shape}&quot;)<br>print(f&quot;First sample label: {targets[0]}&quot;)<br>print(f&quot;Label name: {train_dataset.df[&#39;Classification&#39;].iloc[targets[0].item()]}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhapsltY83W-n1iu5TQjLA.png" /></figure><h3>Step 5: Model Setup — Fine-tuning ResNet50</h3><p>For this task, I loaded a pretrained ResNet50 as the backbone. Instead of training from scratch, I froze the early layers (up to layer3) since they learn general low-level features like edges and textures that are transferable across tasks. I unfroze layer4 and replaced the final fully connected layer to match my 3 classes.</p><pre>model = models.resnet50(pretrained=True)<br><br># replace final layer for 3-class classification<br>model.fc = nn.Linear(model.fc.in_features, num_class)<br><br># freeze everything except layer4 and fc<br>for name, param in model.named_parameters():<br>  if &quot;layer4&quot; not in name and &quot;fc&quot; not in name:<br>    param.requires_grad = False<br><br># confirm trainable layer<br>for name, param in model.named_parameters():<br>  if param.requires_grad:<br>    print(f&quot; {name}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*do0c9U60aVbxgV4UT2nN8A.png" /></figure><p>For the optimizer and loss function, I used Adam with a learning rate of 1e-4, CrossEntropyLoss, and a ReduceLROnPlateau scheduler that halves the learning rate if validation loss plateaus for 2 epochs.</p><pre>optimizer = torch.optim.Adam(params=trainable_params, lr=1e-4)<br>loss_fn = nn.CrossEntropyLoss()<br>scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(<br>    optimizer, mode=&#39;min&#39;, factor=0.5, patience=2<br>)</pre><p>In my experiment code, I also built a checkpoint system to save and resume training mid-epoch — useful when working in Colab, where sessions can reset.</p><h3>Step 6: Evaluation Function</h3><p>Before training, I define an evaluation function. It switches the model into eval()mode to disable dropout and norm updates. It runs inference without gradient computation, and returns accuracy, F1, precision, and recall — all macro-averaged so each class gets equal weight regardless of size. This function is called at the end of every epoch during training to track how the model is doing on the held-out test set.</p><pre>def evaluate_model(model, data_loader, device, loss_fn=None):<br>  model.eval()<br><br>  all_targets, all_preds = [], []<br>  total_loss = 0.0<br>  num_samples = 0<br><br>  with torch.no_grad():<br>    for images, targets in data_loader:<br>      images, targets = images.to(device), targets.to(device)<br>      outputs = model(images)<br><br>      if loss_fn is not None:<br>          batch_loss = loss_fn(outputs, targets).item()<br>          total_loss += batch_loss * images.size(0)<br>          num_samples += images.size(0)<br><br>      _, preds = torch.max(outputs, 1)<br>      all_targets.extend(targets.cpu().numpy())<br>      all_preds.extend(preds.cpu().numpy())<br><br>    metrics = {<br>        &quot;accuracy&quot;: accuracy_score(all_targets, all_preds),<br>        &quot;f1&quot;: f1_score(all_targets, all_preds, average=&quot;macro&quot;),<br>        &quot;precision&quot;: precision_score(all_targets, all_preds, average=&quot;macro&quot;),<br>        &quot;recall&quot;: recall_score(all_targets, all_preds, average=&quot;macro&quot;)<br>    }<br><br>    if loss_fn is not None and num_samples &gt; 0:<br>        metrics[&quot;loss&quot;] = total_loss / num_samples<br><br>    return metrics</pre><h3>Step 7: Training</h3><p>I trained for 5 epochs with a batch size of 32. The loop handles a few things beyond the basics, as this is a learning experiment: it logs batch-level loss every 20 batches so I can see intra-epoch progress, saves a checkpoint to Google Drive every 50 batches (useful in Colab, where sessions can drop mid-training), and calls evaluate_model at the end of each epoch, steps the LR scheduler based on validation loss, saves the best model weights whenever validation loss improves, and serializes all metrics to a pickle file so they survive a runtime reset.</p><pre>for epoch in range(start_epoch, num_epochs):<br>    print(f&quot;\n--- Epoch {epoch+1}/{num_epochs} ---&quot;)<br>    model.train()<br>    running_loss = 0.0<br><br>    for batch_idx, (images, targets) in enumerate(train_loader):<br>        # skip batches already processed if resuming mid-epoch<br>        if epoch == start_epoch and batch_idx &lt; start_batch:<br>            continue<br><br>        images, targets = images.to(device), targets.to(device).long()<br>        optimizer.zero_grad()<br>        outputs = model(images)<br>        loss = loss_fn(outputs, targets)<br>        loss.backward()<br>        optimizer.step()<br><br>        # track batch-level loss<br>        train_losses_batch.append(loss.item())<br>        batch_indices.append(epoch + batch_idx / len(train_loader))<br>        running_loss += loss.item() * images.size(0)<br><br>        # print progress every 20 batches<br>        if (batch_idx + 1) % 20 == 0:<br>            print(f&quot;Epoch {epoch+1}, Batch {batch_idx+1}/{len(train_loader)} - Loss: {loss.item():.4f}&quot;)<br><br>        # save checkpoint every 50 batches<br>        if (batch_idx + 1) % 50 == 0:<br>            old_checkpoints = glob.glob(os.path.join(checkpoint_dir, &quot;checkpoint_epoch*.pt&quot;))<br>            for old_ckpt in old_checkpoints:<br>                os.remove(old_ckpt)<br><br>            save_checkpoint(<br>                model=model,<br>                optimizer=optimizer,<br>                scheduler=scheduler,<br>                epoch=epoch+1,<br>                batch_index=batch_idx+1,<br>                loss=loss.item(),<br>                best_val_loss=best_val_loss,<br>                save_path=os.path.join(checkpoint_dir, f&quot;checkpoint_epoch{epoch+1}_batch{batch_idx+1}.pt&quot;)<br>            )<br><br>    # compute epoch-level training loss<br>    epoch_loss = running_loss / len(train_loader.dataset)<br>    train_losses_epoch.append(epoch_loss)<br><br>    # evaluate on test set<br>    metrics = evaluate_model(model, test_loader, device, loss_fn=loss_fn)<br>    test_loss = metrics[&quot;loss&quot;] if &quot;loss&quot; in metrics else float(&quot;inf&quot;)<br>    test_accuracy = metrics[&quot;accuracy&quot;]<br>    f1 = metrics[&#39;f1&#39;]<br>    precision = metrics[&#39;precision&#39;]<br>    recall = metrics[&#39;recall&#39;]<br><br>    # step scheduler and record epoch metrics<br>    scheduler.step(test_loss)<br>    val_losses_epoch.append(test_loss)<br>    val_accuracies_epoch.append(test_accuracy)<br><br>    print(f&quot;Epoch [{epoch+1}/{num_epochs}] Completed | Train Loss: {epoch_loss:.4f} | Test Loss: {test_loss:.4f} | Test Acc: {test_accuracy:.4f}&quot;)<br>    print(f&quot;F1: {f1:.4f}, Precision: {precision:.4f}, Recall: {recall:.4f}&quot;)<br><br>    # save best model<br>    if test_loss &lt; best_val_loss:<br>        best_val_loss = test_loss<br>        torch.save(model.state_dict(), os.path.join(checkpoint_dir, &quot;best_model.pt&quot;))<br><br>    start_batch = 0<br><br>    # persist metrics to disk<br>    metrics = {<br>        &#39;train_losses_epoch&#39;: train_losses_epoch,<br>        &#39;val_losses_epoch&#39;: val_losses_epoch,<br>        &#39;val_accuracies_epoch&#39;: val_accuracies_epoch,<br>        &#39;train_losses_batch&#39;: train_losses_batch,<br>        &#39;batch_indices&#39;: batch_indices<br>    }<br>    with open(metrics_path, &#39;wb&#39;) as f:<br>        pickle.dump(metrics, f)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRtTKAfaK1gYr_7U5rsJbA.png" /></figure><p>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5W1sfomXpXXKq2QaFgTHLQ.png" /></figure><p>A few things to note from the training curve. The training loss dropped steadily from 0.44 in epoch 1 down to 0.04 by epoch 5 — a sign that the model was learning the training data well. The validation loss, however, didn’t follow the same clean downward trend: it dipped at epoch 1, bounced up at epoch 2, then gradually recovered. This gap between training and validation loss is a classic sign of mild overfitting, which is expected given the relatively small fine-tuning dataset. Despite that, validation accuracy kept improving, ending at <strong>88.4%</strong> in epoch 5.</p><p>The macro F1 score of <strong>0.88</strong> tells us the model performed consistently across all three classes. Given how visually similar some prints and photographs can be, that’s an encouraging result.</p><h3>Step 8: Plotting Training Metrics</h3><p>After training, I visualize the loss and accuracy curves using a plot_metrics function that reads the saved metrics pickle file. The left plot overlays batch-level and epoch-level training loss against validation loss; the right plot shows how validation accuracy evolved across epochs.</p><pre>def plot_metrics(metrics_path, save_name=&quot;final_loss_accuracy_plot.png&quot;):<br>    if not os.path.exists(metrics_path):<br>        print(f&quot;No metrics file found at {metrics_path}. Cannot plot.&quot;)<br>        return<br><br>    with open(metrics_path, &#39;rb&#39;) as f:<br>        metrics = pickle.load(f)<br>        train_losses_epoch = metrics.get(&#39;train_losses_epoch&#39;, [])<br>        val_losses_epoch = metrics.get(&#39;val_losses_epoch&#39;, [])<br>        val_accuracies_epoch = metrics.get(&#39;val_accuracies_epoch&#39;, [])<br>        train_losses_batch = metrics.get(&#39;train_losses_batch&#39;, [])<br>        batch_indices = metrics.get(&#39;batch_indices&#39;, [])<br><br>    epochs = list(range(1, len(train_losses_epoch) + 1))<br>    plt.figure(figsize=(12, 5))<br><br>    # Loss plot<br>    plt.subplot(1, 2, 1)<br>    if train_losses_batch:<br>        plt.plot(batch_indices, train_losses_batch,<br>                 label=&#39;Train Loss (batch)&#39;, alpha=0.3, color=&#39;blue&#39;)<br>    plt.plot(epochs, train_losses_epoch,<br>             label=&#39;Train Loss (epoch)&#39;, marker=&#39;o&#39;, color=&#39;blue&#39;)<br>    plt.plot(epochs, val_losses_epoch,<br>             label=&#39;Validation Loss&#39;, marker=&#39;o&#39;, color=&#39;orange&#39;)<br>    plt.xlabel(&#39;Epoch&#39;)<br>    plt.ylabel(&#39;Loss&#39;)<br>    plt.title(&#39;Training &amp; Validation Loss&#39;)<br>    plt.legend()<br>    plt.grid(True)<br><br>    # Accuracy plot<br>    plt.subplot(1, 2, 2)<br>    plt.plot(epochs, val_accuracies_epoch,<br>             label=&#39;Validation Accuracy&#39;, marker=&#39;o&#39;, color=&#39;green&#39;)<br>    plt.xlabel(&#39;Epoch&#39;)<br>    plt.ylabel(&#39;Accuracy&#39;)<br>    plt.title(&#39;Validation Accuracy&#39;)<br>    plt.legend()<br>    plt.grid(True)<br><br>    plt.tight_layout()<br>    plt.show()<br><br>plot_metrics(metrics_path)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzZJ0IHPqmG4NgTFDe30hw.png" /></figure><p>The batch-level loss trace (the faint blue line) shows the noisy, step-by-step progress within each epoch, while the epoch-level line smooths it out. The widening gap between training and validation loss across epochs is the mild overfitting signal — the model memorizes the training data more as epochs progress, but validation accuracy still trends upward, ending at 88.4%.</p><h3>What’s Next: Try It Yourself</h3><p>The fine-tuned model is now deployed as a Streamlit app on Hugging Face Spaces. You can also upload any image and get a prediction — Drawing, Photograph, or Print — straight from the model we trained here.</p><p><a href="https://huggingface.co/spaces/ll-monkey/ARTWORKS-CLASSIFIER"><strong>ARTWORKS CLASSIFIER on Hugging Face</strong></a></p><p>The 60-image demo set I held out at the start was specifically for this — images the model has never seen during training or evaluation, so the predictions from the app are a genuine test of how well it generalizes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=953c9700f660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HYROX Data Science Series Part 3: Building an LSTM Model to Forecast Finish Times]]></title>
            <link>https://ll-monkey.medium.com/hyrox-data-science-series-part-3-building-an-lstm-model-to-forecast-finish-times-45f2d6fc6e79?source=rss-5a15a144aae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f2d6fc6e79</guid>
            <category><![CDATA[sport-analytics]]></category>
            <category><![CDATA[bidirectional-lstm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hyrox]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[LL-Monkey]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 11:55:22 GMT</pubDate>
            <atom:updated>2026-04-14T11:55:22.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNKJhEfGUVQ4oVrllyMpiw.png" /></figure><p>Greetings! This is the third part of the HYROX Data Science Series. As promised, we will build an AI model to predict an athlete’s final time based on accumulated time at each checkpoint in the race. Before getting our hands dirty, you might be interested in getting the data from hyresult.com using a Python scraper from the series’s first part: <a href="https://medium.com/@pdontr/from-the-race-track-to-the-data-pipeline-scraping-hyrox-bangkok-2026-results-part-1-38ee8a79e458"><em>HYROX Data Science Series Part 1: Scraping Bangkok 2026 Race Data from the Track with Python</em></a>. Plus, you might want to understand and clean the data you obtain, with some guidance in the second part: <a href="https://medium.com/@pdontr/hyrox-data-science-series-part-2-what-4000-athletes-in-bangkok-2026-taught-us-about-age-fatigue-e6b4b6c35b98"><em>HYROX Data Science Series Part 2: What 4000+ athletes in Bangkok 2026 taught us about age, fatigue, and the brutal reality of the Roxzone</em></a>.</p><p>First things first, what we are going to do here is not all new. If you are a HYROX athlete yourself, you might be using the ROXFIT app, where you can watch live races and see other athletes with their “predicted finished time.” But how exactly do these predictive models work under the hood? In this post, we’ll try to build such a model using a Long Short-Term Memory (LSTM) neural network to predict final finish times based on split times.</p><h3>The Model Concept: A model that remembers</h3><p>An <strong>LSTM (Long Short-Term Memory)</strong> is a type of recurrent neural network (RNN) designed to recognize patterns in sequences, such as time-series data or text. Unlike standard neural networks, LSTMs have a “memory” that allows them to retain information over long periods, making them ideal for predicting future outcomes based on historical trends. They achieve this using a system of <strong>gates</strong> (Forget, Input, and Output) that regulate which data to keep or discard, preventing older information from being lost as the sequence grows. This means the LSTM can “remember” an athlete’s performance in earlier time steps to better predict their performance in the next. If you need to deep dive into LSTM, you can explore other Medium posts, such as <a href="https://medium.com/data-science-collective/future-forecasting-of-time-series-using-lstm-a-quick-guide-for-business-leaders-370661c574c9"><em>Future Forecasting Of Time Series using LSTM: A Quick Guide For Business Leaders</em></a><em> </em>by Kareim Tarek.</p><h3>The Race Concept: Race Splits as a Sequence</h3><p>Before we code, let’s look at the logic and background information for those who are new to HYROX. A HYROX race isn’t just one long 8-km run; it’s a sequence of 16 segments (8 runs and 8 workouts), each with a two-part time checkpoints: in and out. As an athlete progresses through the race, their performance at “Station 3 Out” is heavily influenced by how hard they pushed in “Station 1 and 2.”</p><p>About the data, we use only four divisions for demonstration: MEN OPEN, MEN PRO, WOMEN OPEN, WOMEN PRO. In this model, we will use the <strong>Accumulated Time</strong> at each checkpoint. We will focus only on the “In” and “Out” times of each workout station (e.g., <em>Sled Push In, Sled Push Out</em>). In other words, we will use the accumulated time when the athlete enters and exits the workout station. However, for your experiment, you can expand this to include the <strong>Roxzone</strong> entries and exits for even higher granularity. By treating these splits as a sequence, the LSTM can “see” the athlete’s fatigue building up over time.</p><h3>Step 1: Preprocessing the Race Data</h3><p>Before feeding our data into a neural network, we need to make sure it is in a format that the neural network can understand. We start by loading our dataset from part 2, which contains 4543 entries and 90 columns.</p><pre>import pandas as pd<br>import numpy as np<br><br>df = pd.read_csv(&quot;hyrox_data_cleaned.csv&quot;)<br>df.shape</pre><pre># Output<br>(4543, 90)</pre><p>We will select only the columns we will use. This includes <strong>division, Total Time, </strong>and<strong> the workout’s accumulated time</strong> starting with “wor” and ending with “time_acc”. Noted that, while the cleaned dataset already contains the age group, gender, and Pro/Open information, we use the <strong>division </strong>column here to make it easier to encode it later on (you will see!).</p><pre># the workout accumulated time starts with &quot;wor&quot; and ends with &quot;time_acc&quot;<br>race_seq_cols = [col for col in df.columns if col.startswith(&quot;wor&quot;) and col.endswith(&#39;time_acc&#39;)]<br>selected_cols = [&quot;division&quot;, &quot;Total Time&quot;] + race_seq_cols<br>df = df[selected_cols]<br>df.head()</pre><pre># Output<br>(4543, 18)</pre><p>Next, we extract and encode context information about the athletes. Gender is mapped to binary values; athletes in the “PRO” or “ELITE” divisions are flagged using an is_pro variable, and ages are mapped into 9 ordered categories (from 16-24 up to 60+). In here, we use a function instead of encoding each column one by one.</p><pre># Encode gender, age, pro/open<br><br>def encode_data(df, input_col):<br><br>    temp_df = df.copy()<br>    <br>    # Gender. 1 for Women, 0 for MEN<br>    temp_df[&quot;gender&quot;] = temp_df[input_col].str.upper().str.contains(&quot;WOMEN&quot;).astype(int)<br>    <br>    # Is Pro. 1 if string contains &#39;PRO&#39;<br>    temp_df[&quot;is_pro&quot;] = temp_df[input_col].str.upper().str.contains(&quot;PRO|ELITE&quot;).astype(int)<br>    <br>    # Age Group from the last item in the division&#39;s string<br>    temp_df[&quot;age_raw&quot;] = temp_df[input_col].str.split().str[-1]<br><br>    # Group all categories 60 and older into a single &#39;60+&#39; bucket<br>    sixty_plus = [&#39;60-64&#39;, &#39;65-69&#39;, &#39;70-74&#39;, &#39;75-79&#39;, &#39;80-84&#39;, &#39;85-89&#39;]<br>    temp_df.loc[temp_df[&quot;age_raw&quot;].isin(sixty_plus), &quot;age_raw&quot;] = &quot;60+&quot;<br><br>    # Define the sort order for age groups<br>    ordered_ages = [<br>        &#39;16-24&#39;, &#39;25-29&#39;, &#39;30-34&#39;, &#39;35-39&#39;, &#39;40-44&#39;, <br>        &#39;45-49&#39;, &#39;50-54&#39;, &#39;55-59&#39;, &#39;60+&#39;<br>    ]<br>    <br>    # Map age strings to numerical ranks (1-9)<br>    age_mapping = {age: i + 1 for i, age in enumerate(ordered_ages)}<br>    temp_df[&quot;age_group&quot;] = temp_df[&quot;age_raw&quot;].map(age_mapping)<br>    <br>    # Handle empty data<br>    temp_df.replace(&quot;null&quot;, np.nan, inplace=True)<br>    temp_df = temp_df.dropna(subset=[&quot;age_group&quot;, &quot;gender&quot;, &quot;is_pro&quot;]).reset_index(drop=True)<br><br>    # Drop raw age column<br>    temp_df.drop(columns=[&quot;age_raw&quot;], inplace=True)<br>    <br>    return temp_df<br><br>df = encode_data(df, &quot;division&quot;)<br>df[[&quot;gender&quot;, &quot;is_pro&quot;, &quot;age_group&quot;]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duhNXVAcQUdeYm3tnOeSUA.png" /></figure><h3>Step 2: Data Preparation for LSTM</h3><h4>Preparing the “3D” Data</h4><p>In standard machine learning, we usually feed the model a flat table (rows and columns). But because we are using an LSTM, we need to restructure our data into a <strong>3D shape</strong>: <strong>[Athletes, Time Steps, Features]:</strong></p><p>First, we initialize an empty “container” for this data. The output will be a blank template. The top section represents the input for a single athlete <em>x</em>. It has <strong>15 rows</strong>, one for each race checkpoint, and <strong>4 columns</strong> waiting for our features: your current time, age, gender, and pro status. The bottom section is the target <em>y</em>, which is the final finish time we want the model to predict.</p><p>Think of this as an <strong>empty shelf</strong> with 15 slots. Right now, the slots are empty (all zeros), but soon we will fill each slot with the athlete’s stats so the LSTM can learn how their performance evolves from the first sled push to the final run.</p><pre># Prepare the shape<br>n_samples = len(df)  # 4543 athletes<br>n_timesteps = len(race_seq_cols)  # 15 timesteps (checkpoints)<br>n_feats = 4  # 4 features for each split (accumulated time, age_group, is_pro, gender)<br><br># use np.zeros to create a blank template.<br>X = np.zeros((n_samples, n_timesteps, n_feats))<br>y = np.zeros((n_samples, n_timesteps, 1))<br><br>print(X[0])<br>print(y[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgIKjif4UVLt2uDo3jyKUQ.png" /></figure><h4>Scaling the Data</h4><p>Most Machine learning models struggle when numbers are on different scales — for example, comparing an “Age Group” of <strong>2</strong> with a “Total Time” of <strong>5,000</strong> seconds. To fix this, we use <strong>MinMaxScaler </strong>(you can experiment with other types of scaling, like StandardScaler). This keeps everything strictly between 0 and 1. It’s like converting different currencies into a single global standard so the model can compare them fairly.</p><p>Note that we use two separate scalers — one for <em>x </em>and one for <em>y </em>— to make it easier to translate the model’s predictions back into real-world units. If we used just one scaler, we wouldn’t be able to “un-scale” the final result because the scaler would be looking for four inputs (age, gender, etc.) instead of just the one we care about (total time).</p><p>Further, for non-time columns, we only scale the age_group one because the others are already in 0 and 1 values.</p><pre>from sklearn.preprocessing import MinMaxScaler<br><br>scaler_X = MinMaxScaler()<br>scaler_y = MinMaxScaler()<br><br># Scale the race splits, age, and total time<br>cols_to_scale = race_seq_cols + [&quot;age_group&quot;]<br>df_scaled = df.copy()<br>df_scaled[cols_to_scale] = scaler_X.fit_transform(df[cols_to_scale])<br>df_scaled[&quot;Total Time&quot;] = scaler_y.fit_transform(df[[&quot;Total Time&quot;]])</pre><h4>Building the Sequences</h4><p>Now we fill our 3D container. For every athlete, we loop through the race checkpoints. At each step, we give the model a “snapshot” that includes how long they’ve been racing, plus their static info (Age, Gender, Pro status). By the time the loop finishes, the model has a full “film strip” of the athlete’s performance from start to finish.</p><p>Voila! We have successfully replaced our “blank shelf” with actual data. We print out <em>x[0]</em>, representing the first athlete (first row of the data). There are 15 timesteps, each with 4 features: accumulated time, age_group (the first group is 0), gender (MEN category is 0), and pro/open division (open division is 0). Each timestep in <em>x[0] </em>has a corresponding <em>y[0]</em>, which contains the same Total Time as the athlete.</p><pre># Add features to each time step<br># (athlete, timesteps, feature)<br><br>total_time_vals = df_scaled[&quot;Total Time&quot;].values<br>age_vals = df_scaled[&quot;age_group&quot;].values<br>gender_vals = df_scaled[&quot;gender&quot;].values<br>pro_vals = df_scaled[&quot;is_pro&quot;].values<br><br># Loop through each athlete and each race checkpoint<br>for i in range(n_samples):<br>    acc_time = df_scaled.iloc[i][race_seq_cols].values.astype(float)<br>    <br>    for t in range(n_timesteps): <br>        X[i, t, 0] = acc_time[t]  # Feature 1 Current accumulated time<br>        X[i, t, 1] = age_vals[i]  # Feature 2 Age<br>        X[i, t, 2] = gender_vals[i]  # Feature 3 Gender<br>        X[i, t, 3] = pro_vals[i]  # Feature 4 Pro/Open status<br>        <br>        y[i, t, 0] = total_time_vals[i] # The target: Total Time<br><br>print(X[0])<br>print(y[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vt-qTrumkbEBu3cDcw-MNg.png" /></figure><h4>Train/Test Split</h4><p>Finally, we split our data into training and testing sets to ensure we can validate our model on unseen athletes. To keep our evaluation fair across the board, we use <strong>stratified sampling</strong> on the age groups. This ensures that both our training and testing sets have a balanced representation of every age bracket, from the young guns to the masters.</p><pre>from sklearn.model_selection import train_test_split<br><br>age_labels = df_scaled[&quot;age_group&quot;]<br><br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, <br>    y, <br>    test_size=0.2, <br>    random_state=15,  # 15 to honour the Elite 15<br>    stratify=age_labels)<br><br>print(X_train.shape)<br>print(X_test.shape)</pre><pre># Output<br>(3634, 15, 4)  # Train<br>(909, 15, 4)  # Test</pre><h3>Step 4: Building the Bidirectional LSTM</h3><h4>Designing the Model Architecture</h4><p>We utilize a <strong>Bidirectional LSTM</strong>. This allows the model to look at the race sequence both forward and backward, helping it understand the “pacing profile” of different athletes more effectively.</p><p>For demonstration, we stack three LSTM layers (128, 64, and 32 units, respectively) on top of each other. Between these recurrent layers, we use <strong>Dropout (0.3) </strong>— the regularization technique that randomly “turns off” 30% of the neurons during training — to prevent overfitting.</p><p><strong>The TimeDistributed</strong> <strong>layers</strong> at the end are the most crucial design choice. In a standard time-series model, the network processes the whole sequence and spits out one final prediction at the very end. However, wrapping our Dense layers in these layers tells the model to output a finish time prediction at <em>every single checkpoint</em>. As a result, our model doesn’t have to wait until the end of the race to be useful. It can dynamically update its forecast as an athlete crosses every timing mat — in our case, the in and out mat of each station.</p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import LSTM, Dense, TimeDistributed, Input, Dropout, Bidirectional<br>from tensorflow.keras.optimizers import Adam<br><br>model = Sequential([<br>    Input(shape=(n_timesteps, n_feats)),<br>    Bidirectional(LSTM(128, return_sequences=True)),<br>    Dropout(0.3),<br>    LSTM(64, return_sequences=True),<br>    Dropout(0.3),<br>    LSTM(32, return_sequences=True),<br>    TimeDistributed(Dense(16, activation=&quot;relu&quot;)),<br>    TimeDistributed(Dense(1)),<br>])</pre><p>Finally, we compile the model using the <strong>Adam optimizer</strong>. We apply the <em>gradient clipping </em>technique with “clipvalue”. RNNs and LSTMs are prone to the “exploding gradient” problem, where math errors compound and cause the model to crash during training. This clip value is like a safety net, keeping our weight updates stable. We optimize the network using Mean Squared Error (MSE) to heavily penalize large mistakes, while tracking Mean Absolute Error (MAE) so we can eventually read our model&#39;s accuracy in straightforward seconds.</p><pre>optimizer = Adam(learning_rate=0.001, clipvalue=1.0)<br><br>model.compile(optimizer=optimizer, loss=&quot;mse&quot;, metrics=[&quot;mae&quot;])<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVvSG_Om4Vstyh6BfFv4fQ.png" /></figure><h3>Step 5: Training the Model</h3><p>It’s time to really push the training button. In deep learning, training usually occurs over several <strong>epochs</strong>, where one epoch represents a single complete pass of the entire training dataset through the neural network. However, setting a high number of epochs can lead to overfitting. To prevent overfitting and optimize our training, we introduce two powerful Keras “Callbacks”: <strong>EarlyStopping</strong> and <strong>ReduceLROnPlateau</strong>.</p><p><strong>EarlyStopping: Knowing When to Quit</strong></p><p>We monitor the Validation Mean Absolute Error (val_mae). The patient parameter means that if the model&#39;s accuracy on the validation set doesn&#39;t improve for 10 consecutive epochs, training will stop automatically. More importantly, the restore_best_weights ensures that we don&#39;t get stuck with the weights from the final overfitted epoch, but use its most accurate state.</p><pre>from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau<br><br>print(&quot;Training HYROX LSTM...&quot;)<br><br>early_stop = EarlyStopping(<br>    monitor=&quot;val_mae&quot;,<br>    patience=10,<br>    restore_best_weights=True<br>)</pre><h4>ReduceLROnPlateau: Fine-Tuning the Learning Rate</h4><p>As the model gets closer to the optimal solution, taking large steps (our initial learning rate) can cause it to overshoot the target. This callback watches the same Validation Mean Absolute Error. If it plateaus for just 5 epochs (patience=5), the learning rate is drastically reduced (factor=0.2), allowing the model to make finer, more precise adjustments.</p><pre>lr_scheduler = ReduceLROnPlateau(<br>    monitor=&quot;val_mae&quot;,<br>    factor=0.2,<br>    patience=5,<br>    min_lr=0.00001<br>)</pre><p><strong>The Training Execution</strong></p><p>When we finally call model.fit(). We set aside 20% of our training data to for validation set (validation_split=0.2). We use a small batch size (batch_size=8), which means the model updates its weights after evaluating every 8 athletes. The smaller batch size often helps models generalize better.</p><pre>history = model.fit(<br>    X_train, y_train,<br>    epochs=200,<br>    batch_size=8,<br>    validation_split=0.2,<br>    callbacks=[early_stop, lr_scheduler],<br>    verbose=1<br>)</pre><pre>Training HYROX LSTM...<br>Epoch 1/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 9s 14ms/step - loss: 0.0046 - mae: 0.0416 - val_loss: 7.6160e-04 - val_mae: 0.0195 - learning_rate: 0.0010<br>Epoch 2/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 0.0012 - mae: 0.0251 - val_loss: 6.2500e-04 - val_mae: 0.0175 - learning_rate: 0.0010<br>Epoch 3/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 0.0011 - mae: 0.0238 - val_loss: 0.0011 - val_mae: 0.0275 - learning_rate: 0.0010<br>Epoch 4/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 9.8032e-04 - mae: 0.0224 - val_loss: 7.6520e-04 - val_mae: 0.0200 - learning_rate: 0.0010<br>Epoch 5/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 8.3673e-04 - mae: 0.0202 - val_loss: 0.0011 - val_mae: 0.0228 - learning_rate: 0.0010<br>Epoch 6/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 8.2946e-04 - mae: 0.0204 - val_loss: 0.0012 - val_mae: 0.0260 - learning_rate: 0.0010<br>Epoch 7/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 8.2158e-04 - mae: 0.0204 - val_loss: 5.3696e-04 - val_mae: 0.0153 - learning_rate: 0.0010<br>Epoch 8/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 8.0553e-04 - mae: 0.0199 - val_loss: 9.3926e-04 - val_mae: 0.0223 - learning_rate: 0.0010<br>Epoch 9/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 9.3185e-04 - mae: 0.0211 - val_loss: 5.1298e-04 - val_mae: 0.0154 - learning_rate: 0.0010<br>Epoch 10/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 15ms/step - loss: 7.5839e-04 - mae: 0.0197 - val_loss: 8.1433e-04 - val_mae: 0.0195 - learning_rate: 0.0010<br>Epoch 11/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 9.2749e-04 - mae: 0.0211 - val_loss: 0.0015 - val_mae: 0.0264 - learning_rate: 0.0010<br>Epoch 12/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 7.7946e-04 - mae: 0.0194 - val_loss: 4.8987e-04 - val_mae: 0.0157 - learning_rate: 0.0010<br>Epoch 13/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 5.1620e-04 - mae: 0.0156 - val_loss: 3.9358e-04 - val_mae: 0.0127 - learning_rate: 2.0000e-04<br>Epoch 14/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.9392e-04 - mae: 0.0149 - val_loss: 3.8777e-04 - val_mae: 0.0125 - learning_rate: 2.0000e-04<br>Epoch 15/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.8954e-04 - mae: 0.0148 - val_loss: 3.9578e-04 - val_mae: 0.0125 - learning_rate: 2.0000e-04<br>Epoch 16/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.7591e-04 - mae: 0.0147 - val_loss: 5.0496e-04 - val_mae: 0.0143 - learning_rate: 2.0000e-04<br>Epoch 17/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.7102e-04 - mae: 0.0148 - val_loss: 4.0467e-04 - val_mae: 0.0127 - learning_rate: 2.0000e-04<br>Epoch 18/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.9600e-04 - mae: 0.0149 - val_loss: 3.7626e-04 - val_mae: 0.0120 - learning_rate: 2.0000e-04<br>Epoch 19/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.5517e-04 - mae: 0.0143 - val_loss: 3.7034e-04 - val_mae: 0.0118 - learning_rate: 2.0000e-04<br>Epoch 20/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 6s 17ms/step - loss: 4.6274e-04 - mae: 0.0142 - val_loss: 4.0959e-04 - val_mae: 0.0128 - learning_rate: 2.0000e-04<br>Epoch 21/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 15ms/step - loss: 4.5944e-04 - mae: 0.0143 - val_loss: 4.0856e-04 - val_mae: 0.0134 - learning_rate: 2.0000e-04<br>Epoch 22/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.5479e-04 - mae: 0.0145 - val_loss: 4.2165e-04 - val_mae: 0.0130 - learning_rate: 2.0000e-04<br>Epoch 23/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.7577e-04 - mae: 0.0144 - val_loss: 4.5414e-04 - val_mae: 0.0139 - learning_rate: 2.0000e-04<br>Epoch 24/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 4.4692e-04 - mae: 0.0140 - val_loss: 4.0794e-04 - val_mae: 0.0120 - learning_rate: 2.0000e-04<br>Epoch 25/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 4.0121e-04 - mae: 0.0132 - val_loss: 3.8323e-04 - val_mae: 0.0114 - learning_rate: 4.0000e-05<br>Epoch 26/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.8143e-04 - mae: 0.0130 - val_loss: 3.8282e-04 - val_mae: 0.0115 - learning_rate: 4.0000e-05<br>Epoch 27/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.8184e-04 - mae: 0.0128 - val_loss: 4.1694e-04 - val_mae: 0.0125 - learning_rate: 4.0000e-05<br>Epoch 28/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 15ms/step - loss: 3.8371e-04 - mae: 0.0129 - val_loss: 3.7388e-04 - val_mae: 0.0117 - learning_rate: 4.0000e-05<br>Epoch 29/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 6s 15ms/step - loss: 3.7649e-04 - mae: 0.0128 - val_loss: 3.7027e-04 - val_mae: 0.0113 - learning_rate: 4.0000e-05<br>Epoch 30/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 6s 15ms/step - loss: 3.8179e-04 - mae: 0.0129 - val_loss: 3.8269e-04 - val_mae: 0.0115 - learning_rate: 4.0000e-05<br>Epoch 31/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.7341e-04 - mae: 0.0127 - val_loss: 3.7980e-04 - val_mae: 0.0112 - learning_rate: 1.0000e-05<br>Epoch 32/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.6324e-04 - mae: 0.0125 - val_loss: 3.7977e-04 - val_mae: 0.0112 - learning_rate: 1.0000e-05<br>Epoch 33/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 6s 17ms/step - loss: 3.6100e-04 - mae: 0.0126 - val_loss: 3.8478e-04 - val_mae: 0.0114 - learning_rate: 1.0000e-05<br>Epoch 34/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.7102e-04 - mae: 0.0126 - val_loss: 3.7672e-04 - val_mae: 0.0114 - learning_rate: 1.0000e-05<br>Epoch 35/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.7154e-04 - mae: 0.0128 - val_loss: 3.7433e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 36/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6832e-04 - mae: 0.0126 - val_loss: 3.6662e-04 - val_mae: 0.0109 - learning_rate: 1.0000e-05<br>Epoch 37/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6029e-04 - mae: 0.0125 - val_loss: 3.8004e-04 - val_mae: 0.0114 - learning_rate: 1.0000e-05<br>Epoch 38/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.5522e-04 - mae: 0.0124 - val_loss: 3.7671e-04 - val_mae: 0.0113 - learning_rate: 1.0000e-05<br>Epoch 39/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.6046e-04 - mae: 0.0125 - val_loss: 3.7410e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 40/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6353e-04 - mae: 0.0125 - val_loss: 3.8120e-04 - val_mae: 0.0112 - learning_rate: 1.0000e-05<br>Epoch 41/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6602e-04 - mae: 0.0125 - val_loss: 3.7917e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 42/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6334e-04 - mae: 0.0125 - val_loss: 3.6973e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 43/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.6274e-04 - mae: 0.0124 - val_loss: 3.7225e-04 - val_mae: 0.0109 - learning_rate: 1.0000e-05<br>Epoch 44/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.6784e-04 - mae: 0.0125 - val_loss: 3.7821e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 45/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.4982e-04 - mae: 0.0123 - val_loss: 3.6986e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 46/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.5511e-04 - mae: 0.0123 - val_loss: 3.7193e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 47/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6539e-04 - mae: 0.0125 - val_loss: 3.7037e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 48/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 15ms/step - loss: 3.5968e-04 - mae: 0.0124 - val_loss: 3.7994e-04 - val_mae: 0.0113 - learning_rate: 1.0000e-05<br>Epoch 49/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 15ms/step - loss: 3.4927e-04 - mae: 0.0123 - val_loss: 3.6464e-04 - val_mae: 0.0108 - learning_rate: 1.0000e-05<br>Epoch 50/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.5758e-04 - mae: 0.0124 - val_loss: 3.6665e-04 - val_mae: 0.0109 - learning_rate: 1.0000e-05<br>Epoch 51/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.4534e-04 - mae: 0.0122 - val_loss: 3.6869e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 52/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.5519e-04 - mae: 0.0124 - val_loss: 3.7172e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 53/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 15ms/step - loss: 3.6147e-04 - mae: 0.0124 - val_loss: 3.6723e-04 - val_mae: 0.0107 - learning_rate: 1.0000e-05<br>Epoch 54/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.6717e-04 - mae: 0.0125 - val_loss: 3.6262e-04 - val_mae: 0.0107 - learning_rate: 1.0000e-05<br>Epoch 55/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.6201e-04 - mae: 0.0124 - val_loss: 3.6882e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 56/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.4684e-04 - mae: 0.0123 - val_loss: 3.6476e-04 - val_mae: 0.0108 - learning_rate: 1.0000e-05<br>Epoch 57/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.5354e-04 - mae: 0.0124 - val_loss: 3.7536e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 58/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.5102e-04 - mae: 0.0123 - val_loss: 3.7749e-04 - val_mae: 0.0113 - learning_rate: 1.0000e-05<br>Epoch 59/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.4282e-04 - mae: 0.0121 - val_loss: 3.7891e-04 - val_mae: 0.0111 - learning_rate: 1.0000e-05<br>Epoch 60/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 6s 16ms/step - loss: 3.5074e-04 - mae: 0.0123 - val_loss: 3.7715e-04 - val_mae: 0.0109 - learning_rate: 1.0000e-05<br>Epoch 61/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.5023e-04 - mae: 0.0123 - val_loss: 3.7217e-04 - val_mae: 0.0110 - learning_rate: 1.0000e-05<br>Epoch 62/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 13ms/step - loss: 3.5414e-04 - mae: 0.0123 - val_loss: 3.6917e-04 - val_mae: 0.0108 - learning_rate: 1.0000e-05<br>Epoch 63/200<br>364/364 ━━━━━━━━━━━━━━━━━━━━ 5s 14ms/step - loss: 3.5584e-04 - mae: 0.0123 - val_loss: 3.6359e-04 - val_mae: 0.0108 - learning_rate: 1.0000e-05</pre><p>Phew! Depending on your random seed, the training duration will vary; in our demo, the model stops around <strong>Epoch 63. </strong>We can see the <strong>MAE (Mean Absolute Error)</strong> and <strong>Loss</strong> steadily decrease. This tells us that the model is rapidly learning the relationship between split times and finish times. A key moment occurs at <strong>Epoch 13</strong>, where the ReduceLROnPlateau callback kicks in, dropping the learning rate from 0.001 to 0.0002. This allows the model to “fine-tune” its weights, leading to a significant drop in error. By the time the model approaches <strong>Epoch 63</strong>, the validation MAE has stabilized at an impressively low value (approx. 0.0108 in scaled units).</p><h3>Step 6: Look at the Model’s Performance</h3><h4>Model’s Learning Curve</h4><p>We can visualize the model’s performance. Here, we create two plots: one for <strong>MAE (Mean Absolute Error)</strong> and one for <strong>Loss (MSE)</strong>.</p><pre>import matplotlib.pyplot as plt<br><br>def plot_history(history):<br>    mae = history.history[&#39;mae&#39;]<br>    val_mae = history.history[&#39;val_mae&#39;]<br>    loss = history.history[&#39;loss&#39;]<br>    val_loss = history.history[&#39;val_loss&#39;]<br>    epochs = range(1, len(mae) + 1)<br><br>    plt.figure(figsize=(15, 6))<br><br>    # MAE<br>    plt.subplot(1, 2, 1)<br>    plt.plot(epochs, mae, &#39;b-&#39;, label=&#39;Training MAE&#39;, alpha=0.7)<br>    plt.plot(epochs, val_mae, &#39;r-&#39;, label=&#39;Validation MAE&#39;, linewidth=2)<br>    plt.title(&#39;Training and Validation MAE&#39;, fontsize=14)<br>    plt.xlabel(&#39;Epochs&#39;)<br>    plt.ylabel(&#39;MAE (Seconds)&#39;)<br>    plt.legend()<br>    plt.grid(True, alpha=0.3)<br><br>    # MSE<br>    plt.subplot(1, 2, 2)<br>    plt.plot(epochs, loss, &#39;b-&#39;, label=&#39;Training Loss&#39;, alpha=0.7)<br>    plt.plot(epochs, val_loss, &#39;r-&#39;, label=&#39;Validation Loss&#39;, linewidth=2)<br>    plt.title(&#39;Training and Validation Loss (MSE)&#39;, fontsize=14)<br>    plt.xlabel(&#39;Epochs&#39;)<br>    plt.ylabel(&#39;Loss&#39;)<br>    plt.legend()<br>    plt.grid(True, alpha=0.3)<br><br>    plt.tight_layout()<br>    plt.show()<br><br><br>plot_history(history)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB4kGz3mdwhuv02p3dwOgA.png" /></figure><p>On the left, we see the <strong>Mean Absolute Error (MAE)</strong> plummeting within the first few epochs, indicating the model quickly grasped the fundamental pacing patterns of the race. On the right, the <strong>Loss (MSE)</strong> follows a similar pattern. Most importantly, the training and validation lines stay closely aligned as they plateau, indicating that the model is generalizing quite well across different athletes rather than simply memorizing the training data.</p><h4>Model’s Prediction Ability</h4><p>To see how our model performs in the real world, we need to convert our predictions from the 0–1 scale to total seconds (remember that we scaled the data with MinMaxScaler). Plotting the <strong>Actual vs. Predicted</strong> finish times on a scatter plot shows how accurate the model is. The diagonal dashed line represents the “Perfect Prediction” — the closer the dots are to this line, the better the model.</p><p>For better visibility, we also color-code the points by their error magnitude — blue dots show where the model predicted a faster time than reality, while red dots indicate where it predicted a slower time.</p><p>Well, our model is pretty good. The majority of points hugging the perfect prediction line. With some predictions that are way slower than the actual finished time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0DHnIY4JoF7AqmwTtzoAA.png" /></figure><p>We can also break down the performance across different divisions and genders, so we can observe how the predictions consistently perform across all categories.</p><p>We can look at the Pro/Open and Men/Women division. We can see from the plot that the LSTM maintains a high level of precision regardless of the athlete’s competitive tier.</p><pre>import seaborn as sns<br><br># Add metadata to results_df<br>results_df[&#39;Gender_Name&#39;] = [&quot;Women&quot; if g &gt; 0.5 else &quot;Men&quot; for g in X_test[:, 0, 2]]<br>results_df[&#39;Division_Type&#39;] = [&quot;Pro&quot; if p &gt; 0.5 else &quot;Open&quot; for p in X_test[:, 0, 3]]<br><br># Perfect Prediction line<br>numeric_cols = [&quot;Predicted_Total_Time&quot;, &quot;Actual_Total_Time&quot;]<br>all_values = results_df[numeric_cols]<br>lims = [all_values.min().min(), all_values.max().max()]<br><br># Plot Pro vs Open Division accuracy<br>g = sns.FacetGrid(results_df, col=&quot;Division_Type&quot;, hue=&quot;Gender_Name&quot;, height=6, aspect=1.2)<br>g.map(sns.scatterplot, &quot;Actual_Total_Time&quot;, &quot;Predicted_Total_Time&quot;, alpha=0.9, s=70)<br><br>for ax in g.axes.flat:<br>    ax.plot(lims, lims, &#39;k--&#39;, alpha=0.5, label=&quot;Perfect Prediction&quot;)<br>    ax.set_xlabel(&quot;Actual Time (sec)&quot;)<br>    ax.set_ylabel(&quot;Predicted Time (sec)&quot;)<br>    ax.grid(True, alpha=0.3) <br><br>g.add_legend(title=&quot;Gender&quot;)<br>g.fig.suptitle(&quot;Comparison: Open vs. Pro Prediction Accuracy by Gender&quot;, y=1.05, fontsize=16)<br>plt.tight_layout()<br>plt.show()</pre><p>We can see that the LSTM maintains a high level of precision regardless of the athlete’s competitive tier. The tight clustering of both male and female data points along the “Perfect Prediction” line indicates that the model has successfully identified universal pacing cues. Whether it’s the fast-twitch intensity of a Pro racer or the steady endurance of an Open-category athlete, the model adapts its forecast accurately, proving it is a reliable tool for any HYROX participant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xrL04EpUiZXToxhNMQqgw.png" /></figure><p>Let’s dig deep into the age group. By breaking down the predictions — from the 16–24 youngsters to the 60+ veterans — we can see that the LSTM can still perform pretty well across all nine age groups.</p><pre># Rescale Age back to group numbers (1-9)<br>age_min, age_max = 1, 9 <br>age_groups_rescaled = np.round(X_test[:, 0, 1] * (age_max - age_min) + age_min).astype(int)<br>ordered_ages = [<br>        &#39;16-24&#39;, &#39;25-29&#39;, &#39;30-34&#39;, &#39;35-39&#39;, &#39;40-44&#39;, <br>        &#39;45-49&#39;, &#39;50-54&#39;, &#39;55-59&#39;, &#39;60+&#39;<br>    ]<br>age_mapping = {age: i + 1 for i, age in enumerate(ordered_ages)}<br><br># Create reverse map to get age group names<br>reverse_age_map = {v: k for k, v in age_mapping.items()}<br>results_df[&#39;Age_Group_Name&#39;] = [reverse_age_map.get(a, &quot;Unknown&quot;) for a in age_groups_rescaled]<br><br># Sort age groups<br>age_order = [&quot;16-24&quot;, &quot;25-29&quot;, &quot;30-34&quot;, &quot;35-39&quot;, &quot;40-44&quot;, &quot;45-49&quot;, &quot;50-54&quot;, &quot;55-59&quot;, &quot;60+&quot;]<br>results_df[&#39;Age_Group_Name&#39;] = pd.Categorical(results_df[&#39;Age_Group_Name&#39;], categories=age_order, ordered=True)<br><br># Create a grid of scatter plots<br>g = sns.relplot(<br>    data=results_df,<br>    x=&quot;Actual_Total_Time&quot;,<br>    y=&quot;Predicted_Total_Time&quot;,<br>    hue=&quot;Gender_Name&quot;,    # Distinguish by Gender<br>    col=&quot;Age_Group_Name&quot;,  # Separate subplots for each Age Group<br>    col_wrap=3,            # Display 3 plots per row<br>    kind=&quot;scatter&quot;,<br>    alpha=0.9,<br>    s=70,<br>    height=4,<br>    aspect=1,<br>    edgecolor=&quot;w&quot;,      <br>    linewidth=0.5<br>)<br><br># Define chart limits based on actual data range<br>lims = [results_df[[&quot;Actual_Total_Time&quot;, &quot;Predicted_Total_Time&quot;]].min().min(),<br>        results_df[[&quot;Actual_Total_Time&quot;, &quot;Predicted_Total_Time&quot;]].max().max()]<br><br># Draw the &#39;Perfect Prediction&#39; diagonal line on every subplot<br>for ax in g.axes.flat:<br>    ax.plot(lims, lims, color=&quot;black&quot;, linestyle=&#39;--&#39;, alpha=0.5, label=&#39;Perfect Prediction&#39;)<br>    ax.set_xlabel(&quot;Actual (sec)&quot;)<br>    ax.set_ylabel(&quot;Predicted (sec)&quot;)<br>    ax.set_xlim(lims)<br>    ax.set_ylim(lims)<br><br>g.fig.suptitle(&quot;Model Accuracy: Age Group Breakdown by Gender&quot;, y=1.05, fontsize=18)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*yxUY3Hldejw4oMaHazC8DQ.png" /></figure><h3>Conclusion: From Data Points to Race Strategies</h3><p>As we wrap up this third part of the journey, it’s clear that these data points are far more than just numbers on a screen. For those of us who have stood at the starting line, we know that every split time represents a real moment of grit. By building this model, we haven’t just created a piece of code; we’ve captured the universal rhythm of fatigue and perseverance that connects every athlete on the track.</p><p>Personally, as I look at these accuracy curves, I’m also playing the long game. My goal? A podium finish in my 70s. While others are sprinting for trophies in their 30s, I’m using this LSTM to calculate exactly how many decades of steady pacing I need to outlast the competition. By the time I hit that 70+ bracket, my biggest rival won’t be a pro athlete.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f2d6fc6e79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HYROX Data Science Series Part 2: What 4000+ athletes in Bangkok 2026 taught us about age, fatigue…]]></title>
            <link>https://ll-monkey.medium.com/hyrox-data-science-series-part-2-what-4000-athletes-in-bangkok-2026-taught-us-about-age-fatigue-e6b4b6c35b98?source=rss-5a15a144aae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b4b6c35b98</guid>
            <category><![CDATA[sport-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[hyrox]]></category>
            <category><![CDATA[data-visualization-python]]></category>
            <dc:creator><![CDATA[LL-Monkey]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 13:33:41 GMT</pubDate>
            <atom:updated>2026-04-01T13:36:41.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>HYROX Data Science Series Part 2: <strong>What 4000+ athletes in Bangkok 2026 taught us about age, fatigue, and the brutal reality of the Roxzone.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWeDoCsV4meYYCCSnzMjpA.jpeg" /></figure><p>Welcome back to the HYROX Data Science Series! In Part 1, we built an engine to scrape and collect the HYROX Bangkok 2026 race data. If you happened to miss it, you can catch up on how we built our web scraper here: <a href="https://medium.com/@pdontr/from-the-race-track-to-the-data-pipeline-scraping-hyrox-bangkok-2026-results-part-1-38ee8a79e458"><em>HYROX Data Science Series Part 1: Scrapping Bangkok 2026 Race Data from the Track with Python</em></a><em>.</em></p><p>Before we jump into the data, a quick confession: having survived the Open division twice myself, my doubles partner and I recently started joking about stepping up to the Pro division for our next race. <em>“How much harder could it be, right?”</em> we laughed.</p><p>Well, as a data enthusiast, I decided to stop guessing and ask the data. By merging the datasets of four major divisions from the Bangkok race — Men Open, Women Open, Men Pro, and Women Pro — I wanted to see exactly what separates the elites from the rest of us (us meaning my partner and I). Spoiler alert: The data humbled us completely.</p><p>Here is what over 4,000 athletes taught us about surviving the ultimate fitness race.</p><h3>Step 1: Gathering the Pieces (Loading &amp; Merging)</h3><p>Depending on how you use Part 1, you might have one large dataset or seperated ones for each division. I did the latter. Hence, our first task was to load them into a single, massive pandas DataFrame.</p><pre># install required libaries<br>pip install pandas numpy matplotlib seaborn</pre><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Set plotting style<br>sns.set_theme(style=&quot;whitegrid&quot;)<br>plt.rcParams[&quot;figure.figsize&quot;] = (12, 8)<br><br># Our scraped datasets<br>files = [<br>    &quot;hyrox_bkk_men_2026.csv&quot;,<br>    &quot;hyrox_bkk_women_2026.csv&quot;,<br>    &quot;hyrox_bkk_pro_men_2026.csv&quot;,<br>    &quot;hyrox_bkk_pro_women_2026.csv&quot;<br>]<br><br># Load and concatenate datasets<br>df = pd.concat((pd.read_csv(f) for f in files), ignore_index=True)<br>print(f&quot;Total rows loaded: {len(df)}&quot;)</pre><pre># Output<br>Total rows loaded: 4693</pre><h3>Step 2: Data Cleaning and Time Conversion</h3><p>Before we could generate any exciting charts, we had to face the reality of real-world sports data: it’s messy. Race times are recorded as strings in HH:MM:SS or MM:SS format (the result of our scraper code), which is useless for mathematical analysis. We needed everything in total seconds.</p><p>Furthermore, sometimes timing chips fail, athletes DNF (Did Not Finish), or records show up with a literal hyphen (-) or a null string instead of a time. Feeding this into a chart would lead to incorrect visualization or even break the code.</p><p>Here is how we convert the time data and cleaned the messy data:</p><pre># Function to convert HH:MM:SS to seconds<br>def time_to_secs(t):<br>    if pd.isna(t): return np.nan<br>    t = str(t).strip()<br>    if t == &#39;-&#39; or t == &#39; &#39;: return np.nan<br>    parts = t.split(&#39;:&#39;)<br>    if len(parts) == 3:<br>        return int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2])<br>    elif len(parts) == 2:<br>        return int(parts[0]) * 60 + int(parts[1])<br>    return np.nan<br><br># Select time-based columns (skipping &#39;Time of Day&#39; columns)<br>time_cols = [col for col in df.columns[5:] if &#39;tod&#39; not in col.lower()]<br><br>for col in time_cols:<br>    df[col] = df[col].apply(time_to_secs)<br><br># Clean up and drop rows with missing data<br>df.replace(r&#39;^\s*-\s*$&#39;, np.nan, regex=True, inplace=True) <br>df.replace(&#39;null&#39;, np.nan, inplace=True) <br>df.replace(&#39; &#39;, np.nan, inplace=True)<br>df = df.dropna()<br>print(f&quot;Total rows after cleaning: {len(df)}&quot;)</pre><pre># Output<br>Total rows after cleaning: 4549</pre><h3>Step 3: Feature Engineering</h3><p>Next, we needed to extract categorical features from the raw division column (e.g., extracting &quot;Men&quot;, &quot;Pro&quot;, and &quot;30-34&quot; from a string like &quot;HYROX PRO MEN 30-34&quot;).</p><p>One tricky part here was age. There were some rows with a null age. Also, some older categories contain fewer data points, which makes it hard to extract any statistically significant information. Let&#39;s handle these age issues.</p><pre># Look at unique division categories<br>df[&quot;division&quot;].unique()</pre><pre># Output<br>array([&#39;HYROX MEN 16-24&#39;, &#39;HYROX MEN 30-34&#39;, &#39;HYROX MEN 35-39&#39;,<br>       &#39;HYROX MEN 25-29&#39;, &#39;HYROX MEN 40-44&#39;, &#39;HYROX MEN 45-49&#39;,<br>       &#39;HYROX MEN 50-54&#39;, &#39;HYROX MEN 55-59&#39;, &#39;HYROX MEN 60-64&#39;,<br>       &#39;HYROX MEN 65-69&#39;, &#39;HYROX MEN null&#39;, &#39;HYROX MEN 70-74&#39;,<br>       &#39;HYROX WOMEN 35-39&#39;, &#39;HYROX WOMEN 30-34&#39;, &#39;HYROX WOMEN 25-29&#39;,<br>       &#39;HYROX WOMEN 40-44&#39;, &#39;HYROX WOMEN 16-24&#39;, &#39;HYROX WOMEN null&#39;,<br>       &#39;HYROX WOMEN 45-49&#39;, &#39;HYROX WOMEN 50-54&#39;, &#39;HYROX WOMEN 55-59&#39;,<br>       &#39;HYROX WOMEN 60-64&#39;, &#39;HYROX WOMEN 70-74&#39;, &#39;HYROX WOMEN 65-69&#39;,<br>       &#39;HYROX PRO MEN 30-34&#39;, &#39;HYROX PRO MEN 40-44&#39;,<br>       &#39;HYROX PRO MEN 16-24&#39;, &#39;HYROX PRO MEN 25-29&#39;,<br>       &#39;HYROX PRO MEN 35-39&#39;, &#39;HYROX PRO MEN 45-49&#39;,<br>       &#39;HYROX PRO MEN 50-54&#39;, &#39;HYROX PRO MEN 55-59&#39;,<br>       &#39;HYROX PRO MEN 60-64&#39;, &#39;HYROX PRO WOMEN 35-39&#39;,<br>       &#39;HYROX PRO WOMEN 25-29&#39;, &#39;HYROX PRO WOMEN 40-44&#39;,<br>       &#39;HYROX PRO WOMEN 16-24&#39;, &#39;HYROX PRO WOMEN 30-34&#39;,<br>       &#39;HYROX PRO WOMEN 45-49&#39;, &#39;HYROX PRO WOMEN 50-54&#39;,<br>       &#39;HYROX PRO WOMEN 55-59&#39;], dtype=object)</pre><pre><br># Extract Gender and Pro status<br>df[&quot;gender&quot;] = df[&quot;division&quot;].apply(lambda x: &quot;WOMEN&quot; if &quot;WOMEN&quot; in str(x).upper() else &quot;MEN&quot;)<br>df[&quot;is_pro&quot;] = df[&quot;division&quot;].apply(lambda x: &quot;PRO&quot; if &quot;PRO&quot; in str(x).upper() else &quot;OPEN&quot;)<br>df[&quot;category&quot;] = df[&quot;gender&quot;] + &quot; &quot; + df[&quot;is_pro&quot;]<br><br># Safely extract and format Age Groups<br>df[&quot;age_raw&quot;] = df[&quot;division&quot;].str.extract(r&quot;(\d{2}-\d{2}|\d{2}\+)&quot;)<br><br># Group 60+ athletes to avoid losing data<br>sixty_plus = [&quot;60-64&quot;, &quot;65-69&quot;, &quot;70-74&quot;, &quot;75-79&quot;, &quot;80-84&quot;, &quot;85-89&quot;]<br>df.loc[df[&quot;age_raw&quot;].isin(sixty_plus), &quot;age_raw&quot;] = &quot;60+&quot;<br><br>age_order = [&quot;16-24&quot;, &quot;25-29&quot;, &quot;30-34&quot;, &quot;35-39&quot;, &quot;40-44&quot;, &quot;45-49&quot;, &quot;50-54&quot;, &quot;55-59&quot;, &quot;60+&quot;]<br>df[&quot;age_group&quot;] = pd.Categorical(df[&quot;age_raw&quot;], categories=age_order, ordered=True)<br><br># Finally, drop rows that are missing critical target variables<br>df_clean = df.dropna(subset=[&quot;Total Time&quot;, &quot;age_group&quot;]).copy()<br>print(f&quot;Final clean dataset ready: {len(df_clean)} athletes.&quot;)</pre><pre># Output<br>Final clean dataset ready: 4543 athletes.</pre><h3>Step 4: Visualizing the Data</h3><h4>The Division Landscape: Pro vs. Open</h4><p>First, let’s look at the overall finish times across the four main categories using a Violin Plot.</p><pre>sns.violinplot(data=df_clean, x=&quot;category&quot;, y=&quot;Total Time&quot;, palette=&quot;magma&quot;)<br>plt.title(&quot;Finish Time Distribution by Division&quot;, fontsize=16)<br>plt.ylabel(&quot;Total Time (Seconds)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXF_kKMNtQsCGe3ScdMlkA.png" /></figure><p>It is obvious that the majority of the athletes in the Pro division are much faster than those in the Open division. Only a select few in the Open division can truly compete with the Pros. The data clearly shows that if you want to stand on the Pro podium, your margin for error is razor-thin. (Looking at this, my partner and I might need to reconsider our bold Pro division plans!)</p><h4>Does Age Really Matter?</h4><p>One of the most inspiring things about HYROX is the diversity of its participants. But does peak performance strictly belong to the 20-somethings? (If so, I might need to stick with being a ‘recreational athlete’).</p><p>We plotted the Total Finish Time across all Age Groups and Genders, using a boxplot with individual data points overlaid as a stripplot to show the true density of the crowd.</p><pre>sns.boxplot(data=df_clean, x=&quot;age_group&quot;, y=&quot;Total Time&quot;, color=&quot;whitesmoke&quot;, showfliers=False, width=0.5)<br>sns.stripplot(data=df_clean, x=&quot;age_group&quot;, y=&quot;Total Time&quot;, hue=&quot;gender&quot;, palette=&quot;plasma&quot;, jitter=True, alpha=0.7, dodge=False, size=5)<br>plt.title(&quot;Race Performance across Age Groups&quot;, fontsize=16)<br>plt.xlabel(&quot;Age Group&quot;, fontsize=12)<br>plt.ylabel(&quot;Total Time (Seconds)&quot;, fontsize=12)<br>plt.legend(title=&quot;Gender&quot;, bbox_to_anchor=(1.02, 1), loc=&quot;upper left&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoJBv92CMjv3KDG1I7tuEg.png" /></figure><p>The results are fascinating. The “sweet spot” for HYROX isn’t necessarily the youngest age bracket (16–24). The median times for athletes in the <strong>30–34</strong> and <strong>35–39</strong> age groups are highly competitive. Well, this suggests that my road to the podium in my 70s might still work out!</p><h4>The Ultimate Filter: What Makes a Pro a Pro?</h4><p>HYROX consists of 8 functional workout stations. If you want to move from the Open division to the Pro division, which workout should you focus on? Well, it should be note for those who are new to HYROX that there are weight differences between Open and Pro division. For more details, please visit: <a href="https://hyrox.com/the-fitness-race/">HYROX page</a>.</p><p>To answer this, we calculated the <strong>Percentage Difference</strong> in average time between Open and Pro athletes for each station.</p><pre>workout_cols = [&quot;SkiErg&quot;, &quot;Sled Push&quot;, &quot;Sled Pull&quot;, &quot;Burpee Broad Jump&quot;, <br>                &quot;Row&quot;, &quot;Farmers Carry&quot;, &quot;Sandbag Lunges&quot;, &quot;Wall Balls&quot;]<br>workout_names = [&quot;SkiErg&quot;, &quot;Sled Push&quot;, &quot;Sled Pull&quot;, &quot;Burpees&quot;, &quot;Row&quot;, &quot;Farmers Carry&quot;, &quot;Lunges&quot;, &quot;Wall Balls&quot;]<br><br>pro_means = df_clean[df_clean[&quot;is_pro&quot;] == &quot;PRO&quot;][workout_cols].mean()<br>open_means = df_clean[df_clean[&quot;is_pro&quot;] == &quot;OPEN&quot;][workout_cols].mean()<br>diff_pct = ((open_means - pro_means) / pro_means) * 100<br><br>sns.barplot(x=diff_pct.values, y=workout_names, palette=&quot;rocket&quot;)<br>plt.title(&quot;The Ultimate Filter: Percentage Slower (Open vs Pro)&quot;, fontsize=16)<br>plt.xlabel(&quot;Percentage Slower (%)&quot;)<br>plt.axvline(x=0, color=&quot;black&quot;, linestyle=&quot;--&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqRnERcXcMk80ce-AU0B-Q.png" /></figure><p>The data reveals a fascinating, almost counter-intuitive story about the reality of the Pro division:</p><ul><li><strong>The Weight Trap (Sled Push and Pull):</strong> Look at the left side of the chart. Surprisingly, Open athletes are actually <em>faster</em> than the Pros here! How is that possible? Because the Pro division fight with heavier weights. The data proves that this massive weight jump is a brutal time-sink for the Pros.</li><li><strong>The True Engine Filters (Burpee Broad Jumps, SkiErg, and Row):</strong> Now look at the right side of the chart. This is where Open athletes bleed the most time. No wonder Burpee Broad Jumps come up as the number one station where Open athletes are slower (I, myself, question my life choices every time I hit this station).</li></ul><p>So? If you are an Open athlete stepping up to the Pro division like me, you must accept that the heavier sleds will inevitably slow you down. However, the true separator between divisions isn’t just raw strength — it’s the cardiovascular engine.</p><h4>The Roxzone Trap and Running Fade</h4><p>The “Roxzone” is the transition area between running and workouts. We plotted total Roxzone Time against Total Finish Time to see if it makes a difference.</p><pre>sns.scatterplot(data=df_clean, x=&quot;Roxzone&quot;, y=&quot;Total Time&quot;, hue=&quot;category&quot;, alpha=0.8, palette=&quot;magma&quot;)<br>plt.title(&quot;The Roxzone Effect: Transition Time vs Total Finish Time&quot;, fontsize=16)<br>plt.xlabel(&quot;Total Roxzone Time (Seconds)&quot;)<br>plt.ylabel(&quot;Total Finish Time (Seconds)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qi7T3JD9NfSsJHbprFytKg.png" /></figure><p>Well, well, well… races are truly won and lost in the transitions. We can see that athletes who finish with elite overall times spend significantly less time in the Roxzone. While amateurs treat it as a resting zone to catch their breath, top performers treat it as part of the active race. We even found a few athletes who spent an incredible amount of time just surviving in the Roxzone!</p><pre>top5_rox = df_clean.nlargest(5, &quot;Roxzone&quot;)<br>total_time_check = top5_rox[[&quot;category&quot;, &quot;Roxzone&quot;, &quot;Total Time&quot;]]<br>print(&quot;Top 5 Athletes Who Spent Most Time in the Roxzone&quot;)<br>print(total_time_check)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*4By4tbGuo9-uY3Cj5dfs1Q.png" /></figure><p>But where do athletes bleed this time? We extracted the split times for each specific transition (Rox 1 to Rox 7) by carefully subtracting the workout time from the total block time.</p><pre># Get roxzone time in during each station<br><br># Stations<br>workout_names = [<br>    &quot;SkiErg&quot;, <br>    &quot;Sled Push&quot;, <br>    &quot;Sled Pull&quot;, <br>    &quot;Burpee Broad Jump&quot;, <br>    &quot;Row&quot;, <br>    &quot;Farmers Carry&quot;, <br>    &quot;Sandbag Lunges&quot;, <br>    &quot;Wall Balls&quot;<br>]<br><br># Loop through roxzone between stations<br>for i in range(1, 8):<br>    try:<br>        rox_in_col = f&quot;rox{i}_in_Roxzone In_time_acc&quot;<br>        rox_out_col = f&quot;rox{i}_out_Roxzone Out_time_acc&quot;<br>        <br>        station = workout_names[i-1]<br>        wor_in_col = f&quot;wor{i}_in_{station} In_time_acc&quot;<br>        wor_out_col = f&quot;wor{i}_out_{station} Out_time_acc&quot;<br>        <br>        total_block_time = df_clean[rox_out_col] - df_clean[rox_in_col]<br>        station_time = df_clean[wor_out_col] - df_clean[wor_in_col]<br>        <br>        df_clean[f&quot;Rox_Split_{i}_sec&quot;] = total_block_time - station_time<br>        <br>    except KeyError as e:<br>        print(f&quot;Skipping split {i} because column {e} was not found.&quot;)<br><br>df_clean[[f&quot;Rox_Split_{i}_sec&quot; for i in range(1, 8)]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRO5YBMoCcEOy9Vi5Ww7kA.png" /></figure><pre>rox_cols = [f&quot;Rox_Split_{i}_sec&quot; for i in range(1, 8) if f&quot;Rox_Split_{i}_sec&quot; in df_clean.columns]<br><br>if rox_cols:<br>    rox_melted = df_clean.melt(id_vars=[&quot;is_pro&quot;], value_vars=rox_cols, var_name=&quot;Transition&quot;, value_name=&quot;Seconds&quot;)<br>    rox_melted[&quot;Transition&quot;] = rox_melted[&quot;Transition&quot;].str.replace(&quot;_sec&quot;, &quot;&quot;).str.replace(&quot;Rox_Split_&quot;, &quot;Rox &quot;)<br>    <br>    plt.figure(figsize=(12, 6))<br>    sns.boxplot(data=rox_melted, x=&quot;Transition&quot;, y=&quot;Seconds&quot;, hue=&quot;is_pro&quot;, palette=&quot;viridis&quot;, showfliers=False)<br>    plt.title(&quot;The Roxzone Bleed: Time Spent in Each Transition&quot;, fontsize=16)<br>    plt.show()</pre><p>But where exactly do athletes bleed this time? We extracted the split times for each specific transition (Rox 1 to Rox 7) by carefully subtracting the workout time from the total block time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gy7aH3gd959VTzZpV92Pkw.png" /></figure><p>For the Open Division, transition times spike dramatically after the heavy leg workouts (Sled Push and Sandbag Lunges). Athletes are literally stopping to survive (me too!). Meanwhile, the Pro Division maintains an almost flat transition time throughout the entire race.</p><p>This fatigue also bleeds into their running. Let’s look at the pacing strategy across all 8 runs:</p><pre><br>run_cols = [f&quot;Run {i}&quot; for i in range(1, 9)]<br>if all(col in df_clean.columns for col in run_cols):<br>    run_melted = df_clean.melt(id_vars=[&quot;is_pro&quot;], value_vars=run_cols, var_name=&quot;Run_Split&quot;, value_name=&quot;Seconds&quot;)<br>    run_melted[&quot;Run_Split&quot;] = run_melted[&quot;Run_Split&quot;].str.replace(&quot;_sec&quot;, &quot;&quot;)<br>    <br>    plt.figure(figsize=(10, 6))<br>    sns.lineplot(data=run_melted, x=&quot;Run_Split&quot;, y=&quot;Seconds&quot;, hue=&quot;is_pro&quot;, marker=&quot;o&quot;, palette=&quot;viridis&quot;, errorbar=None)<br>    plt.title(&quot;Running Pacing Strategy: Pro vs Open&quot;, fontsize=16)<br>    plt.ylabel(&quot;Average Running Time (Seconds)&quot;)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHFt0Z2OZxk_N-AJ-lhapA.png" /></figure><p>Why are you guys so freaking fast! We can see that the Pros start fast (Run 1), and settle into a highly consistent, relentless pace for Runs 2–7. The Open division, however, tells a story of survival. We (meaning my partner and me) may have thought we were sprinting through the stations, but the data tells a completely different story!</p><p>Nevertheless, it is interesting to see that both Pros and Open athletes do not go all-out at the very beginning, deliberately slowing their pace just before the dreaded Wall Balls.</p><h3>Conclusion: Ready for the AI</h3><p>Exploratory Data Analysis has given us the blueprint of a HYROX race. We now know that pacing consistency, transition discipline, and surviving the heavy sleds and Wall Balls are mathematically the keys to an elite time.</p><p>As for my partner and me? We now know exactly what we are signing up for if we click that “Pro” registration button.</p><p>But we don’t just understand the patterns — we are now ready to teach an AI to recognize them. In <strong>Part 3</strong>, we will take this exact dataset into the lab and build a <strong>Bidirectional LSTM Neural Network</strong>. We will feed the model an athlete’s split times up to the halfway point and ask it to predict their exact final finish time.</p><p>Will the AI understand the fatigue factor better than we do? I don’t know. But it might help me prepare to finish faster in my next race! (Fingers crossed).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b4b6c35b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HYROX Data Science Series Part 1: Scrapping Bangkok 2026 Race Data from the Track with Python]]></title>
            <link>https://ll-monkey.medium.com/from-the-race-track-to-the-data-pipeline-scraping-hyrox-bangkok-2026-results-part-1-38ee8a79e458?source=rss-5a15a144aae0------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ee8a79e458</guid>
            <category><![CDATA[hyrox]]></category>
            <category><![CDATA[sport-analytics]]></category>
            <category><![CDATA[python-webscraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[LL-Monkey]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 11:01:00 GMT</pubDate>
            <atom:updated>2026-03-31T08:47:18.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tFmKQswBbECI1cnNoWEAQ.jpeg" /></figure><p>The HYROX Bangkok 2025/2026 season wrapped up just a week ago. Even though this global fitness racing concept has been around for years, this was only its second event here in Thailand. The energy was absolutely insane — reports show that over 18,000 athletes showed up, doubling last year’s turnout!</p><p>My partner and I competed in Double Women Open last year, and our main goal this time was simple: beat our previous (and honestly, pretty horrible) times. We actually pulled it off! But while scrolling through the leaderboards, I noticed something else — everyone is getting faster. The overall race times are continuously dropping, and the Men’s Pro world record was just smashed in London this March 2026 at an unbelievable 52:42. Looking at these stats, I quickly realized I might have to wait until I’m 70 to actually stand on a podium for my age group (LOL!).</p><p>But as someone currently diving into the world of Data Science, simply participating wasn’t enough. I want to look into the actual HYROX data to uncover the trends myself.</p><p>That curiosity became the starting point for this project: building a Python web scraper to extract the HYROX leaderboard data from hyresult.com.</p><p>In this article, I will walk you through the process using simple, everyday language. We will start by testing the logic with individual code blocks step-by-step. Once we understand exactly how the web scraping mechanics work, we will then assemble those pieces into a clean, professional Object-Oriented Programming (OOP) Class.</p><p>Let’s get started!</p><h3>Step 1: The Proof of Concept (Can we actually scrape this?)</h3><p>Before we build a massive, automated data-extracting machine, we need to test the waters. Will the HYROX website even let us in, or will it block us immediately?</p><p>If you navigate to the hyresult.com, you will be able to see the list of HYROX races around the world. I use the recent HYROX Bangkok 2026, and test the water with the MEN division leaderboard page.</p><pre>import requests<br><br># Set headers <br>headers = {<br>    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3&#39;<br>}<br><br># Send get request<br>url = &quot;https://www.hyresult.com/ranking/s8-2026-bangkok-hyrox-men?p=1&amp;_rsc=er28k&quot;<br>res = requests.get(url, headers=headers)<br><br>print(&quot;Status Code:&quot;, res.status_code)<br>print(&quot;Raw Content:&quot;, res.content[:200])<br>print(&quot;Readable Text:&quot;, res.text[:200])<br><br><br></pre><pre># Result<br><br>Status Code: 200<br>Raw Content: b&#39;&lt;!DOCTYPE html&gt;&lt;html lang=&quot;en&quot; class=&quot;dark&quot; style=&quot;color-scheme:dark&quot;&gt;&lt;head&gt;&lt;meta charSet=&quot;utf-8&quot;/&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;/&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;/_n&#39;<br>Readable Text: &lt;!DOCTYPE html&gt;&lt;html lang=&quot;en&quot; class=&quot;dark&quot; style=&quot;color-scheme:dark&quot;&gt;&lt;head&gt;&lt;meta charSet=&quot;utf-8&quot;/&gt;&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;/&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;/_n</pre><h4>What is happening here?</h4><ul><li><strong>headers:</strong> Web servers are smart and highly protective. If a raw Python script knocks on their door, they usually slam it shut and block you. To get around this, we use a User-Agent.</li><li><strong>requests.get:</strong> We define our target URL (the men&#39;s leaderboard page) and use the requests library to fetch it by passingheaders=headers.</li><li><strong>status_code:</strong> Printing res.status_code is our reality check. If the terminal prints 200, it is &quot;OK&quot;. If you see 403 (Forbidden) or 404 (Not Found), it means our disguise failed or the link is broken.</li><li><strong>content vs </strong><strong>text</strong> Finally, we print the first 200 characters of the response to see what we got. res.content gives us the raw, computer-level bytes, while res.text translates it into readable characters.</li></ul><h3>Step 2: Fetching the Athlete List from the Leaderboard</h3><p>Now that we know the website will let us in, it is time to grab the actual list of athletes. But there is a catch: modern websites are built using complex frameworks (like React or Next.js). If you just download the page, you get a massive, unreadable wall of code.</p><pre>import re<br><br># Set target division and page to test the code<br>division = &quot;s8-2026-bangkok-hyrox-men&quot;<br>page = 2<br>url = f&quot;https://www.hyresult.com/ranking/{division}?p={page}&amp;_rsc=er28k&quot;<br><br># Update headers<br>headers = {<br>    &#39;Accept&#39;: &#39;*/*&#39;,<br>    &#39;rsc&#39;: &#39;1&#39;,  # Ask for raw data, not the whole visual webpage<br>    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15&#39;,<br>    &#39;next-router-state-tree&#39;: f&#39;%5B%22%22%2C%7B%22children%22%3A%5B%22ranking%22%2C%7B%22children%22%3A%5B%5B%22slug%22%2C%22{division}%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D&#39;,<br>    &#39;next-url&#39;: f&#39;/ranking/{division}&#39;<br>}<br><br>try:<br>    # Fetch data<br>    res = requests.get(url, headers=headers, timeout=20)<br>    res.raise_for_status()<br>    res.encoding = &#39;utf-8&#39;<br>    <br>    # Save a copy of raw data for debugging<br>    with open(&#39;webscrap_debug.txt&#39;, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>        f.write(res.text)<br>        <br>    # Use regular expression to find what we want<br>    athlete_pattern = r&#39;&quot;athlete&quot;:\{&quot;name&quot;:&quot;([^&quot;]+)&quot;,&quot;slug&quot;:&quot;[^&quot;]+&quot;,&quot;nation&quot;:&quot;([^&quot;]+)&quot;,&quot;idp&quot;:&quot;([^&quot;]+)&quot;\}&#39;<br>    matches = re.findall(athlete_pattern, res.text)<br>    <br>    # Print the first 3 athletes we found<br>    print(matches[:3]) <br>    <br>except Exception as e:<br>    print(f&quot;Error occurs, cannot get athlete list, {e}&quot;)</pre><pre># Result<br><br>[(&#39;Martin Pauvert&#39;, &#39;FRA&#39;, &#39;LR3MS4JI482E33&#39;), (&#39;Sinthich Kidtatun&#39;, &#39;THA&#39;, &#39;LR3MS4JI483925&#39;), (&#39;Liam Harding&#39;, &#39;IRL&#39;, &#39;LR3MS4JI482E27&#39;]</pre><h4>What is happening here?</h4><ul><li><strong>Upgrading Headers:</strong> You might notice rsc: 1 and a block of next-router-state-tree. It forces the HYROX server to send us clean data instead of heavy visual elements like buttons and images.</li><li><strong>Raw Data (</strong><strong>with open...):</strong> This block of code saves the website&#39;s response into a neat text file (webscrap_debug.txt) on our computer. That way, we can open it in a text editor and explore the data.</li><li><strong>Regular Expression: </strong>If you inspect the source code, you will notice that athletes’ information on the leaderboard also includes ‘idp’ or athlete ID. We collect it for fetching the athlete’s details.</li></ul><h3>Step 3: Fetching Athlete’s Profile</h3><p>Alright, we now have a list of athletes and their unique IDs. We can use ID to enter each athlete’s personal result page and grab the details: their race date, division, and how fast they completed every single workout station (like the Ski Erg or Sled Push).</p><pre># Use athlete&#39;s ID from our previous list<br># For testing, we will just use only the first item<br>name, nation, athlete_id = matches[0]<br>print(f&quot;Testing profile for ID: {athlete_id}&quot;)<br><br># Set up the target URL and Headers for the profile page<br>url = f&quot;https://www.hyresult.com/result/{athlete_id}?_rsc=er28k&quot;<br>headers = {<br>    &#39;Accept&#39;: &#39;*/*&#39;,<br>    &#39;rsc&#39;: &#39;1&#39;,<br>    &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15&#39;,<br>    &#39;next-router-state-tree&#39;: f&#39;%5B%22%22%2C%7B%22children%22%3A%5B%22result%22%2C%7B%22children%22%3A%5B%5B%22idp%22%2C%22{athlete_id}%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D&#39;,<br>    &#39;next-url&#39;: f&#39;/result/{athlete_id}&#39;<br>}<br><br># Fetch the profile<br>res = requests.get(url, headers=headers, timeout=10)<br>res.raise_for_status()<br>res.encoding = &#39;utf-8&#39;<br><br># Get Metadata (Race Date and Division)<br>meta_pattern = r&#39;&quot;name&quot;:&quot;description&quot;,&quot;content&quot;:&quot;HYROX race analysis for .*? at .*?, ([A-Za-z]+ \d+–\d+) in division (.*?)&quot;\}&#39;<br>meta_match = re.search(meta_pattern, res.text)<br>race_date = meta_match.group(1) if meta_match else &quot;N/A&quot;<br>full_div = meta_match.group(2) if meta_match else &quot;N/A&quot;<br>print(&quot;Race Date:&quot;, race_date)<br>print(&quot;Division:&quot;, full_div)<br><br># Get Station Times<br>station_pattern = r&#39;&quot;name&quot;:&quot;([^&quot;]+)&quot;,&quot;time&quot;:(\d+)&#39;<br>stations = re.findall(station_pattern, res.text)<br>print(&quot;Stations:&quot;, stations[:2]) # Print just the first 2 <br><br># Get Detailed Splits<br>detailed_pattern = r&#39;&quot;((?:rox|wor|total)\d*?_?.*?)&quot;.*?&quot;children&quot;:&quot;([^&quot;]+)&quot;\}.*?&quot;children&quot;:&quot;([^&quot;]+)&quot;\}.*?&quot;children&quot;:&quot;([^&quot;]+)&quot;\}&#39;<br>raw_splits = re.findall(detailed_pattern, res.text)<br>print(&quot;Detailed Splits:&quot;, raw_splits[:2]) # Print just the first 2</pre><pre># Result<br><br>Testing profile for ID: LR3MS4JI482E33<br>Race Date: Mar 20–22<br>Division: HYROX MEN 30-34<br>Stations: [(&#39;Total Time&#39;, &#39;4167&#39;), (&#39;Runs&#39;, &#39;1925&#39;)]<br>Detailed Splits: [(&#39;rox1_in&#39;, &#39;Roxzone In&#39;, &#39;10:15:29&#39;, &#39;05:24&#39;), (&#39;wor1_in&#39;, &#39;SkiErg In&#39;, &#39;10:15:31&#39;, &#39;05:26&#39;)]</pre><h4>What is happening here?</h4><p>Let’s break down how we are catching this data:</p><ul><li><strong>Metadata </strong><strong>re.search:</strong> Instead of finding a list of things, we just want to find one specific summary sentence that HYROX hides in the code (it usually starts with &quot;name&quot;:&quot;description&quot;). We use re.search because we only need to find it once.</li><li><strong>Station Times </strong><strong>re.findall:</strong> This pattern is delightfully simple. It scans the page looking for a &quot;name&quot; (like &quot;Burpee Broad Jumps&quot;) followed by a &quot;time&quot; in seconds (like 180). Because an athlete completes multiple stations, we use re.findall to grab all of them into a neat list.</li><li><strong>Regex for Splits: </strong>The(?:rox|wor|total)\d*? just looks for specific ID codes HYROX uses. rox stands for Roxzone, wor stands for Workout, and total is the running total. The rest of the pattern simply grabs the next three pieces of data connected to it: the label (e.g., &quot;In&quot; or &quot;Out&quot;), the time of day, and the accumulated time.</li></ul><h3>Step 4: Cleaning Up and Building the Table (The DataFrame)</h3><p>At this point, we have successfully extracted all the information. But the total seconds (like 245 seconds for a run) are not very human-friendly. We want it to look like a proper race time: 00:04:05.</p><p>On top of that, we need to organize all these scattered pieces of data — names, divisions, and station times — into a neat, Excel-like table.</p><pre>import pandas as pd<br><br># Create empty dictionary for athlete&#39;s data<br>athlete_data = {}<br><br># Convert time (Seconds to HH:MM:SS)<br>for station_name, seconds_str in stations: <br>    # divmod is a cool math trick that divides and gives you the remainder!<br>    m, s = divmod(int(seconds_str), 60) # Get total minutes and leftover seconds<br>    h, m = divmod(m, 60)                # Get total hours and leftover minutes<br>    formatted_time = f&quot;{h:02d}:{m:02d}:{s:02d}&quot; <br>    # save to empty dictionary<br>    athlete_data[station_name] = formatted_time<br><br># Organize Detailed Splits<br>for row_key, label, tod, time_acc in raw_splits:<br>    # Create unique column names like &quot;rox1_In_tod&quot; and save the data<br>    athlete_data[f&quot;{row_key}_{label}_tod&quot;] = tod<br>    athlete_data[f&quot;{row_key}_{label}_time_acc&quot;] = time_acc<br><br># Construct the DataFrame<br>df = pd.DataFrame(matches[:1], columns=[&#39;name&#39;, &#39;nation&#39;, &#39;athlete_id&#39;])<br><br># Add the race date and division as new columns<br>df[[&#39;race_date&#39;, &#39;division&#39;]] = race_date, full_div<br><br># Unpack all the race times from our profile card into the table<br>for k, v in athlete_data.items():<br>    df[k] = v<br><br># Look the result<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ww7Rn6r4TX7d2X0aTakOOA.png" /></figure><h3>Step 5: The Scraper Class</h3><p>You did it! We successfully tested every single step: connecting to the website, finding the athletes, extracting their times, and formatting the data.</p><p>But right now, our code is scattered in different blocks. If we want to run this for all 18,000 athletes across 14 different divisions, running separate blocks of code will be a nightmare.</p><p>We are going to take all our working pieces and wrap them into an <strong>Object-Oriented Programming (OOP) Class</strong>.</p><pre>import requests<br>import re<br>import pandas as pd<br>import time<br>import os<br>from tqdm import tqdm<br><br>class HyroxScraper:<br>    def __init__(self, output_file=&quot;hyrox_bkk_2026.csv&quot;):<br>        self.output_file = output_file<br>        self.session = requests.Session()  # Keep the connection open<br>        self.session.headers.update({<br>            &#39;rsc&#39;: &#39;1&#39;,<br>            &#39;User-Agent&#39;: &#39;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15&#39;<br>        })<br><br>    def fetch_athlete_list(self, division, page):<br>        url = f&quot;https://www.hyresult.com/ranking/{division}?p={page}&amp;_rsc=er28k&quot;<br>        self.session.headers.update({<br>            &#39;next-router-state-tree&#39;: f&#39;%5B%22%22%2C%7B%22children%22%3A%5B%22ranking%22%2C%7B%22children%22%3A%5B%5B%22slug%22%2C%22{division}%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D&#39;,<br>            &#39;next-url&#39;: f&#39;/ranking/{division}&#39;<br>        })<br>        try:<br>            res = self.session.get(url, timeout=20)<br>            res.raise_for_status()<br>            res.encoding = &#39;utf-8&#39;<br>            athlete_pattern = r&#39;&quot;athlete&quot;:\{&quot;name&quot;:&quot;([^&quot;]+)&quot;,&quot;slug&quot;:&quot;[^&quot;]+&quot;,&quot;nation&quot;:&quot;([^&quot;]+)&quot;,&quot;idp&quot;:&quot;([^&quot;]+)&quot;\}&#39;<br>            matches = re.findall(athlete_pattern, res.text)<br>            return matches<br>        except Exception as e:<br>            print(f&quot;Error occurs, cannot get athlete list, {e}&quot;)<br>            return []<br><br>    def fetch_athlete_profile(self, athlete_id):<br>        url = f&quot;https://www.hyresult.com/result/{athlete_id}?_rsc=er28k&quot;<br>        self.session.headers.update({<br>            &#39;next-router-state-tree&#39;: f&#39;%5B%22%22%2C%7B%22children%22%3A%5B%22result%22%2C%7B%22children%22%3A%5B%5B%22idp%22%2C%22{athlete_id}%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D&#39;,<br>            &#39;next-url&#39;: f&#39;/result/{athlete_id}&#39;<br>        })<br>        try:<br>            res = self.session.get(url, timeout=20)<br>            res.raise_for_status()<br>            res.encoding = &#39;utf-8&#39;<br>            <br>            meta_pattern = r&#39;&quot;name&quot;:&quot;description&quot;,&quot;content&quot;:&quot;HYROX race analysis for .*? at .*?, ([A-Za-z]+ \d+–\d+) in division (.*?)&quot;\}&#39;<br>            meta_match = re.search(meta_pattern, res.text)<br>            race_date = meta_match.group(1) if meta_match else &quot;N/A&quot;<br>            full_div = meta_match.group(2) if meta_match else &quot;N/A&quot;<br>            <br>            station_pattern = r&#39;&quot;name&quot;:&quot;([^&quot;]+)&quot;,&quot;time&quot;:(\d+)&#39;<br>            stations = re.findall(station_pattern, res.text)<br>         <br>            detailed_pattern = r&#39;&quot;((?:rox|wor|total)\d*?_?.*?)&quot;.*?&quot;children&quot;:&quot;([^&quot;]+)&quot;\}.*?&quot;children&quot;:&quot;([^&quot;]+)&quot;\}.*?&quot;children&quot;:&quot;([^&quot;]+)&quot;\}&#39;<br>            raw_splits = re.findall(detailed_pattern, res.text)<br><br>            return race_date, full_div, stations, raw_splits<br>        except Exception as e:<br>            print(f&quot;Error getting athlete&#39;s profile, {e}&quot;)<br>            return &quot;N/A&quot;, &quot;N/A&quot;, [], []<br>            <br>    def save_athlete(self, athlete_dict):<br>        df = pd.DataFrame([athlete_dict])<br>        write_mode = &#39;a&#39; if os.path.exists(self.output_file) else &#39;w&#39;<br>        write_header = not os.path.exists(self.output_file)<br>        df.to_csv(self.output_file, mode=write_mode, header=write_header, index=False)<br><br>    def run(self, divisions):<br>        print(f&quot;Start fetching data and save to {self.output_file}...&quot;)<br><br>        # tqdm gives a beautiful loading bar<br>        pbar = tqdm(divisions)<br>        <br>        for div in pbar:<br>            pbar.set_description(f&quot;Fetching {div}&quot;)<br>            page = 1<br>            while True:<br>                athletes = self.fetch_athlete_list(div, page)<br>                <br>                if not athletes:<br>                    break # Stop when we reach the last page<br>                    <br>                for name, nation, idp in athletes:<br>                    race_date, full_div, stations, raw_splits = self.fetch_athlete_profile(idp)<br><br>                    # Flatten results into a dictionary<br>                    if race_date:<br>                        athlete_data = {<br>                            &#39;name&#39;: name,<br>                            &#39;nation&#39;: nation,<br>                            &#39;athlete_id&#39;: idp,<br>                            &#39;race_date&#39;: race_date,<br>                            &#39;division&#39;: full_div<br>                        }<br>                    <br>                        for station_name, seconds_str in stations: <br>                            m, s = divmod(int(seconds_str), 60)<br>                            h, m = divmod(m, 60)<br>                            formatted_time = f&quot;{h:02d}:{m:02d}:{s:02d}&quot; <br>                            athlete_data[station_name] = formatted_time<br>                        <br>                        for row_key, label, tod, time_acc in raw_splits:<br>                            athlete_data[f&quot;{row_key}_{label}_tod&quot;] = tod<br>                            athlete_data[f&quot;{row_key}_{label}_time_acc&quot;] = time_acc<br>                        <br>                        self.save_athlete(athlete_data)<br><br>                    time.sleep(1.5)<br>                page += 1<br><br><br>if __name__ == &quot;__main__&quot;:<br>    divisions = [<br>        &quot;s8-2026-bangkok-hyrox-men&quot;,<br>        # Add all other divisions here<br>    ]<br><br>    scraper = HyroxScraper(output_file=&#39;hyrox_bkk_2026.csv&#39;)<br>    scraper.run(divisions)</pre><h3>Conclusion</h3><p>There you have it! We went from staring at a confusing web page to building a functional, automated Python web scraper. Now, I have a massive CSV file filled with the race data of all athletes from HYROX Bangkok 2026.</p><p>The next step? Importing this beautiful dataset into Pandas to do some serious Data Analysis. Who knows, maybe the data will show me a secret strategy to finally get on that podium before I turn 70!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ee8a79e458" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>