<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en_US"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://william-golovlev.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://william-golovlev.github.io/" rel="alternate" type="text/html" hreflang="en_US" /><updated>2026-12-04T16:01:46-08:00</updated><id>https://william-golovlev.github.io/feed.xml</id><title type="html">William Golovlev</title><subtitle>William Golovlev is an AI engineer building RAG systems, explainable AI and ML tools. Articles, projects and resume.</subtitle><author><name>William Golovlev</name></author><entry><title type="html">From Software Developer to AI Development Specialist: How I learned to advocate for my goals</title><link href="https://william-golovlev.github.io/blog/software-developer-to-ai-specialist/" rel="alternate" type="text/html" title="From Software Developer to AI Development Specialist: How I learned to advocate for my goals" /><published>2026-09-03T12:00:00-07:00</published><updated>2026-09-03T12:00:00-07:00</updated><id>https://william-golovlev.github.io/blog/software-developer-to-ai-specialist</id><content type="html" xml:base="https://william-golovlev.github.io/blog/software-developer-to-ai-specialist/"><![CDATA[<h2 id="the-shift-moving-into-ai-engineering">The Shift: Moving into AI Engineering</h2>

<p>Long time no post! As the title gives away, I’ve been focused on my career, specifically on negotiating a move into AI engineering. My blog probably tells you I’m into AI, but I always wanted it to be my job, not a side hobby.</p>

<p>To be transparent, leadership at my company was rightfully hesitant about AI. Some folks were worried about security. So for almost a year I wrote up research to share with my boss and the company, and I did demos of what’s possible. The demos are what sold the stakeholders. After a lot of patience, they were thrilled with what they saw, and now we’re chasing AI initiatives and I’ve moved into the role of “AI Development Specialist.” (I was told it was hard to create a new position title and this is what they landed on, but the role description is basically AI Engineer.)</p>

<ul>
  <li><strong>Previous role:</strong> Software Developer</li>
  <li><strong>New role:</strong> AI Development Specialist (AI Engineer)</li>
  <li><strong>Key shift:</strong> From building traditional CRUD apps and services to designing LLM workflows, RAG pipelines and fine-tuning models, plus AI governance.</li>
</ul>

<hr />

<h2 id="why-the-transition-made-sense">Why the Transition Made Sense</h2>

<p>I was already pushing hard for AI at the company. We have a lot of useful data, so why not put AI to work? But my demos weren’t just snazzy, and they didn’t just solve a problem. They addressed the company’s real concern: data privacy and safety. If our data leaked, it could put the company under VERY quickly.</p>

<ul>
  <li>I always wanted to be an AI engineer. I just needed to figure out how to put that into action at my current company.</li>
  <li>The demo used a pretty niche tool, ML.NET, which let us keep the entire process in our own data center. One demo solved a logistics problem and the safety concern at the same time.</li>
  <li>My degree and previous roles weren’t AI-focused. What helped was doing AI as a hobby: taking courses in my free time and building RAG systems and agentic projects. That gave me the confidence to advocate for myself and show management what AI can do.</li>
</ul>

<hr />

<h2 id="what-changes-day-to-day">What Changes Day-to-Day</h2>

<p>It’s early, since I just got the role last month, but between conversations and the new job description I have a decent idea. Before, I reported only to my manager and all my work came from him. I never “owned” a major initiative. Now I’m expected to step up: owning the project (which is a lot more than owning the code), meeting with stakeholders instead of just my manager, and coordinating and managing contractors.</p>

<h3 id="traditional-software-development-vs-ai-engineering">Traditional Software Development vs. AI Engineering</h3>

<table>
  <thead>
    <tr>
      <th style="text-align: left">Aspect</th>
      <th style="text-align: left">Software Developer</th>
      <th style="text-align: left">AI Development Specialist</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: left"><strong>Primary Focus</strong></td>
      <td style="text-align: left">Deterministic logic, API architecture, UI/UX</td>
      <td style="text-align: left">Probabilistic systems, LLM orchestration, AI governance</td>
    </tr>
    <tr>
      <td style="text-align: left"><strong>Tooling</strong></td>
      <td style="text-align: left">Standard frameworks, databases, CI/CD</td>
      <td style="text-align: left">model evaluation, vector DBs, AI agents</td>
    </tr>
    <tr>
      <td style="text-align: left"><strong>Mindset</strong></td>
      <td style="text-align: left">Writing strict control flow</td>
      <td style="text-align: left">Model/System design, guardrails, fallback handling</td>
    </tr>
  </tbody>
</table>

<p>Basically, it’s a much wider umbrella. As an entry-level SWE at my job, the focus was writing good code. Now I’m expected to handle AI system design and governance too.</p>

<hr />

<h2 id="challenges-and-lessons-so-far">Challenges and Lessons (So Far)</h2>

<ol>
  <li><strong>Convincing skeptics.</strong> You probably picture stakeholders who want to throw AI at everything as a buzzword. I had the opposite problem. Before I ever advocated for myself, a former coworker tried to push for AI and was always shut down: security concerns, an old-fashioned mindset, and so on. So I went in with some trepidation. What got me through was answering the concerns I’d heard before anyone could raise them again. Once they knew their concerns were covered, it worked.</li>
  <li><strong>Applying AI where it’s actually useful.</strong> Be careful about throwing AI at anything and everything. Companies have learned this the hard way, like replacing customer support teams with chatbots. An LLM can’t handle everything. You need a specific, narrow goal the AI system can reliably hit, not a jack of all trades. My manager and I thought hard about this and demoed an idea that solves a real problem, one that would definitely be more effective than a human dispatcher. It also tackles a real gap: experienced dispatchers are retiring, and newer dispatchers don’t have as much industry knowledge yet.</li>
  <li><strong>Finding the right tech stack.</strong> We needed tools that fit our exact needs. What I found, ML.NET, is EXTREMELY lightweight, simple and classical. It existed before the AI hype even started. We didn’t need a fancy third-party AI API or an LLM for this. ML.NET is lightweight, free and local. I guess that’s what good governance looks like.</li>
</ol>

<hr />

<h2 id="looking-ahead">Looking Ahead</h2>

<p>I’m excited to finally be working on my long-term goal of doing AI full time.</p>

<ul>
  <li>I’ve always loved agentic AI and automation, so I’m looking forward to any automation project that comes my way.</li>
  <li>If you’re a developer, advocate for yourself (whatever your goal is) with your higher-ups instead of just job hopping. If you can make the case and convince people, everyone gets value out of it, including you. And showing growth within a company is far more valuable for your career than job hopping.</li>
</ul>]]></content><author><name>William Golovlev</name></author><category term="Career &amp; Tech" /><category term="Career Transition" /><category term="AI Engineering" /><category term="Software Engineering" /><category term="AI Development" /><category term="Career" /><summary type="html"><![CDATA[How I went from software developer to AI Development Specialist at my company, and what I learned about advocating for myself.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/22.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/22.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Beyond the JSON Bridge: The Rise of Code-Centric Agents</title><link href="https://william-golovlev.github.io/blog/code-centric-agents/" rel="alternate" type="text/html" title="Beyond the JSON Bridge: The Rise of Code-Centric Agents" /><published>2026-04-08T13:00:00-07:00</published><updated>2026-04-08T13:00:00-07:00</updated><id>https://william-golovlev.github.io/blog/code-centric-agents</id><content type="html" xml:base="https://william-golovlev.github.io/blog/code-centric-agents/"><![CDATA[<h2 id="two-ways-an-agent-can-act">Two Ways an Agent Can Act</h2>

<p>There are two main ways to let an AI agent do things: have it fill out a structured tool call, or have it write code. Most agents so far use the first. The second is catching on fast, and knowing when to use which will save you a lot of pain.</p>

<h3 id="react-json-the-classic-approach">ReAct (JSON): The Classic Approach</h3>

<p>“Reason + Act” (ReAct) has been the workhorse of agentic AI. The model outputs a structured JSON block, the system runs it, and the result gets fed back:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="nl">"tool"</span><span class="p">:</span><span class="w"> </span><span class="s2">"weather"</span><span class="p">,</span><span class="w"> </span><span class="nl">"args"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="nl">"city"</span><span class="p">:</span><span class="w"> </span><span class="s2">"NYC"</span><span class="p">}}</span><span class="w">
</span></code></pre></div></div>

<p>It’s predictable, safe and easy to debug. The model basically asks permission to use a tool, waits for the result, then decides what to do next.</p>

<h3 id="code-agents-the-newer-approach">Code Agents: The Newer Approach</h3>

<p>Instead of filling in a fixed schema, the model writes a snippet of code that gets the job done. Rather than asking to use a weather tool, it might write:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">requests</span>
<span class="n">weather_data</span> <span class="o">=</span> <span class="n">requests</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="sa">f</span><span class="s">"https://api.weather.com/v1/weather?city=NYC"</span><span class="p">).</span><span class="n">json</span><span class="p">()</span>
<span class="n">temperature</span> <span class="o">=</span> <span class="n">weather_data</span><span class="p">[</span><span class="s">'current'</span><span class="p">][</span><span class="s">'temp'</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"The temperature in NYC is </span><span class="si">{</span><span class="n">temperature</span><span class="si">}</span><span class="s">°F"</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="the-core-shift-from-asking-to-doing">The Core Shift: From Asking to Doing</h3>

<p><strong>We’re moving from models that ask to use a tool to models that write the logic to use those tools.</strong> It’s the difference between asking someone to pass you a screwdriver and just building the damn thing yourself.</p>

<hr />

<h2 id="how-the-frontier-models-do-it">How the Frontier Models Do It</h2>

<h3 id="claude-anthropic-hybrid">Claude (Anthropic): Hybrid</h3>

<p>For broad interactions like web search, Claude sticks with <strong>Tool Calling</strong> (structured JSON). On top of that, harnesses like Claude Code and the Claude Agent SDK can spin up <strong>sub-agents</strong> for multi-step work. That’s a feature of the harness, not something hidden inside the model, but it works like a manager handing specific tasks to specialists.</p>

<h3 id="gemini-google-the-thinking-agent">Gemini (Google): The Thinking Agent</h3>

<p>Gemini leans on <strong>“Thinking” as Chain-of-Thought (CoT)</strong>: a hidden reasoning layer where it runs a Think -&gt; Act -&gt; Observe loop before giving you the final answer. Google emphasizes “native” tool use, where reasoning and execution are tightly coupled inside the model.</p>

<p>The Thinking block is an internal monologue that keeps the messy trial-and-error out of view. You see the chef’s plated dish, not the burnt attempts and spilled ingredients.</p>

<hr />

<h2 id="rule-of-thumb-dont-overengineer">Rule of Thumb: Don’t Overengineer</h2>

<p>If you just need the current temperature, a JSON tool call is perfect. It’s fast, predictable and cheap.</p>

<p>Using a full code agent (VM spin-up, extra logic) for a basic API fetch is like using a chainsaw to cut a grape. You add complexity, security risk and latency for nothing.</p>

<h3 id="when-code-agents-win">When Code Agents Win</h3>

<p><strong>Ambiguity.</strong> When the workflow isn’t a straight line. “Clean this messy CSV and find the outliers” needs judgment, conditionals and iteration that are painful to express in JSON.</p>

<p><strong>Complex data types.</strong> JSON can’t carry non-serializable objects. Try passing a live database connection, a PyTorch model object or a big binary blob through it. You end up with 20 tool definitions for something code does in one line.</p>

<p><strong>Logic density.</strong> Code lets the agent run if/else, loops and data transformations locally, without a round trip to the LLM for every tiny step. That matters a lot for speed and cost.</p>

<hr />

<h2 id="frameworks-at-a-glance">Frameworks at a Glance</h2>

<table>
  <thead>
    <tr>
      <th>Framework</th>
      <th>Primary Logic</th>
      <th>Philosophy</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Hugging Face smolagents</td>
      <td>Code-First</td>
      <td>Minimalist; the agent writes Python. Extremely high efficiency for complex tasks.</td>
    </tr>
    <tr>
      <td>LangGraph</td>
      <td>State-First</td>
      <td>Focuses on “cycles” and controlled graphs. Great for complex, repeatable business logic.</td>
    </tr>
    <tr>
      <td>LlamaIndex ReAct</td>
      <td>JSON-First</td>
      <td>Optimized for RAG; uses tool-calling to fetch data and reason over documents.</td>
    </tr>
  </tbody>
</table>

<hr />

<h2 id="the-security-elephant-in-the-room">The Security Elephant in the Room</h2>

<h3 id="the-risk">The Risk</h3>

<p>A code agent is, by definition, an arbitrary code execution engine. Sooner or later it will try something you didn’t want, by mistake or through prompt injection. Plan for it.</p>

<h3 id="the-fix-sandbox-everything">The Fix: Sandbox Everything</h3>

<p>Never run agent code on your host machine. Ever.</p>

<p>Use micro-VMs (Firecracker) or hardened containers with strict import controls. Allow only the libraries the agent actually needs (e.g., pandas, requests) and block <code class="language-plaintext highlighter-rouge">os</code>, <code class="language-plaintext highlighter-rouge">sys</code> and <code class="language-plaintext highlighter-rouge">subprocess</code> entirely.</p>

<p>Think of a chemistry lab: you don’t let interns mix whatever they want in the main building. You give them a fume hood and a shelf of approved reagents.</p>

<hr />

<h2 id="choosing-your-architecture">Choosing Your Architecture</h2>

<p>Neither approach is “better.” It depends on the job.</p>

<p><strong>Use ReAct/JSON</strong> for rigid, predictable tool use and simple API calls, in high-security environments, or anywhere you need maximum control and observability.</p>

<p><strong>Use code agents</strong> for open-ended data science work, complex tasks with real ambiguity, cases where using the tools takes actual logic, and heavy data processing.</p>

<p>A practical default: start with JSON tool calls, and switch to a code agent only when you catch yourself writing a pile of tools to work around what a few lines of code would do.</p>]]></content><author><name>William Golovlev</name></author><category term="AI Engineering" /><category term="AI Agents" /><category term="Code Agents" /><category term="ReAct" /><category term="Tool Calling" /><category term="Claude" /><category term="Gemini" /><category term="AI Architecture" /><summary type="html"><![CDATA[How we're moving from models that ask to use tools to models that write the logic to use those tools.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/20.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/20.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Beyond Flat Search - Mastering Hierarchical RAG</title><link href="https://william-golovlev.github.io/blog/hierarchical-rag/" rel="alternate" type="text/html" title="Beyond Flat Search - Mastering Hierarchical RAG" /><published>2026-03-09T05:00:00-07:00</published><updated>2026-03-09T05:00:00-07:00</updated><id>https://william-golovlev.github.io/blog/hierarchical-rag</id><content type="html" xml:base="https://william-golovlev.github.io/blog/hierarchical-rag/"><![CDATA[<p>Most RAG (Retrieval-Augmented Generation) systems assume that slicing a document into equal-sized chunks and grabbing the top 5 is enough. For dense scientific papers, it isn’t. A paragraph on page 4 might depend on a table on page 12, and flat retrieval will happily hand the model one without the other.</p>

<p>For my <strong>Seed Oil Research Analyst</strong>, I dropped basic chunking for <strong>Hierarchical Node Parsing</strong> and <strong>Auto-Merging Retrieval</strong>.</p>

<h3 id="parents-children-and-auto-merging-">Parents, Children and Auto-Merging 🌳</h3>

<p>Flat RAG treats your data like a deck of cards spread on a table. Hierarchical RAG treats it like a family tree. With <strong>LlamaIndex</strong>, each document gets split at several sizes so you keep both the big picture and the details:</p>

<ol>
  <li><strong>Parent nodes:</strong> Large chunks (e.g., 2048 tokens) that hold the overall context, like a study’s full methodology or conclusion.</li>
  <li><strong>Child nodes:</strong> Each parent is split into smaller pieces (e.g., 512 and 128 tokens). These are what actually get indexed in <strong>Pinecone</strong>.</li>
  <li><strong>Auto-merge:</strong> If the retriever finds that, say, 3 out of 4 children of a parent are relevant, it doesn’t send those fragments to the LLM. It swaps them for the whole parent node.</li>
</ol>

<p><strong>Why it helps:</strong> You get the precision of small-chunk search with the context of a large chunk, and the answers stop feeling choppy.</p>

<p><strong>When to use it:</strong> Long, structured documents where meaning spans sections (papers, contracts, manuals). For short FAQs or notes, flat chunking is fine.</p>

<h3 id="parsing-scientific-pdfs-">Parsing Scientific PDFs 🧬</h3>

<p>Scientific PDFs are a nightmare for text extraction: multi-column layouts, complex tables, footnotes everywhere.</p>

<p>I used <strong>LlamaParse</strong>, which uses vision-based models to understand the page <em>layout</em>, not just the text. So when a study reports linoleic acid oxidation in a table, the table structure survives, and the hierarchical parser can connect those rows to the summary that discusses them.</p>

<blockquote>
  <p><strong>Thought Provoker:</strong> If a RAG system answers from one fragment of a study but misses the “limitations” section three pages later, is that an insight or a dangerous half-truth? This is why keeping context intact matters more than just finding the right words.</p>
</blockquote>

<h3 id="the-gatekeeper-stopping-off-topic-hallucinations-">The Gatekeeper: Stopping Off-Topic Hallucinations 🧭</h3>

<p>One of the biggest problems I hit: ask something out of scope, like “What’s the weather?”, and a vector database will <em>still</em> return its closest match, even if that match is only 20% relevant. The LLM then tries to force that weak match into an answer.</p>

<p>My fix was a <strong>similarity gatekeeper</strong>:</p>

<ul>
  <li><strong>Score threshold:</strong> A strict cutoff of 0.75+ similarity. If nothing in the peer-reviewed library clears it, the system stops and doesn’t answer.</li>
  <li><strong>Result:</strong> Instead of inventing a link between weather and seed oils, it stays in its lane. It acts like a careful technical analyst instead of an eager-to-please chatbot.</li>
</ul>

<h3 id="what-i-took-away-">What I Took Away 🌐</h3>

<p>The model matters (this one runs Llama 3 on Groq), but most of the quality in RAG comes from the <strong>plumbing</strong>.</p>

<ul>
  <li><strong>State management:</strong> With <strong>Chainlit</strong>, I had to keep the UI locked until the whole hierarchical tree was loaded into memory. Async here isn’t just about speed, it’s about not letting users ask questions of a half-loaded index.</li>
  <li><strong>Responsibility:</strong> When a tool summarizes medical or scientific research, “close enough” isn’t good enough.</li>
</ul>

<p>Auto-merging keeps the context, and the similarity cutoff keeps it honest. Together they make the system show its work instead of just generating.</p>

<p><strong>Challenge:</strong> If you were building a research assistant, would you want it to be “creative” and fill in gaps, or “rigid” and refuse to answer without 100% certainty?</p>]]></content><author><name>William Golovlev</name></author><category term="AI Engineering" /><category term="RAG" /><category term="LlamaIndex" /><category term="Hierarchical RAG" /><category term="Auto-Merging Retrieval" /><category term="AI Architecture" /><category term="Advanced RAG" /><summary type="html"><![CDATA[Solving the "Lost in the Middle" problem with Auto-Merging Retrieval and LlamaIndex.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/21.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/21.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Building Trust in AI: Engineering an Explainable Document Research Assistant</title><link href="https://william-golovlev.github.io/blog/xai-architecture/" rel="alternate" type="text/html" title="Building Trust in AI: Engineering an Explainable Document Research Assistant" /><published>2026-02-19T12:20:00-08:00</published><updated>2026-02-19T12:20:00-08:00</updated><id>https://william-golovlev.github.io/blog/xai-architecture</id><content type="html" xml:base="https://william-golovlev.github.io/blog/xai-architecture/"><![CDATA[<h2 id="the-problem-can-you-trust-the-answer">The Problem: Can You Trust the Answer?</h2>

<p>If an AI answers a question about your documents, how do you know it actually read them and didn’t make something up? That question is one of the biggest blockers to using AI at work, especially for things like legal research, medical analysis or any document-heavy job.</p>

<p>I built the XAI Document Research Assistant to answer it: every step of the retrieval-augmented generation (RAG) pipeline is visible and checkable.</p>

<h2 id="hybrid-retrieval">Hybrid Retrieval</h2>

<p>No single retrieval method works for every kind of question, so the system uses a <strong>hybrid search</strong> that combines two.</p>

<h3 id="semantic-search-finding-concepts">Semantic Search: Finding Concepts</h3>
<p><code class="language-plaintext highlighter-rouge">all-MiniLM-L6-v2</code> embeddings stored in ChromaDB handle meaning. Questions like “What are the key themes in this document?” or “Explain the methodology” get matched to relevant passages by vector similarity.</p>

<h3 id="keyword-search-finding-specifics">Keyword Search: Finding Specifics</h3>
<p>Semantic search is bad at exact matches: specific IDs, part numbers, rare acronyms. <strong>BM25</strong> (Best Matching 25) covers that. It treats the documents like a search engine index, so a query for “model X-17” or “section 4.2(b)” finds the exact passage.</p>

<h3 id="reranking-quality-control">Reranking: Quality Control</h3>
<p>Hybrid search can still return 20 or so candidate chunks. <strong>FlashRank</strong>, a cross-encoder reranker, scores each one against the specific question so only the best context reaches the language model.</p>

<h2 id="the-trust-layer-faithfulness-scoring">The Trust Layer: Faithfulness Scoring</h2>

<p>Instead of just trusting the output, every answer gets scored automatically with <strong>Ragas</strong>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># The system automatically scores each answer on faithfulness
# High faithfulness (0.95+) means the answer is derived solely from retrieved documents
# Low faithfulness indicates potential hallucination
</span><span class="n">evaluation</span> <span class="o">=</span> <span class="n">evaluator</span><span class="p">.</span><span class="n">evaluate_faithfulness</span><span class="p">(</span><span class="n">question</span><span class="p">,</span> <span class="n">answer</span><span class="p">,</span> <span class="n">retrieved_chunks</span><span class="p">)</span>
</code></pre></div></div>

<p>A score on its own isn’t enough, so I paired it with <strong>LangSmith tracing</strong>. Every interaction gets a trace URL showing which documents were retrieved, how they were reranked, and what the final answer was. No “trust me, it works.” The evidence is in the trace.</p>

<h2 id="engineering-challenges">Engineering Challenges</h2>

<h3 id="keeping-the-database-in-sync">Keeping the Database in Sync</h3>
<p>One of the hardest problems was keeping the Streamlit UI and the ChromaDB backend consistent. When a user removed a file from the uploader, its embeddings stayed in the database.</p>

<p><strong>Fix:</strong> On every script rerun, compare <code class="language-plaintext highlighter-rouge">processed_files</code> with the current <code class="language-plaintext highlighter-rouge">uploaded_files</code> and purge anything that was removed:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Detect deletions and sync database
</span><span class="n">current_uploaded_names</span> <span class="o">=</span> <span class="p">[</span><span class="n">f</span><span class="p">.</span><span class="n">name</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">uploaded_files</span><span class="p">]</span> <span class="k">if</span> <span class="n">uploaded_files</span> <span class="k">else</span> <span class="p">[]</span>
<span class="n">files_to_remove</span> <span class="o">=</span> <span class="p">[</span><span class="n">f</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">st</span><span class="p">.</span><span class="n">session_state</span><span class="p">.</span><span class="n">processed_files</span> <span class="k">if</span> <span class="n">f</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">current_uploaded_names</span><span class="p">]</span>

<span class="k">for</span> <span class="n">file_name</span> <span class="ow">in</span> <span class="n">files_to_remove</span><span class="p">:</span>
    <span class="n">st</span><span class="p">.</span><span class="n">session_state</span><span class="p">.</span><span class="n">rag_app</span><span class="p">.</span><span class="n">db</span><span class="p">.</span><span class="n">delete_file</span><span class="p">(</span><span class="n">file_name</span><span class="p">)</span>
    <span class="n">st</span><span class="p">.</span><span class="n">session_state</span><span class="p">.</span><span class="n">processed_files</span><span class="p">.</span><span class="n">remove</span><span class="p">(</span><span class="n">file_name</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="the-bm25-index-bug">The BM25 Index Bug</h3>
<p>The sneakiest bug was a “documents don’t match index corpus!” error. After a file was deleted, the chunks cache was updated but the BM25 index still pointed at the old corpus.</p>

<p><strong>Fix:</strong> Rebuild the chunks cache and the BM25 index together after every deletion:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Rebuild both cache and index from remaining documents
</span><span class="n">leftovers</span> <span class="o">=</span> <span class="bp">self</span><span class="p">.</span><span class="n">collection</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="n">include</span><span class="o">=</span><span class="p">[</span><span class="s">"documents"</span><span class="p">],</span> <span class="n">limit</span><span class="o">=</span><span class="bp">self</span><span class="p">.</span><span class="n">collection</span><span class="p">.</span><span class="n">count</span><span class="p">())</span>
<span class="bp">self</span><span class="p">.</span><span class="n">chunks_cache</span> <span class="o">=</span> <span class="n">leftovers</span><span class="p">[</span><span class="s">"documents"</span><span class="p">]</span>
<span class="n">tokenized_chunks</span> <span class="o">=</span> <span class="p">[</span><span class="n">simple_tokenizer</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">.</span><span class="n">chunks_cache</span><span class="p">]</span>
<span class="bp">self</span><span class="p">.</span><span class="n">bm25</span> <span class="o">=</span> <span class="n">BM25Okapi</span><span class="p">(</span><span class="n">tokenized_chunks</span><span class="p">)</span> <span class="k">if</span> <span class="bp">self</span><span class="p">.</span><span class="n">chunks_cache</span> <span class="k">else</span> <span class="bp">None</span>
</code></pre></div></div>

<h2 id="performance">Performance</h2>

<h3 id="batch-encoding-for-large-documents">Batch Encoding for Large Documents</h3>
<p>Embedding a big document all at once eats memory, so chunks are encoded in batches with a progress bar:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">batch_size</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">total_batches</span> <span class="o">=</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">chunks</span><span class="p">)</span> <span class="o">+</span> <span class="n">batch_size</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">//</span> <span class="n">batch_size</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunks</span><span class="p">),</span> <span class="n">batch_size</span><span class="p">):</span>
    <span class="n">batch_chunks</span> <span class="o">=</span> <span class="n">chunks</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="n">batch_size</span><span class="p">]</span>
    <span class="n">batch_embeddings</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">array</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">model</span><span class="p">.</span><span class="n">encode</span><span class="p">(</span><span class="n">batch_chunks</span><span class="p">,</span> <span class="n">normalize_embeddings</span><span class="o">=</span><span class="bp">True</span><span class="p">)).</span><span class="n">tolist</span><span class="p">()</span>
    <span class="c1"># Update progress bar for user feedback
</span>    <span class="n">update_progress</span><span class="p">(</span><span class="n">i</span> <span class="o">//</span> <span class="n">batch_size</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">total_batches</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="one-shared-instance">One Shared Instance</h3>
<p>Multiple RAG instances meant memory bloat and inconsistent state. With <code class="language-plaintext highlighter-rouge">@st.cache_resource</code>, the heavy models load once, globally, and are shared across every session and user. Anything per-user (like the list of processed files) lives in <code class="language-plaintext highlighter-rouge">st.session_state</code> instead:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">st</span><span class="p">.</span><span class="n">cache_resource</span>
<span class="k">def</span> <span class="nf">get_rag_app</span><span class="p">(</span><span class="n">persist_dir</span><span class="o">=</span><span class="s">'./db'</span><span class="p">):</span>
    <span class="s">"""Singleton pattern to ensure only one RAGApp instance."""</span>
    <span class="k">return</span> <span class="n">RAGApp</span><span class="p">(</span><span class="n">persist_dir</span><span class="p">)</span>
</code></pre></div></div>

<h2 id="the-audit-trail-langsmith">The Audit Trail: LangSmith</h2>

<p>Each trace records:</p>

<ul>
  <li>the HyDE-generated search query</li>
  <li>how many chunks were found and which search method found them</li>
  <li>FlashRank scores and the final selection</li>
  <li>token usage and latency</li>
  <li>the faithfulness score</li>
</ul>

<p>That’s a full audit trail you can review for compliance, accuracy or performance.</p>

<h2 id="lessons-learned">Lessons Learned</h2>

<p><strong>State management is where the bugs live.</strong> The hard bugs weren’t in the algorithms. They were in keeping UI state, database state and cache state in sync, especially with multiple users.</p>

<p><strong>Make errors specific.</strong> “Database error” helps nobody. Tell users what went wrong and what to try.</p>

<p><strong>Show what’s happening.</strong> Progress bars, status messages and debug logs aren’t extras. They’re a big part of why people trust a system.</p>

<p><strong>Test the messy workflows.</strong> Everything worked with one document. Adding, removing and switching between several documents is where the critical bugs showed up.</p>

<h2 id="from-black-box-to-glass-box">From Black Box to Glass Box</h2>

<p>With all of this in place, users can check every answer against the source, admins can audit every interaction, and developers can debug from a complete trace. If you’re building RAG for anything high-stakes, I’d treat faithfulness scoring and tracing as part of the core pipeline, not something to add later.</p>

<p><strong>Try the live demo:</strong> <a href="https://huggingface.co/spaces/william-ai-dev/xai-document-research">XAI Document Research Assistant</a></p>]]></content><author><name>William Golovlev</name></author><category term="AI Engineering" /><category term="RAG" /><category term="Explainable AI" /><category term="LangSmith" /><category term="ChromaDB" /><category term="BM25" /><category term="FlashRank" /><category term="AI Trust" /><summary type="html"><![CDATA[How I solved the AI 'Black Box' problem using hybrid search, reranking, and programmatic faithfulness scoring to create a transparent RAG pipeline.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/xai-architecture.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/xai-architecture.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">FitXAI Implementation - Building an Explainable AI (xAI) Workout Coach</title><link href="https://william-golovlev.github.io/blog/fitxai-implementation/" rel="alternate" type="text/html" title="FitXAI Implementation - Building an Explainable AI (xAI) Workout Coach" /><published>2026-02-03T12:20:00-08:00</published><updated>2026-02-03T12:20:00-08:00</updated><id>https://william-golovlev.github.io/blog/fitxai-implementation</id><content type="html" xml:base="https://william-golovlev.github.io/blog/fitxai-implementation/"><![CDATA[<p>In my Random Forests post, we covered how a forest of decision trees votes on a prediction. This post puts that to work: <strong>FitXAI</strong> is a workout coach that gives you a personalized plan and shows you <em>why</em> it picked each part of it.</p>

<h2 id="-the-idea">🎯 The Idea</h2>

<p>Most fitness apps are black boxes. You enter your info, get a plan, and have no idea why it chose those exercises or that split. FitXAI combines three things to fix that:</p>

<ul>
  <li><strong>Machine learning</strong> for the recommendations (a Random Forest ensemble)</li>
  <li><strong>SHAP values</strong> to show which inputs drove each recommendation</li>
  <li><strong>An LLM</strong> to turn that into plain-English coaching notes</li>
</ul>

<h2 id="️-system-architecture">🏗️ System Architecture</h2>

<h3 id="core-components">Core Components</h3>

<p>The key piece is the function that turns raw SHAP output into something readable:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Main prediction pipeline
</span><span class="k">def</span> <span class="nf">create_aggregated_explanation</span><span class="p">(</span><span class="n">shap_values</span><span class="p">,</span> <span class="n">feature_names</span><span class="p">,</span> <span class="n">input_transformed</span><span class="p">,</span> <span class="n">target_idx</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
    <span class="s">"""Create aggregated SHAP explanation with human-readable features"""</span>
    <span class="c1"># Process multi-output SHAP values
</span>    <span class="c1"># Aggregate one-hot encoded features
</span>    <span class="c1"># Generate human-readable explanations
</span></code></pre></div></div>

<h3 id="data-schema">Data Schema</h3>

<p>The model takes 8 inputs:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">FEATURE_COLS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s">'height_cm'</span><span class="p">,</span>      <span class="c1"># User height
</span>    <span class="s">'physique_idx'</span><span class="p">,</span>   <span class="c1"># Body type (-0.5 to 0.5)
</span>    <span class="s">'exp_idx'</span><span class="p">,</span>        <span class="c1"># Experience level (0.1 to 0.8)
</span>    <span class="s">'joint_health'</span><span class="p">,</span>   <span class="c1"># Joint health (1-10 scale)
</span>    <span class="s">'stress_idx'</span><span class="p">,</span>     <span class="c1"># Stress level (1-10 scale)
</span>    <span class="s">'avail_min'</span><span class="p">,</span>      <span class="c1"># Available workout time
</span>    <span class="s">'equip_lvl'</span><span class="p">,</span>      <span class="c1"># Equipment access (0-2)
</span>    <span class="s">'goal_id'</span>         <span class="c1"># Primary goal (0-2)
</span><span class="p">]</span>
</code></pre></div></div>

<p>A preprocessing pipeline scales the numeric columns, one-hot encodes the categorical ones, and does some feature engineering on top.</p>

<p>That’s a lot of data processing, which is normal for ML, but this project had an extra wrinkle. My data didn’t have one “target” like most online courses or college assignments. I needed a multi-output Random Forest that predicts 5 things at once, which meant breaking the inputs apart with the steps above and then aggregating the output back into something a person can read. I’ll probably go deeper on this another time, maybe with a video on my channel.</p>

<h2 id="-the-random-forest-ensemble">🤖 The Random Forest Ensemble</h2>

<h3 id="multi-output-architecture">Multi-Output Architecture</h3>

<p>Instead of a single-output classifier, FitXAI uses a <strong>multi-output Random Forest</strong> that predicts 5 dimensions at once:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
    <span class="s">'workout_split'</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>        <span class="c1"># PPL, Full Body, or Upper/Lower
</span>    <span class="s">'training_modality'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>    <span class="c1"># Machines, Calisthenics, or Weights
</span>    <span class="s">'cardio_approach'</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>      <span class="c1"># None, LISS, or HIIT
</span>    <span class="s">'intensity_level'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>      <span class="c1"># Low, Medium, or High
</span>    <span class="s">'rest_days'</span><span class="p">:</span> <span class="mi">2</span>            <span class="c1"># Number of rest days per week
</span><span class="p">}</span>
</code></pre></div></div>

<p>Predicting them together keeps the plan <strong>coherent</strong>: the outputs are learned jointly instead of by five separate models that might disagree.</p>

<h3 id="why-a-forest-and-not-one-tree">Why a Forest and Not One Tree</h3>

<p>Compared to a single decision tree, the forest gives you less overfitting (thanks to bootstrap aggregation), built-in feature importance, better tolerance for outliers and noisy data, and training that parallelizes easily.</p>

<h2 id="-explainable-ai-implementation">🧠 Explainable AI Implementation</h2>

<h3 id="shap-integration">SHAP Integration</h3>

<p>The transparency comes from SHAP (SHapley Additive exPlanations), which shows how much each input pushed a recommendation one way or the other:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Create SHAP explanations for each prediction
</span><span class="n">explainer</span> <span class="o">=</span> <span class="n">shap</span><span class="p">.</span><span class="n">TreeExplainer</span><span class="p">(</span><span class="n">model</span><span class="p">.</span><span class="n">named_steps</span><span class="p">[</span><span class="s">'classifier'</span><span class="p">])</span>
<span class="n">shap_values</span> <span class="o">=</span> <span class="n">explainer</span><span class="p">.</span><span class="n">shap_values</span><span class="p">(</span><span class="n">input_transformed</span><span class="p">)</span>

<span class="c1"># Generate human-readable explanations
</span><span class="n">clean_exp</span><span class="p">,</span> <span class="n">final_names</span><span class="p">,</span> <span class="n">agg_vals</span><span class="p">,</span> <span class="n">agg_data</span> <span class="o">=</span> <span class="n">create_aggregated_explanation</span><span class="p">(</span>
    <span class="n">shap_values</span><span class="p">,</span> <span class="n">transformed_names</span><span class="p">,</span> <span class="n">current_transformed</span><span class="p">,</span> <span class="n">target_idx</span>
<span class="p">)</span>
</code></pre></div></div>

<p>(<code class="language-plaintext highlighter-rouge">'classifier'</code> is the Random Forest itself.)</p>

<h3 id="aggregating-one-hot-features">Aggregating One-Hot Features</h3>

<p>One annoying thing about SHAP: it scores each one-hot column separately, so “Equipment” shows up as three confusing features. I group them back together:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Define feature groups for aggregation
</span><span class="n">ohe_groups</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">"Equipment"</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">"features"</span><span class="p">:</span> <span class="p">[</span><span class="n">f</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">feature_names</span> <span class="k">if</span> <span class="s">"equip_lvl"</span> <span class="ow">in</span> <span class="n">f</span><span class="p">],</span>
        <span class="s">"labels"</span><span class="p">:</span> <span class="n">EQUIPMENT_LABELS</span>
    <span class="p">},</span>
    <span class="s">"Goal"</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">"features"</span><span class="p">:</span> <span class="p">[</span><span class="n">f</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">feature_names</span> <span class="k">if</span> <span class="s">"goal_id"</span> <span class="ow">in</span> <span class="n">f</span><span class="p">],</span>
        <span class="s">"labels"</span><span class="p">:</span> <span class="n">GOAL_LABELS</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>That gives you explanations like “Equipment: Full Gym increases recommendation” instead of raw one-hot values.</p>

<p>Full transparency: I got this aggregation working for the first chart (the waterfall), but not for the second bar graph below it. It ain’t easy!</p>

<h2 id="-user-interface">🎨 User Interface</h2>

<h3 id="streamlit">Streamlit</h3>

<p>The whole app is Streamlit, which made it quick to build and deploy:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Page configuration for optimal user experience
</span><span class="n">st</span><span class="p">.</span><span class="n">set_page_config</span><span class="p">(</span>
    <span class="n">page_title</span><span class="o">=</span><span class="s">"FitXAI Coach"</span><span class="p">,</span>
    <span class="n">layout</span><span class="o">=</span><span class="s">"centered"</span><span class="p">,</span>
    <span class="n">initial_sidebar_state</span><span class="o">=</span><span class="s">"expanded"</span>
<span class="p">)</span>
</code></pre></div></div>

<h3 id="custom-visualization">Custom Visualization</h3>

<p>I didn’t like the built-in SHAP waterfall plots (they’re brittle), so I wrote my own:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">create_custom_waterfall_chart</span><span class="p">(</span><span class="n">feature_names</span><span class="p">,</span> <span class="n">shap_values</span><span class="p">,</span> <span class="n">data_values</span><span class="p">):</span>
    <span class="s">"""Create custom horizontal bar chart to replace brittle SHAP waterfall"""</span>
    <span class="n">fig</span><span class="p">,</span> <span class="n">ax</span> <span class="o">=</span> <span class="n">plt</span><span class="p">.</span><span class="n">subplots</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span>
    
    <span class="c1"># Sort features by absolute SHAP impact
</span>    <span class="n">sorted_indices</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">argsort</span><span class="p">(</span><span class="n">np</span><span class="p">.</span><span class="nb">abs</span><span class="p">(</span><span class="n">shap_values</span><span class="p">))[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="n">sorted_shap</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">shap_values</span><span class="p">)[</span><span class="n">sorted_indices</span><span class="p">]</span>
    <span class="n">y_pos</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">arange</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">sorted_shap</span><span class="p">))</span>
    
    <span class="c1"># Create horizontal bars with color coding
</span>    <span class="n">colors</span> <span class="o">=</span> <span class="p">[</span><span class="s">'#2ecc71'</span> <span class="k">if</span> <span class="n">v</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="s">'#e74c3c'</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">sorted_shap</span><span class="p">]</span>
    <span class="n">bars</span> <span class="o">=</span> <span class="n">ax</span><span class="p">.</span><span class="n">barh</span><span class="p">(</span><span class="n">y_pos</span><span class="p">,</span> <span class="n">sorted_shap</span><span class="p">,</span> <span class="n">align</span><span class="o">=</span><span class="s">'center'</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="n">colors</span><span class="p">,</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">0.8</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="layers-of-explanation">Layers of Explanation</h3>

<p>Each result comes with SHAP charts showing feature impact, an AI coach summary from the LLM, a weekly workout schedule with exercises, and a downloadable report.</p>

<h2 id="-technical-challenges">🔧 Technical Challenges</h2>

<h3 id="multi-output-shap">Multi-Output SHAP</h3>

<p>For multi-output models, SHAP can hand back a list of arrays, and between all my mappings, targets and features it got confusing fast. This is the extraction that works:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Correct multi-output extraction
</span><span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">shap_values</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span>
    <span class="n">vals</span> <span class="o">=</span> <span class="n">shap_values</span><span class="p">[</span><span class="n">target_idx</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">vals</span> <span class="o">=</span> <span class="n">shap_values</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="p">:,</span> <span class="n">target_idx</span><span class="p">]</span>
</code></pre></div></div>

<h3 id="input-validation">Input Validation</h3>

<p>Inputs are validated with Pydantic:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">FitnessInput</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
    <span class="n">height_cm</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">physique_idx</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">exp_idx</span><span class="p">:</span> <span class="nb">float</span>
    
    <span class="o">@</span><span class="n">validator</span><span class="p">(</span><span class="s">'height_cm'</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">validate_height</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">v</span><span class="p">):</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="mi">100</span> <span class="o">&lt;=</span> <span class="n">v</span> <span class="o">&lt;=</span> <span class="mi">250</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">'Height must be between 100-250 cm'</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">v</span>
</code></pre></div></div>

<h3 id="caching">Caching</h3>

<p>Streamlit’s caching gave me some trouble at first, but it works well now. I leaned on snippets I found in other projects:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">st</span><span class="p">.</span><span class="n">cache_resource</span>
<span class="k">def</span> <span class="nf">load_model</span><span class="p">():</span>
    <span class="s">"""Cache model loading for performance"""</span>
    <span class="k">return</span> <span class="n">joblib</span><span class="p">.</span><span class="n">load</span><span class="p">(</span><span class="s">'fitness_model.joblib'</span><span class="p">)</span>
</code></pre></div></div>

<h2 id="-deployment">🚀 Deployment</h2>

<h3 id="hugging-face-spaces">Hugging Face Spaces</h3>

<p>The app runs on <a href="https://huggingface.co/spaces/william-ai-dev/fit-xai">Hugging Face Spaces</a>. Streamlit apps deploy there with basically no config, the Space is version-controlled, and it’s easy to share.</p>

<h3 id="data-collection">Data Collection</h3>

<p>The app saves anonymized inputs and predictions:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">save_user_data</span><span class="p">(</span><span class="n">user_inputs</span><span class="p">,</span> <span class="n">predictions</span><span class="p">):</span>
    <span class="s">"""Save user input data and predictions to CSV"""</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">csv_file</span><span class="p">,</span> <span class="s">'a'</span><span class="p">,</span> <span class="n">newline</span><span class="o">=</span><span class="s">''</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="p">.</span><span class="n">writer</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
        <span class="n">writer</span><span class="p">.</span><span class="n">writerow</span><span class="p">([</span><span class="n">datetime</span><span class="p">.</span><span class="n">now</span><span class="p">().</span><span class="n">isoformat</span><span class="p">(),</span> <span class="p">...])</span>
</code></pre></div></div>

<p>That data can be used to keep improving the model while keeping users anonymous.</p>

<h2 id="key-learnings">Key Learnings</h2>

<p><strong>What worked:</strong> Multi-output Random Forests gave coherent plans. SHAP explanations make the recommendations easier to trust. Streamlit made prototyping and deployment fast. Aggregating one-hot features made the model readable.</p>

<p><strong>What was hard:</strong></p>

<ol>
  <li><strong>SHAP’s built-in plots were brittle.</strong> Fixed with custom charts.</li>
  <li><strong>Multi-output explanations.</strong> Fixed with careful indexing, but aggregation on the second chart is still an open problem.</li>
  <li><strong>UI stability.</strong> Fixed with a lot of CSS.</li>
  <li><strong>Data preprocessing.</strong> Fixed with a proper pipeline.</li>
</ol>

<h2 id="future-ideas">Future Ideas</h2>

<p>Progress tracking over time, learning from user feedback, wearable integration, workout sharing, and better visualizations.</p>

<h2 id="try-it-yourself">Try It Yourself</h2>

<p>FitXAI is free at <a href="https://huggingface.co/spaces/william-ai-dev/fit-xai">https://huggingface.co/spaces/william-ai-dev/fit-xai</a>. Plug in your info and you’ll get a plan, the explanation behind it, and a downloadable copy. The full source (training pipeline, SHAP integration, custom charts and Streamlit UI) is in the Space repository.</p>

<hr />

<p><strong>Takeaway:</strong> If your model’s output affects what someone does, show them why. A Random Forest plus SHAP is one of the cheapest ways to get there. And I think any engineer who wants to work in AI should be able to explain how their model works under the hood, and prove it.</p>]]></content><author><name>William Golovlev</name></author><category term="AI/ML" /><category term="Random Forest" /><category term="SHAP" /><category term="Streamlit" /><category term="Explainable AI" /><category term="Fitness Tech" /><summary type="html"><![CDATA[How I built FitXAI, a workout coach that explains its recommendations using a multi-output Random Forest and SHAP.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/19.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/19.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Random Forests in 10 Minutes - Wisdom of the Crowd</title><link href="https://william-golovlev.github.io/blog/random-forests-10-minutes/" rel="alternate" type="text/html" title="Random Forests in 10 Minutes - Wisdom of the Crowd" /><published>2026-01-28T12:00:00-08:00</published><updated>2026-01-28T12:00:00-08:00</updated><id>https://william-golovlev.github.io/blog/random-forests-10-minutes</id><content type="html" xml:base="https://william-golovlev.github.io/blog/random-forests-10-minutes/"><![CDATA[<p>Last post we built a neural network from scratch. It worked, but it needed constant babysitting: learning rates, gradients, normalization. This time it’s an algorithm that’s much harder to break and often does better on tabular data: the <strong>Random Forest</strong>.</p>

<div style="text-align: center; margin: 2rem 0;">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/KltwEHLvto4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
</div>

<p>Still <strong>Pandas</strong> for the data and <strong>PyTorch</strong> logic for the mechanics, but a different strategy. Instead of one complex brain, we use a committee of 100 simple Decision Trees. If you missed how we prep the Titanic data, the full series is here: <a href="https://www.youtube.com/@WillGWithAI">https://www.youtube.com/@WillGWithAI</a></p>

<hr />

<h3 id="the-decision-tree-">The Decision Tree 🌲</h3>

<p>A forest starts with a tree, and a Decision Tree is just a chain of yes/no questions.</p>

<p><strong>The logic:</strong> Is the passenger male? If yes, was their ticket 3rd class?</p>

<p><strong>The problem:</strong> A single tree is a perfectionist. It memorizes the training data so well that it falls apart on any passenger it hasn’t seen. That’s <strong>overfitting</strong>.</p>

<blockquote>
  <p><strong>Thought Provoker:</strong> Ask one person for medical advice and they might be wrong. Ask 1,000 and take the most common answer, and you’re using the “Wisdom of the Crowd.” At what point does a group of simple thinkers beat one genius expert?</p>
</blockquote>

<hr />

<h3 id="bagging-diversity-through-randomness-">Bagging: Diversity Through Randomness 🎲</h3>

<p>If all 100 trees saw the same thing, they’d be 100 clones. The fix is <strong>Bagging</strong> (Bootstrap Aggregating), plus a bit of extra randomness.</p>

<p>Each tree gets a random subset of passengers. And at every split, the tree only gets to choose from a random subset of <strong>features</strong> (like Age, Sex or Fare). At one split, Tree A might only get to pick between Age and Siblings. At another, Tree B might only get Fare and Pclass.</p>

<p><strong>The result:</strong> The trees see different things, so they make different mistakes. Average their votes and the mistakes mostly cancel out.</p>

<p><strong>Challenge:</strong> After watching the video, can you explain why we deliberately hide some columns at each split? What would happen if every tree got to split on “Sex” first?</p>

<hr />

<h3 id="why-the-forest-is-so-stable-️">Why the Forest Is So Stable 🏛️</h3>

<p>Random Forests don’t much care if your data is noisy or you forgot to normalize.</p>

<p><strong>Outliers:</strong> One passenger with a $500 ticket won’t wreck a Random Forest the way it can throw off a neural network’s gradients.</p>

<p><strong>No babysitting:</strong> No exploding gradients, no hunting for a learning rate like exactly 2.0. You grow the trees and let them vote.</p>

<blockquote>
  <p><strong>Thought Provoker:</strong> If forests are more stable and easier to build, why did we spend so long on neural networks? Are there problems a forest simply can’t “see”?</p>
</blockquote>

<hr />

<h3 id="picking-the-right-tool-">Picking the Right Tool 🌐</h3>

<p>Building this Titanic predictor in 10 minutes made something click for me: “AI” isn’t one thing, it’s a toolbox. Sometimes you want the precision of a neural network. Sometimes you want a Random Forest that just works.</p>

<p><strong>The trade-off:</strong> We hit high accuracy again, but traded mathematical elegance for logical voting.</p>

<p><strong>Rule of thumb:</strong> For tabular data (rows and columns, like a spreadsheet), try a Random Forest first. It’s a strong baseline with very little tuning. Reach for a neural network when the data or the problem actually needs it.</p>

<p>I’m still surprised how much simpler this was than the NN training loop. Is simpler always better? Not always, but it’s a good place to start.</p>]]></content><author><name>William Golovlev</name></author><category term="AI/ML" /><category term="Machine Learning" /><category term="Random Forest" /><category term="Decision Trees" /><category term="AI Tutorial" /><category term="PyTorch" /><summary type="html"><![CDATA[Moving from a single neural network to a "forest" of decision makers.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/18.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/18.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Turning the Key - Building a Neural Network From Scratch</title><link href="https://william-golovlev.github.io/blog/building-nn-from-scratch/" rel="alternate" type="text/html" title="Turning the Key - Building a Neural Network From Scratch" /><published>2026-01-27T04:00:00-08:00</published><updated>2026-01-27T04:00:00-08:00</updated><id>https://william-golovlev.github.io/blog/building-nn-from-scratch</id><content type="html" xml:base="https://william-golovlev.github.io/blog/building-nn-from-scratch/"><![CDATA[<p>A lot of people treat AI as a black box: data goes in, a prediction pops out. This is the finale of my series, and it’s all code. We’ll walk through the model that predicts Titanic survivors and watch it get better in real time.</p>

<div style="text-align: center; margin: 2rem 0;">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/DQdX1Xsgvg4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>
</div>

<p>No <code class="language-plaintext highlighter-rouge">scikit-learn</code> shortcuts here. It’s <strong>PyTorch Tensors</strong>, manual <strong>Gradient Descent</strong> and our own <strong>Matrix Multiplication</strong>, so you can see exactly how a machine “learns.” If any of those terms are new, look them up first (or catch the earlier videos in my series: <a href="https://www.youtube.com/@WillGWithAI">https://www.youtube.com/@WillGWithAI</a>).</p>

<hr />
<h3 id="the-master-loop-4-steps-️">The Master Loop: 4 Steps ⚙️</h3>

<p>Every neural network trains on the same cycle. Here’s what my <code class="language-plaintext highlighter-rouge">train_model</code> function does, step by step:</p>

<ol>
  <li><strong>Forward pass.</strong> Push the passenger data through the weights and wrap the result in a Sigmoid. Sigmoid squashes any number into the 0 to 1 range, so we can read the output as a probability.</li>
  <li><strong>Loss.</strong> Compare the model’s prediction to the real survival records, using something like mean squared error or cross-entropy. Lower loss means a better model.</li>
  <li><strong>Backward pass.</strong> Call <code class="language-plaintext highlighter-rouge">loss.backward()</code> to get the downhill slope (gradient) for every weight. The loss is a tensor that remembers how it was computed. That’s PyTorch’s automatic differentiation, and it’s the thing a numpy array, Pandas dataframe or plain list can’t give you.</li>
  <li><strong>Step.</strong> Nudge the weights (our “radio knobs”) to be a little less wrong: subtract gradient × learning rate from each one. Then reset the gradients with <code class="language-plaintext highlighter-rouge">layer.grad.zero_()</code> (more on that below).</li>
</ol>

<blockquote>
  <p><strong>Thought Provoker:</strong> If an AI is just matrix multiplications and subtractions, at what point does “math” become “intelligence”? Or is “intelligence” just our word for very complex statistics? It still feels a little crazy to me that some tabular data and basic linear algebra can predict Titanic survival this well.</p>
</blockquote>

<hr />

<h3 id="why-sigmoid-and-normalization-matter-">Why Sigmoid (and Normalization) Matter 🔄</h3>

<p>You’ll see the results wrapped in <code class="language-plaintext highlighter-rouge">torch.sigmoid()</code>. Without it, the model spits out arbitrary, huge numbers.</p>

<ul>
  <li><strong>Normalization:</strong> We divide each input by its max value. Otherwise an Age of 80 looks 80x more important than a Class of 1, just because the number is bigger.</li>
  <li><strong>Sigmoid:</strong> Turns the output into a clean 0 to 1 answer.</li>
</ul>

<p><strong>Challenge:</strong> Look at the <code class="language-plaintext highlighter-rouge">LogFare</code> column we created. After watching the video, can you explain why we took the log of the fare instead of using the raw dollar amount?</p>

<hr />

<h3 id="the-zero_grad-line-">The <code class="language-plaintext highlighter-rouge">zero_grad</code> Line 🧭</h3>

<p><code class="language-plaintext highlighter-rouge">layer.grad.zero_()</code> trips up a lot of beginners. In PyTorch, gradients <em>accumulate</em> across every <code class="language-plaintext highlighter-rouge">backward()</code> call. If you don’t clear them after each step, the model follows directions from where it <em>used</em> to be, not where it is now. In the video I compare it to a GPS: you want it pointing from your current position, not last turn’s.</p>

<ul>
  <li><strong>Delete that line and see what happens.</strong> The model will likely blow up, taking huge erratic steps until the numbers turn into <code class="language-plaintext highlighter-rouge">NaN</code> (Not a Number).</li>
  <li><strong>A human parallel?</strong> When you learn from a mistake, do you carry the old “bad” data with you, or start fresh? I’m drawing a loose line between brains and AI here, and I’m honestly not sure of my own answer.</li>
</ul>

<hr />

<h3 id="whats-next-">What’s Next 🌐</h3>

<p>The engine works. Loss went down and we hit 83% accuracy. But running the code (or watching the video) is only half of it. The useful part is knowing <em>why</em> it works and <em>where</em> it breaks. If you watch the video, please dig into any terminology that’s new to you.</p>

<ul>
  <li><strong>Overfitting:</strong> If we ran this loop 10,000 times, would the model get smarter, or just memorize who survived?</li>
  <li><strong>Bias in the data:</strong> This data is from 1912. Can the model tell us anything about a shipwreck in 2026?</li>
</ul>

<p>Seeing how this works at a low level changed how I think about AI, and I’m excited to build on it.</p>]]></content><author><name>William Golovlev</name></author><category term="AI/ML" /><category term="Neural Networks" /><category term="PyTorch" /><category term="Machine Learning" /><category term="Deep Learning" /><category term="Gradient Descent" /><category term="AI Tutorial" /><summary type="html"><![CDATA[Going line-by-line through the "Master Loop" that powers modern AI.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/17.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/17.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">The AI Compass: Gradients &amp;amp; The Mountain of Loss</title><link href="https://william-golovlev.github.io/blog/ai-compass-gradients/" rel="alternate" type="text/html" title="The AI Compass: Gradients &amp;amp; The Mountain of Loss" /><published>2026-01-26T12:00:00-08:00</published><updated>2026-01-26T12:00:00-08:00</updated><id>https://william-golovlev.github.io/blog/ai-compass-gradients</id><content type="html" xml:base="https://william-golovlev.github.io/blog/ai-compass-gradients/"><![CDATA[<p>We have our radio knobs (weights) and our scorecard (loss). But with 1,000 knobs, you can’t just guess which way to turn each one. You need a compass. That’s the gradient: it tells the model which direction is downhill toward a better score.</p>

<h2 id="the-mountain-in-the-fog">The mountain in the fog</h2>

<p>You’re standing on a foggy mountain peak, trying to reach a warm cabin in the valley.</p>

<p>You can’t see the cabin (the perfect answer), but you can feel the tilt of the ground under your boots. The gradient is a measurement of that tilt. It tells you which way is up, so you know to step the other way.</p>

<h2 id="step-size-learning-rate">Step size (learning rate)</h2>

<p>Even with a compass, you have to pick how big a stride to take. In AI that’s the learning rate (<code class="language-plaintext highlighter-rouge">lr</code>).</p>

<p>Too small and you take baby steps; you’ll be on that mountain forever. Too big and you leap blindly, maybe right over the valley and onto a different mountain.</p>

<div class="video-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/4MvNlbuj4v8" title="The AI Compass: Gradients &amp; The Mountain of Loss" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<h2 id="back-to-the-code">Back to the code</h2>

<p>Remember <code class="language-plaintext highlighter-rouge">requires_grad</code> from the <a href="/blog/tensors-explained/">tensors post</a>? This is where it pays off. Because PyTorch tracked the history of our tensors, it can calculate the gradient for us automatically.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># The "Magic" button
</span><span class="n">loss</span><span class="p">.</span><span class="n">backward</span><span class="p">()</span>

<span class="c1"># Now our coeffs have a "compass" attached to them!
</span><span class="k">print</span><span class="p">(</span><span class="n">coeffs</span><span class="p">.</span><span class="n">grad</span><span class="p">)</span>
</code></pre></div></div>

<p>Each knob gets its own gradient. If a knob’s gradient is positive, turning that knob up would make the loss worse, so we turn it down. That’s why the update step is <code class="language-plaintext highlighter-rouge">coeffs.sub_(coeffs.grad * lr)</code>: subtract the gradient, scaled by the step size.</p>

<h3 id="the-zero-grad-mystery">The “zero grad” mystery</h3>

<p>You’ll see <code class="language-plaintext highlighter-rouge">coeffs.grad.zero_()</code> in my code. That’s because gradients accumulate: each <code class="language-plaintext highlighter-rouge">backward()</code> call adds to whatever is already there. If you don’t wipe the compass after every step, the model follows directions from your last position and your current one at the same time. It’s like trying to go north and south at once.</p>

<h2 id="why-this-matters">Why this matters</h2>

<p>The gradient is the difference between guessing and optimizing. We’re not changing numbers at random. Every adjustment moves the loss downhill, step by step, until it’s as low as it’ll go.</p>

<p>Next, we put it all together in the complete training loop and follow this compass to the valley.</p>

<hr />

<p>This is part 4 of my AI fundamentals series. If you missed the earlier posts on <a href="/blog/tensors-explained/">tensors</a>, <a href="/blog/ai-loss-functions/">loss functions</a>, and <a href="/blog/ai-radio-knobs/">weights and biases</a>, start there.</p>

<p>Let me know what you think on <a href="https://www.linkedin.com/in/william-golovlev/">LinkedIn</a>, and stay tuned for the final video in this series where we run the complete training loop!</p>]]></content><author><name>William Golovlev</name></author><category term="AI/ML" /><category term="Machine Learning" /><category term="Gradients" /><category term="AI Tutorial" /><category term="Neural Networks" /><category term="Optimization" /><summary type="html"><![CDATA[Understanding how gradients guide AI models down the mountain of loss toward better predictions.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/16.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/16.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">The Radio Knobs of AI: Weights, Biases, and the Learning Loop</title><link href="https://william-golovlev.github.io/blog/ai-radio-knobs/" rel="alternate" type="text/html" title="The Radio Knobs of AI: Weights, Biases, and the Learning Loop" /><published>2026-01-26T00:00:00-08:00</published><updated>2026-01-26T00:00:00-08:00</updated><id>https://william-golovlev.github.io/blog/ai-radio-knobs</id><content type="html" xml:base="https://william-golovlev.github.io/blog/ai-radio-knobs/"><![CDATA[<p>In my <a href="/blog/ai-loss-functions/">last post</a> we found the scorecard (loss). But a score doesn’t help if you don’t know how to change it. This post is about the only two things a model can actually move: weights and biases. Then we’ll run the whole learning loop.</p>

<h2 id="what-are-we-actually-turning">What are we actually turning?</h2>

<p>Think of a model as an old-school radio. To get a clear signal, you twist the knobs.</p>

<p><strong>Weights</strong> decide how much each input matters. Predicting house prices? “Number of rooms” gets a big weight. “Color of the mailbox” gets a tiny one.</p>

<p><strong>Biases</strong> are the baseline, the starting value before any input is considered. If you remember <code class="language-plaintext highlighter-rouge">y = mx + b</code> from school, <code class="language-plaintext highlighter-rouge">m</code> is the weight and <code class="language-plaintext highlighter-rouge">b</code> is the bias.</p>

<h3 id="the-code">The code</h3>

<p>My <code class="language-plaintext highlighter-rouge">init_coeffs</code> function sets up the knobs. <code class="language-plaintext highlighter-rouge">torch.rand</code> gives random numbers between 0 and 1, and the <code class="language-plaintext highlighter-rouge">- 0.5</code> shifts them to between -0.5 and 0.5, so every knob starts near zero without leaning either way.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">init_coeffs</span><span class="p">(</span><span class="n">n_coeffs</span><span class="p">):</span>
    <span class="c1"># Creating our knobs and centering them at 0
</span>    <span class="k">return</span> <span class="p">(</span><span class="n">torch</span><span class="p">.</span><span class="n">rand</span><span class="p">(</span><span class="n">n_coeffs</span><span class="p">)</span> <span class="o">-</span> <span class="mf">0.5</span><span class="p">).</span><span class="n">requires_grad_</span><span class="p">()</span>
</code></pre></div></div>

<p><em><code class="language-plaintext highlighter-rouge">requires_grad_()</code> tells the tensors to record every operation that touches these knobs. That recorded history is how the model later figures out which way to turn them.</em></p>

<hr />

<h2 id="the-compass-gradients">The compass: gradients</h2>

<p>With 1,000 knobs, you’d be guessing forever. You need a compass that says which way to turn each one. That compass is the gradient.</p>

<h3 id="the-mountain-in-the-fog">The mountain in the fog</h3>

<p>You’re standing on a foggy mountain (high loss) and want to reach the valley (low loss). You can’t see the bottom, but you can feel the slope under your feet.</p>

<p>The gradient is that slope. Gradient descent is taking a step downhill.</p>

<h3 id="step-size-learning-rate">Step size (learning rate)</h3>

<p>How big is each step? Too small and you’ll never reach the valley. Too big and you jump right over it. In the code, the step size is <code class="language-plaintext highlighter-rouge">lr</code>, the learning rate.</p>

<p><em>Why <code class="language-plaintext highlighter-rouge">coeffs.grad.zero_()</code>? PyTorch adds new gradients on top of old ones. If you don’t wipe them after each step, the model follows stale directions mixed with new ones and gets lost.</em></p>

<p>I go deeper on gradients in <a href="/blog/ai-compass-gradients/">the next post</a>.</p>

<hr />

<h2 id="the-full-loop">The full loop</h2>

<p>We’ve got the tensors, the scorecard, the knobs, and the compass. Now we put them together.</p>

<h3 id="the-4-step-cycle">The 4-step cycle</h3>

<p>From simple linear regression to ChatGPT, training follows the same basic loop:</p>

<ol>
  <li><strong>Predict:</strong> the model makes a guess.</li>
  <li><strong>Loss:</strong> the scorecard says how far off it is.</li>
  <li><strong>Backward:</strong> the gradient finds the downhill direction.</li>
  <li><strong>Step:</strong> turn the knobs a little in that direction, then repeat.</li>
</ol>

<h3 id="the-code-1">The code</h3>

<p>Here’s the engine in a few lines of PyTorch:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># 1. Start the game
</span><span class="n">coeffs</span> <span class="o">=</span> <span class="n">init_coeffs</span><span class="p">(</span><span class="n">n_coeffs</span><span class="p">)</span>

<span class="c1"># 2. Check the score
</span><span class="n">loss</span> <span class="o">=</span> <span class="n">calc_loss</span><span class="p">(</span><span class="n">coeffs</span><span class="p">,</span> <span class="n">indeps</span><span class="p">,</span> <span class="n">deps</span><span class="p">)</span>

<span class="c1"># 3. Find the way downhill
</span><span class="n">loss</span><span class="p">.</span><span class="n">backward</span><span class="p">()</span>

<span class="c1"># 4. Take the step
</span><span class="k">with</span> <span class="n">torch</span><span class="p">.</span><span class="n">no_grad</span><span class="p">():</span>
    <span class="n">coeffs</span><span class="p">.</span><span class="n">sub_</span><span class="p">(</span><span class="n">coeffs</span><span class="p">.</span><span class="n">grad</span> <span class="o">*</span> <span class="n">lr</span><span class="p">)</span>
    <span class="n">coeffs</span><span class="p">.</span><span class="n">grad</span><span class="p">.</span><span class="n">zero_</span><span class="p">()</span>
</code></pre></div></div>

<p>That’s one pass. Training is just steps 2 to 4 repeated in a loop.</p>

<p><strong>The result:</strong> I ran it 10 times, and the loss dropped from 0.51 to 0.02. The model didn’t “think.” It followed the compass until it stopped being wrong.</p>

<div class="video-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/kfLRVfHFnmI" title="The Radio Knobs of AI: Weights, Biases, and the Learning Loop" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<hr />

<p>That’s the full loop at a glance. Tensors, loss, weights and biases, gradients: the same pieces show up whether the model is a tiny regression or a large language model. Next I zoom in on gradients, then build it all from scratch.</p>

<p>Let me know what you think on <a href="https://www.linkedin.com/in/william-golovlev/">LinkedIn</a>.</p>]]></content><author><name>William Golovlev</name></author><category term="AI/ML" /><category term="Machine Learning" /><category term="Weights" /><category term="Biases" /><category term="AI Tutorial" /><category term="Neural Networks" /><category term="Model Training" /><summary type="html"><![CDATA[Understanding how AI models actually learn through weights, biases, gradients, and the training loop.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/15.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/15.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">AI Loss Functions: How a Model Knows It Is Wrong</title><link href="https://william-golovlev.github.io/blog/ai-loss-functions/" rel="alternate" type="text/html" title="AI Loss Functions: How a Model Knows It Is Wrong" /><published>2026-01-25T12:00:00-08:00</published><updated>2026-01-25T12:00:00-08:00</updated><id>https://william-golovlev.github.io/blog/ai-loss-functions</id><content type="html" xml:base="https://william-golovlev.github.io/blog/ai-loss-functions/"><![CDATA[<p>In my <a href="/blog/tensors-explained/">last post</a> I covered tensors, the “memory” of a machine learning model. This one is about the scorecard that tells the model whether it’s getting better or just guessing. That scorecard is the loss function.</p>

<div class="video-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/ISFBiGgdIYY" title="AI Loss Functions: How a Model Knows It Is Wrong" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="">
  </iframe>
</div>

<h3 id="the-dartboard-analogy">The dartboard analogy</h3>

<p>You’re throwing darts. You remember exactly how you threw each one (angle, speed, release), but there’s a catch: you can’t see where the bullseye is.</p>

<p>You’ll never improve that way. You hit the wall, but you don’t know how far off you were, so you can’t adjust the next throw. The loss fixes that. It’s a single number for how far your throw landed from the bullseye.</p>

<h3 id="watching-it-learn">Watching it learn</h3>

<p>To see this in action I used <a href="https://playground.tensorflow.org/">TensorFlow Playground</a>, which shows a model classifying points in real time.</p>

<p>A fresh model is neutral. It doesn’t know which areas are “blue” and which are “orange,” so it starts with a failing grade of around 0.5 loss. As it runs through epochs (loops over the training data), the colored regions on screen get sharper. That’s the loss dropping as the model gets more confident.</p>

<h3 id="learning-too-fast">Learning too fast</h3>

<p>You might think you should crank the learning rate to the max so the model learns instantly. Don’t. If it learns too fast, the math blows up: the numbers get huge and stop making sense.</p>

<p>A moderate learning rate lets the model settle into the right “shape” for the data instead of overshooting and crashing. If your loss suddenly jumps or turns into <code class="language-plaintext highlighter-rouge">NaN</code>, a too-high learning rate is the first thing to check.</p>

<h3 id="how-it-all-collapses-into-one-number">How it all collapses into one number</h3>

<p>Data passes through the network’s layers, and each layer has weights. I think of those weights as radio knobs.</p>

<p>The input (say, coordinates on a graph) gets multiplied and shifted by those knobs. At the end, all of that gets boiled down to a single number, the loss. In my example:</p>

<ol>
  <li>Take the model’s prediction.</li>
  <li>Subtract the correct answer.</li>
  <li>Take the absolute value, because we only care how far off we were, not whether we were too high or too low.</li>
  <li>Average those errors across all the data points.</li>
</ol>

<p>That recipe has a name: mean absolute error (MAE). Other loss functions square the error instead, but the idea is the same: one number, lower is better.</p>

<h3 id="the-rewind-button">The rewind button</h3>

<p>Because tensors remember their history, we can hit a rewind button called <code class="language-plaintext highlighter-rouge">backward()</code>. It carries the error back through every operation and works out how much each knob (weight) contributed to the mistake.</p>

<p><a href="/blog/ai-radio-knobs/">Next up</a>: how the model actually turns those knobs to fix itself.</p>

<hr />

<p><strong>Check out the interactive tool mentioned in the video:</strong> <a href="https://playground.tensorflow.org/">TensorFlow Playground</a></p>

<p>Let me know what you think on <a href="https://www.linkedin.com/in/william-golovlev/">LinkedIn</a>, and stay tuned for the next video in this series!</p>]]></content><author><name>William Golovlev</name></author><category term="AI/ML" /><category term="Machine Learning" /><category term="Loss Functions" /><category term="AI Tutorial" /><category term="Neural Networks" /><category term="Model Training" /><summary type="html"><![CDATA[Understanding how AI models measure their mistakes and learn from them.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://william-golovlev.github.io/assets/blog-images/14.png" /><media:content medium="image" url="https://william-golovlev.github.io/assets/blog-images/14.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>