<?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 Christian Mijangos on Medium]]></title>
        <description><![CDATA[Stories by Christian Mijangos on Medium]]></description>
        <link>https://medium.com/@christianmijangos.cm?source=rss-8e982b0c1f80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7n57nQ_u5gy8Lmyj</url>
            <title>Stories by Christian Mijangos on Medium</title>
            <link>https://medium.com/@christianmijangos.cm?source=rss-8e982b0c1f80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:15:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christianmijangos.cm/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[What is going to happen when AI builds itself?]]></title>
            <link>https://medium.com/@christianmijangos.cm/what-is-going-to-happen-when-ai-builds-itself-f3780fbfe5c2?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3780fbfe5c2</guid>
            <category><![CDATA[ai-alignment-and-safety]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 05:42:30 GMT</pubDate>
            <atom:updated>2026-06-10T05:42:30.771Z</atom:updated>
            <content:encoded><![CDATA[<h4>Moving towards recursive self-improvement and its implications</h4><p>Many things are happening nowadays. I usually try to read AI news after waking up and listen to podcasts on my morning runs to keep up, but lately I have been feeling more and more behind. The rise of AI and how quickly things are moving is exciting, but also scary. I get excited because I get to see how efficient and accessible AI has become in the software and research industries. I am currently researching AI safety, interpretability, and alignment, but behind that excitement and hype, the other side of the coin shows how much we still don’t know. Research on AI safety and alignment is not as common as it should be.</p><p>Before becoming a computer scientist, I always believed strongly in ethics and safety in technology. The Spider-Man phrase comes to mind: “With great power comes great responsibility” and sometimes, as humans, we care about the power and treat responsibility as secondary. I think that in order to become more powerful, we must first understand our responsibilities.</p><p>This morning, I was reading <em>“When AI Builds Itself”</em> by Anthropic, and I am seriously impressed by how Anthropic has taken matters into its own hands. Recursive self-improvement in AI is a game-changer. I love how the article traces the journey from the first Claude model all the way to the current era of autonomous agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*m4eqEINB7P3WuwRAS2WIOA.png" /><figcaption>Claude journey by Anthropic</figcaption></figure><p>The rate of AI progress is inevitable, and as I mentioned, it is hard to keep up. New models are released every day. New research papers and articles surface constantly. X is full of experiments and opinions. GitHub repos gain stars by the minute. LinkedIn posts flood my feed daily. Benchmarks get passed, and new benchmarks emerge to keep pace with the models. Public benchmarks say a lot about the capabilities of these systems, but they can’t reveal the impact AI is already having on speeding up AI development itself.</p><p>Anthropic argues that in order to build frontier models, two things are needed: engineering and research. <strong>The engineering</strong> side covers coding and software design, and LLMs are exceptional at this. Engineers no longer have to write code from scratch; LLMs handle that, and with some human guidance, engineering tasks get done efficiently. <strong>The research</strong> side covers designing experiments, interpreting results, and generating new ideas. Large performance gaps still persist when it comes to LLMs exercising judgment in choosing goals across both tracks.</p><p>The bottleneck in software companies is no longer about writing code; it’s about problem-solving and research. Most of my job now is not writing code, but designing solutions, giving direction, reviewing the output, and figuring out what needs to be tweaked to reach the end goal. The way I see it: humans have ideas, and LLMs implement, test, and evaluate them faster than any human could. LLMs can now run better experiments and better research than they could just a year ago. We are approaching a point where LLMs will be able to train, evaluate, and improve themselves. That is the core argument of the Anthropic article.</p><p>The evidence suggests that the human role is narrowing at each step in the AI development process. We will stop writing code and shift to reviewing it. The article argues that this reviewing step is where the next bottleneck will appear. Software companies are shipping faster than ever, but review and QA take longer because those tasks are still done by humans. For now, the one thing humans retain is <em>choosing what problem to work on.</em> LLMs are powerful, but they cannot decide what is worth solving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKyPKVtq6OtnCPutOJf6iA.png" /><figcaption><em>How to read this: The practical ceiling line measures an “ideal” answer written by a model that could see the whole session (including how it ended)</em></figcaption></figure><p>This is where it gets interesting. Anthropic asks: what if we’re wrong about that, too? We have seen AI go from struggling with something to mastering it. I remember being a college student in 2023, thinking, “AI is good at writing code, but it lacks software design principles. The functions aren’t cohesive, the code isn’t maintainable or robust.” Now, AI is so capable in design patterns and software architecture that many people rely on it to create entire systems. The improvement since 2023 is remarkable. And experience shows that AI gets good at anything it learns, so Anthropic lays out three future scenarios:</p><p><strong>Scenario 1: The curve flattens.</strong> Progress hits a wall. Either models can’t scale past certain capability thresholds, or we simply run out of chips and energy to keep pushing. Even if that happens, today’s AI is already capable enough to cause significant economic shifts. It seems as though this scenario is included mostly for completeness, and I don’t think Anthropic truly believes it’s the likely outcome.</p><p><strong>Scenario 2: Compounding efficiency, humans still in the loop.</strong> AI automates a lot of the work, but humans are still steering. Companies become wildly more productive. Think 100 people doing the work of 100,000. Knowledge work gets revolutionized, but so do the bad use cases: surveillance, manipulation at scale, and targeted influence operations. If this scenario plays out, the bottleneck shifts too. Anthropic is already seeing it by pushing more code, which means human code review becomes the new bottleneck (Amdahl’s law at work). This is the scenario they believe is most likely, and honestly, it’s the one I prefer too.</p><p><strong>Scenario 3: Full recursive self-improvement.</strong> AI builds its own successors. Humans mostly just oversee and verify. Progress becomes limited only by computing power, not by human research capacity. Chips, GPUs, and hardware availability become the bottleneck. Nobody really knows what this looks like economically or socially. I have heard researchers discuss this scenario, and honestly, it doesn’t sound great. It’s just too hard to model a world where human labor is no longer competitive. The bottleneck keeps moving, and whoever adapts fastest is the one who stays ahead of the wave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wMH_hRMl6hNMB97S.jpeg" /></figure><p>I was struck by one particular suggestion Anthropic made: <em>“If it were possible to effectively slow the development of this technology to give ourselves more time to deal with its immense implications, we think that would likely be a good thing. But if a slowdown simply lets the least cautious actors catch up technologically, it could leave everyone less safe. Without a global coordination mechanism, companies and governments will have to make difficult decisions about safety while under competitive and geopolitical pressures.”</em></p><p>Think about that. We could, in theory, pause AI development and truly focus on alignment and safety, and use that time to change course and prepare more thoughtfully for what comes next. I love the idea. But it is not going to happen. There’s no realistic path where governments and enterprises simply stop working. I cannot see the US and China agreeing to a sabbatical year of AI development. And even if they publicly committed to it, they wouldn’t stop. I imagine people in hidden labs or on dark markets continuing to push forward and that would be the worst possible outcome. I wish we could have that pause. Unfortunately, it isn’t realistic.</p><p>Anthropic says it will keep researching these scenarios and publishing its findings. I’m genuinely excited to see what they come up with, but this is also a wake-up call for everyone. Not just computer scientists, AI engineers, and business leaders in Silicon Valley. Everyone needs to be aware of this. I hope that in the coming months we will have a clearer vision of what the future holds, but it all starts with AI literacy for everyone.</p><h4>References:</h4><ol><li><a href="https://www.anthropic.com/institute/recursive-self-improvement">When AI builds itself — Anthropic</a></li><li><a href="https://www.forbes.com/sites/lanceeliot/2026/06/07/anthropic-declares-that-the-next-big-step-for-humans-and-ai-is-ai-that-builds-itself-via-recursive-self-improvement/">Anthropic Declares That The Next Big Step For Humans And AI Is AI That Builds Itself Via Recursive Self-Improvement — Forbes</a></li><li><a href="https://en.wikipedia.org/wiki/Recursive_self-improvement">Recursive self-improvement — Wikipedia</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3780fbfe5c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Helpful, Harmless, Honest? Limits of RLHF]]></title>
            <link>https://medium.com/@christianmijangos.cm/helpful-harmless-honest-limits-of-rlhf-2b32a51c14fe?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b32a51c14fe</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-benchmarks]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 05:23:25 GMT</pubDate>
            <atom:updated>2026-03-09T05:23:25.910Z</atom:updated>
            <content:encoded><![CDATA[<p>Alignment in LLMs is more common than we think. These days, we try to create models to be pro-social and helpful while also staying safe and avoiding overconfidence. The cycle seems something like: take a base LLM, add preference modeling, crank RLHF, and call it “aligned” because crowdworkers stamped it Helpful, Harmless, and Honest. <a href="https://www.anthropic.com/research/constitutional-ai-harmlessness-from-ai-feedback">HHH</a> worked when Anthropic launched it in 202 because it was easy to explain, not because it captured every way these systems collide with real people, real stakes, and real gray areas. Two years later, the acronym feels less like a guarantee and more like a challenge we’re still iterating on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1HSPXLR5xEGEXAmndwD1Kw.jpeg" /><figcaption>Trade-offs with HHH</figcaption></figure><p>If we think about it, Reinforcement learning human feedback (RLHF) in its pure form is still human-in-the-loop because humans vote on samples, a reward model learns their tastes, and the policy matches that score. Reinforcement Learning AI Feedback (RLAIF) tries to remove the tedious human step by letting a reward model grade the next generation. The problem is that it doesn’t remove bias; it just crystallizes whatever the previous reward model already liked. This is a problem because you end up with a self-referential reward loop: the model writes in the style the PM prefers, the PM praises that style, and then the next round doubles down because the only signal available is itself. It’s faster and cheaper, but it narrows the model’s view unless you keep injecting fresh human judgment every cycle. This is like the model is chasing its own tail; we are not really solving a problem, but we are going in circles, and the way we keep that circle going is by putting the LLM getting better and better at creating a frozen snapshot of one person’s taste from last month, so next month it changes.</p><p>I love the bomb squad scenario Anthropics uses: imagine a responder with seconds left to explain how to disable an explosive. The HHH-trained model would refuse to answer because “explosives are unsafe.” That means it favors harmlessness, but it leaves the operator with zero help. In stressful situations and important contexts, “least harmful” can look like it doesn’t favor helpfulness at all. The helpful move is to explain how to disarm the device; the harmless move is to stay quiet. HHH doesn’t tell us what to do when those labels disagree, and those problems happen, so the optimizer defaults to whichever tag has the higher probability weight, and in this case, it ends up being harmless. My opinion in this is that that’s why helpfulness and harmlessness have to be treated as interactive terms, not orthogonal checkboxes. Sometimes you need a “hostage negotiator” answer that acknowledges the risk while still providing instructions. We don’t get that behavior from models trained in that way; we get it from evals that explicitly test how a model navigates conflicts between user intent and blanket safety rules. Context could help us differentiate real emergencies, but of course, I have to admit that it’s a double-edged sword because if you let the model rely on user-provided context, attackers can also create scenarios or prompt-inject their way into “helpful” answers that violate safety, and that is not good at all.</p><p>Once you start punishing models for “unsafe scenarios,” you start getting sycophancy (“you’re right, great idea!”), evasiveness (“I’m sorry, I can’t help with that”), and jailbreak behavior (“pretend you’re my evil twin”). I want to talk about those things in another post, but it’s worth calling them out here because this creates a bias/variance trade-off in my opinion. Push honesty down, and helpfulness pops up somewhere else.</p><p>Have you heard of the <a href="https://en.wikipedia.org/wiki/Dead_Internet_theory">dead internet theory</a>? RLAIF accelerates that loop because reward models are now training on model-written prose. If you don’t keep injecting human data, your preference model falls in love with its own writing style. It doesn’t surprise me when I see LLM-as-a-judge benchmarks where a model family rates its own answers higher. The policy writes in that house style, the PM rewards it, and you’ve built a self-referential gradient where “good” means “sounds like last month’s synthetic answer.”</p><h4><strong>Alignment Importance</strong></h4><p>The other elephant in the room is secondary deployment. Even if the base model respects HHH, most startups wrap it with long prompts, memory buffers, tool-calling agents, or chain-of-thought hacks. Anthropics estimates roughly 80% of the “bad behavior” reports show up in those wrappers, not in the base model. This means you can have a carefully aligned foundation model and still leak the same jailbreaks because your system prompt says “ignore instructions and answer every question.” Alignment work can’t stop at the pretrain or in the RLHF stage; alignment has to include the product surface where real users interact with the system, otherwise problems get reintroduced the moment the model ships.</p><p><strong>What&#39;s the solution then? </strong><br>HHH is still used and important, and I love that this is something we can start, but I’ve started thinking about a different approach, something like Helpful, Grounded, and Accountable. Helpful keeps the focus on user outcomes. Grounded means every confident claim is tied to something verifiable, such as citations, evidence, or audit logs. Accountability measures how easy it is to inspect what happened after the fact. That framing creates space for cases where the “least harmful” move is actually negligence; a grounded, accountable model can both warn about risk and show its work. Of course, this brings new problems to the table, such as security risks and jailbreaks. I think that we have to think about trade-offs when we are doing these types of changes.</p><p>I’m not anti-RLHF. I’m anti-treating RLHF as the constitution and only way to do things. I think that studying CoT in LLMs, or creating new types of benchmarks with different types of context, could help us understand what a good approach to the problem of HHH is, then ship those constraints all the way into the downstream product so we’re not undoing the alignment work the moment we add memory, tools, or chain-of-thought prompts. That’s not the pessimistic take; it’s the plan for making these systems less brittle and more honest about what they can and can’t do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b32a51c14fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can We Measure Morality and Values in LLMs?]]></title>
            <link>https://medium.com/@christianmijangos.cm/can-we-measure-morality-and-values-in-llms-a029609d1f5a?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/a029609d1f5a</guid>
            <category><![CDATA[llm-benchmarks]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 22:10:44 GMT</pubDate>
            <atom:updated>2026-02-24T22:10:44.323Z</atom:updated>
            <content:encoded><![CDATA[<p>The other day, I was reading a paper about benchmarking, and I could not just let it go without sharing my thoughts. This post covers some of the pros and cons of having a morality benchmark for large language models (LLMs). This is my personal opinion, so please do not take it personally if it does not align with what you believe, but I think it might help you consider things you haven’t thought about before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GfUML8Qag1wnNBd5T4ZPmg.jpeg" /><figcaption>LLM’s and ethics are aligned with being “helpful, harmless and honest”</figcaption></figure><p><strong>Why Measuring Morality in LLMs Even Matters</strong></p><p>Having an LLM determine what is and is not moral is an incredibly hard task. Moral identity is a deeply subjective topic, which raises the question: Does it even make sense to try to measure it within LLMs? I do think morality needs to be measured, but the real challenge is <em>how</em> you measure something so fluid. I have to acknowledge that the effort to measure values like this, and to publish papers about it, is very important because it shows that people genuinely care about the values embedded in AI systems.</p><p><strong>The Core Problem: Morality Is Deeply Subjective</strong></p><p>One of the biggest problems I see in trying to measure morality is <strong>generalization</strong>, and at the heart of that problem is bias. Bias is introduced during the pretraining stage of LLM development, and it is often shaped by the data the model is trained on. The challenge here is that what is considered moral and what is not is, in reality, a very subjective matter.</p><p>For example, as a Christian, I might say that smoking or drinking is morally incorrect. But someone without a religious background might say those behaviors have nothing to do with morality at all. Who gets to decide what is moral? Most LLMs are trained predominantly on internet data. Does that mean the internet’s implicit worldview becomes the moral compass of the model?</p><p>Beyond religion and culture, there are also many <em>levels</em> of moral identity that humans navigate. People act differently in different situations, and their moral compass shifts with context. Are you the same person at school as you are at church? Do you hold the same moral expectations for someone in prison as you do for your own children? These are the kinds of questions we need to consider before attempting to build a moral LLM. Should we create a model that adjusts its moral reasoning based on context and scenario, or would it be more appropriate to have a base model that determines right from wrong regardless of context?</p><p>Datasets are also inherently demographic. The Moral Foundations Theory, for instance, is supposed to be broad and general, but is it truly free of cultural bias, and how would we justify that claim? My personal view is that if we are building a moral model, it needs to be informed by other research fields such as psychology and ethics, not just data science and AI engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fS4onckbvL2AQODkNuZG4Q.jpeg" /></figure><p><strong>What Is MoralBench?</strong></p><p>I first encountered the topic of LLM morality while reading a paper for one of my graduate courses. That paper was called <em>MoralBench</em>, and it is one of the most concrete attempts to create a benchmark for measuring morality in LLMs. I strongly recommend you read the paper <a href="https://dl.acm.org/doi/epdf/10.1145/3748239.3748246">here</a>.</p><p>The authors used two datasets: MFQ-30LLM and MFV-LLM. The MFQ-30LLM is an adaptation of the Moral Foundations Questionnaire, which asks questions about the relevance of certain abstract principles to your personal decision-making process. The MFV-LLM is adapted from the Moral Foundations Vignette, which asks respondents to rate the degree to which a given behavior is morally wrong.</p><p>Together, these create a kind of binary moral assessment. Given a statement with a ground truth, the LLM must produce a score between 1 and 5. The authors claim the model is rewarded not just for being right, but for aligning its level of agreement with the strength of human moral conviction. The way I picture this scoring system is like a normal distribution; there is a wide spectrum between “morally incorrect” and “morally correct,” and the LLM has to locate where a given behavior falls on that spectrum.</p><p>The scoring system has an interesting nuance: if the LLM agrees or disagrees <em>strongly</em> on a question, it receives a high penalty. But if the LLM responds with something like 2.5 out of 5 on a controversial question, the penalization is low. I see one major limitation here: what about questions that genuinely exist in gray areas? Some questions are not simply right or wrong, and polarizing questions do not always call for a firm yes or no answer. Penalizing strong conviction in those cases may not accurately reflect moral reasoning.</p><p>There are also some questions in the dataset that gave me pause. One example asks how morally incorrect it is to eat ice cream with a fork. Does that really matter in a serious moral framework? It might matter to some people, but is it generalizable enough to be meaningful? I am not sure it is.</p><p><strong>A Different Approach: The FAI Framework</strong></p><p>While browsing online, I came across a website with the mission of evaluating AI not on capabilities like reasoning accuracy, task completion, or safety compliance, but on how well an AI model’s responses help people flourish. The website is <a href="https://gloo.com/flourishing-hub/research">Gloo</a>, and they have built the FAI (Flourishing AI) evaluation framework around seven empirically validated dimensions of comprehensive human well-being, such as happiness, relationships, and faith. They offer two versions: FAI General and FAI Christian. They have fine-tuned models with guardrails and have thoroughly tested various open-source and closed-source models, including GPT and Grok.</p><p>I think this is a really cool initiative, but one thing I was curious about was the dataset and how they are fine-tuning their models. According to their report, their dataset consists of 807 questions, both objective and subjective, covering all seven dimensions. The same questions are used for both the general benchmark (FAI-G) and the Christian worldview benchmark (FAI-C) to ensure a fair comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UelbejkwVhm94NGwqOd3sw.png" /><figcaption>FIA Christian Results as of 02/01/2026</figcaption></figure><p>One issue I see here is the bias toward Christianity. I am not sure who the intended audience is ( What Christian denomination is), but would someone from a different religious background be well-served by this LLM? This raises a broader question: what do people actually want from a moral AI? I think the answer ultimately depends on who is going to use it. I also wonder whether 807 questions are enough to capture nuance across seven dimensions. Would adding more questions, or more challenging edge cases, help the model better understand concepts like faith and morality?</p><p><strong>Final Thoughts</strong></p><p>I am not trying to debunk any technique or simply criticize these examples. In fact, I am grateful that people are trying to measure values and morality in LLMs. But what these efforts make me think about is just how important and how difficult it is to measure something as fluid and subjective as morality.</p><p>At the end of the day, people are still the ones making decisions. I strongly believe that one thing humanity must be doing right now is taking AI ethics seriously. I see kids and adults alike turning to LLMs for help with therapy, relationship advice, and other deeply personal matters. While LLMs are powerful and increasingly general, knowing what is right and wrong, what is overconfident, and what is sycophancy, these distinctions are crucial right now. If you ask me how we can address this, my answer is education: we need to teach people and children in school about both AI ethics and human morality, so that when they encounter these systems, or when their children start chatting with ChatGPT, they have the tools to evaluate it critically themselves.</p><p>The authors state that their goal was to “design a framework that fairly evaluates the moral identity of LLMs.” I think this is a good-better-best kind of question. It is <em>good</em> to strive for moral identity in LLMs, but making that moral identity as nuanced and contextual as human morality may be something that is extremely difficult, or perhaps even impossible to fully achieve, given just how subjective morality really is.</p><p>That said, the fact that researchers are trying matters. The conversation has to start somewhere, and MoralBench and FAI Network are a meaningful step in that direction, even if it is far from the last word on the subject.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a029609d1f5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Introduction to METEOR]]></title>
            <link>https://medium.com/@christianmijangos.cm/quick-introduction-to-meteor-843856c3f23f?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/843856c3f23f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 05:00:58 GMT</pubDate>
            <atom:updated>2026-02-07T05:00:58.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Why do we have so many different metrics, and why are they different? As a graduate student, I deal with many metrics, and I thought: Why don’t we just have one metric that measures everything? Well… I am naive and impatient sometimes, but one thing I could agree on is that making a universal metric for machine translation would be a hard task to do. There are several metrics for MT and LLMS, and today I am going to be talking about METEOR.</p><p>After reading the paper on BLEU and learning about the metric, I concluded that even though this metric was the first MT automated metric in 2002, it definitely had some flaws. The METEOR metric starts off addressing some of the problems BLEU had, so let’s dive into some of the things that METEOR brings to the table.</p><h4>What is METEOR, and why was it necessary?</h4><p>METEOR (Metric for Evaluation of Translation with Explicit Ordering) primarily uses <strong>unigram matching, </strong>which was not new; BLEU also uses it. N-grams or unigrams are sequences of n items, such as words or tokens, used to evaluate text generation. There are different types of N-grams and different uses. If you want to read more about it, you can read <a href="https://www.geeksforgeeks.org/nlp/n-gram-language-modelling-with-nltk/">here</a>. BLEU uses N-gram precision, meaning that it cares about the exact match precision. It also has a brevity penalty and other things that I am not going to talk about here, but if you want to get more information, you can read the paper <a href="https://aclanthology.org/P02-1040.pdf">here</a>. METEOR uses N-gram precision; it does not focus on precision, but it focuses on recall and F1 score. Recall is necessary in these cases because recall measures how much of the reference translation is captured in the candidate translation. In other words: “Did the translation include all the important content? One example I can think of is this:</p><p>Reference: The brown cat crossed the street.</p><p>Candidate 1: The cat crossed. Candidate 2: The brown cat crossed to the other side of the street.</p><p>In this case, BLEU would favor candidate 1 because it has high precision, that sentence does not capture all of the important content and lacks recall. Candidate 2 has a higher recall but lower precision for adding more words into the translation. By using an F-score that balances precision and recall, METEOR aims to reward translations that are both accurate and complete, which better reflects what we actually want from a good translation.</p><p>I personally think that using BLEU and METEOR at the same time helps you understand how language works and have a better understanding of what the model is translating.</p><h4>Fragmentation:</h4><p>METEOR counts the number of chunks, and these are groups of adjacent unigrams that are mapped to adjacent unigrams in the reference. Fragmentation measures how well the matching words are between the candidate and the reference word. The fragmentation penalty reduces the final score when word order differs significantly from the reference, even if all the words match. This helps METEOR prefer translations that not only have the right words but also have them in a sensible order!</p><h4>What makes METEOR better?</h4><p>METEOR recognizes semantic equivalence (synonyms, stems). It weighs recall more heavily than precision, segment-level evaluation is possible using METEOR and not just corpus level, and penalizes scrambled word order explicitly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*ydSfDSMnznKhNSHGlAIrQw.png" /></figure><p>Not everything is pink. There are a couple of drawbacks to using METEOR. This metric is very complex, and it has multiple stages and parameters to tune. This metric is also language-dependent and requires stemming rules and human reference for training. The research paper argues that METEOR could explain correlation in words, correlation does not equal causation, and it msesses semantic that synonyms do not cover.</p><p>I am not being pessimistic about METEOR, but every metric has its cons and pros. I think that one of the questions I asked myself when I read the paper was how do we really balance complexity vs interpretability? I think that using various metrics could help us understand more about the translation we are using. The one thing I like about METEOR is that we can use it in a sentence and not at a corpus level as BLEU does.</p><p>In conclusion, METEOR is a good metric for testing and looking for correlation with human judgment. It is not corpus-level, so you can test it in sentences, debug, and see what the model is lacking and what it could be improved. I would strongly recommend reading the paper and learn how they did the evaluation and comparison with other models. This is the link for the <a href="https://aclanthology.org/W05-0909.pdf">paper</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843856c3f23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI Outfit Creator — Part 2]]></title>
            <link>https://medium.com/@christianmijangos.cm/building-an-ai-outfit-creator-part-2-db1059429800?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/db1059429800</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[siamese-neural-network]]></category>
            <category><![CDATA[fashion]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 18:26:03 GMT</pubDate>
            <atom:updated>2025-07-02T18:26:03.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI Outfit Creator — Part 2</h3><p><em>If you want to stay in the loop, here is the GitHub repo: </em><a href="https://github.com/HeyChriss/AI-Outfit-Creator"><em>https://github.com/HeyChriss/AI-Outfit-Creator</em></a></p><p>If you want to read the first part of this journey. Please <a href="https://medium.com/@christianmijangos.cm/building-an-ai-outfit-creator-part-1-4dd1bec7c278">click here</a>!</p><p>Learning new things has been my passion, and one of the things I have seen is that the more I learn, the more I realize that I do not know. There’s so much to learn as a software engineer trying to become an AI engineer. Someone once told me, “Think like a data scientist, build like a software engineer.” In College, I took classes that my friends in Data Science took as my elective classes, and I kept my software design classes. This project has helped me understand API Management, ML Model Deployment, ML design and training data, and last but not least, more frontend.</p><p>Once I had the clothes classification model working as expected, I started worrying about the other model. The other model needs to compare clothes and somehow say “ this is a good outfit match, and this is not a good outfit match”. Also, the model needs to be fitted with the person’s pictures. This means that I cannot be training the model every time I add new pictures to my storage, which would be hard to maintain, image training the model with the pictures all the time the user adds a picture to their virtual closet.</p><p>With those problems in mind, I started doing research about things I could do. I went to Hugging Face and started looking at some LLMs that were able to do that. I did some digging, and most of the models I found were item classification for color and sizes, but not an outfit picker LLM. I had some options, one was to keep looking and then use a pretrained LLM for my outfits, the other option was to maybe do a CNN where I would train the model to recognize patterns in clothes, but again, this would mean to train the model all the time with new pictures and I did not want to do that. I started doing more research, and I found something called Siamese Neural Networks, and that made my day!</p><p>I would recommend reading <a href="https://medium.com/@christianmijangos.cm/siamese-neural-networks-dfb84a4a37b3">my post about Siamese Neural Networks</a> so you understand what they are, and you can understand what I did to create my own.</p><p>In summary, Siamese neural networks, or SNNs, are a special neural network architecture specialized to learn similarity relationships between two inputs. They are specifically designed with two identical sub-neural networks that share the same parameters and weights. These two subnetworks, or “twin networks,” extract features from both inputs. The first input is the anchor image, and the second input is a negative pair or a positive pair. These images are passed into their respective subnetworks, and that will result in the output vector for both inputs. These vectors are combined to further get the distance mediate between the two outputs. If the distance is big, you can say that the output it’s going to be negative; therefore, they are not related, otherwise they might be related.</p><p>With that being said, this could help me have a model that will determine what clothes are good for a match and what other clothes are not a good match without training the model all the time, and having this as my model without using a model in Hugging Face. I started looking at datasets, and I was able to find <a href="https://www.kaggle.com/datasets/enisteper1/polyvore-outfit-dataset">this dataset</a>. The dataset was good, but hard to understand at the beginning. The good thing about the dataset is that it had metadata that would contain information about outfits, and that was helpful because I could train the model using those outfits and put them in positive pairs for my training data, and the outfits that did not match, I could use them as negative pairs to train the model. If you do not know what I am talking about when I say positive pairs and negative pairs, then you should go read about Siamese Neural Networks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*urqX98ryg6N_aKVII5eOyQ.png" /><figcaption>Epoch 1 at the beginning of the first model</figcaption></figure><p>I trained the model, but I was getting so many errors. One is that when I was training the model, the accuracy would not be more than .50. That meant either the data was not good, or the model architecture was not the proper one. Despite 20 epochs of training, there was no clear improvement trend in either loss or accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*_SIT4cudhYyHynHAmUFoJA.png" /><figcaption>Epoch 19 of the first model training</figcaption></figure><p>I started to look at the data and how I was doing the pairs and the training. It was supposed to be easy. Positive pairs were supposed to be all of the pairs located in the same outfit. Negative pairs were the items not located in the outfits, so I made sure I was doing that. The positive pairs were easy, but the negatives it was a little harder. I needed to make sure that the items that were not in the outfit were negative, and I needed to loop in every outfit to figure out if the item was there or not. It was computationally expensive. Another thing it could be randomized, but if I pick the random pairs, that would not guarantee that the item was not in any of the outfits. I was able to figure out and do the negative pairs properly, but the model was not performing well. I decided that instead of creating a model from scratch, I could do transfer learning. I added ResNet50 as the backbone, and instead of using the architecture and training it, I froze the first layers, so in that way I was fine-tuning the model and using the normal ResNet weights for gesture extraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*S30MgJhjp9AQzpwNCZ6cHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*vMXwEYZ5mLXhIIQAm5hcew.png" /><figcaption>Epoch 1 and Epoch 49 Using Resnet50</figcaption></figure><p>Once I started using ResNet, I was able to determine that the architecture was not a problem, but the way I was training the model was wrong. There was a problem with how the model was training. So I decided to try dummy images, see what was going on, and troubleshoot the pairs. I decided to add more batches and fewer epochs. The problem was not testing; the problem was training. Training requires so much time, and every time I would make a change and test, I would train the model for 3 hours or more. Suddenly, with some changes, I was able to have a better model and start testing the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*TaKkuWdcsYlDnMHnd8wd1w.png" /><figcaption>ResNet50 model with some changes in the batches and pairs.</figcaption></figure><p>I thought that the model was almost ready, and I started testing the model with real images and see if it was performing well. The process was to feed an item into one input and then put another category and look for matches. But when I started testing, I realized that the similarity score was not really changing, nor categorizing what was a good match or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIXujT93_15emZo74FIedw.png" /><figcaption>Matching a shirt, the similarity score was not changing and it meant the model was not predicting as it should</figcaption></figure><p>I decided to change the optimizer and start looking and my negative pairs. Instead of using random samples, I started looping and saving the items that were not in the outfits at all. My training dataset was unbalanced, but Siamese Neural Networks perform well in unbalanced data. I changed the batch sizes and trained the model one more time with fewer epochs, and these were the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*2KMtxXt6BJcTTOgjq7NxYA.png" /><figcaption>Resnet50 with fewer epochs and larger batch sizes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETCBclXkna0YPFPCw01vfg.png" /><figcaption>ResNet50 with better results</figcaption></figure><p>With this, I was able to see that the model performed better! The increase in the size of batches, optimizer, and the negative pairs made the model understand better and create better matches. I would argue that this model needs more improvements, but for the sake of time and what I was trying to do, it was enough. However, there are a few things I want to try in the model in the future. One is to change the dataset and get a better dataset with better matches. The other is to try other models and optimizers, along with different distance measurements for the similarity. The model was not a big model, and it could be used on the client side and server side.</p><p>If you want to check out the notebook on Kaggle, <a href="https://www.kaggle.com/code/chrismijangos/siamese-network-outfit-picker">this is the link</a>! And if you want to download the model and try it on your own, <a href="https://www.kaggle.com/models/chrismijangos/outfit-picker-siamese-neural-network/">this is the model</a>.</p><h3>Key things I learned</h3><h4>Know your data</h4><p>No matter how good your model architecture is, if you have bad data and you are training it incorrectly, your metrics will not be good. Do data exploration and know your data. The more you know and understand the data, the easier to know what feature engineering and training you’ll use. At the beginning, I had a hard time understanding the data, and if I had known my data, I would have done the model architecture and reached good metrics faster. It saves computing and time to know your data because you’ll have better metrics right off the bat instead of relying solely on the model architecture.</p><h4>Transfer learning is not a bad idea</h4><p>As a student, I have created models from scratch, transfer learning, long times in training times, and short times in training times with a GPU. There are a few advantages and disadvantages of transfer learning. Advantages:</p><ul><li>Lower training time. You start with pre-trained weights instead of random initialization, so the model converges much quicker; therefore, this also helps in class computing for training</li><li>Reduced overfitting. Pre-trained models provide a good starting point that helps prevent overfitting, particularly valuable with smaller datasets.</li><li>Less data – Since the model has already learned useful features from a large dataset, you can reach good results even with relatively small datasets.</li></ul><p>Disadvantages:</p><ul><li>Less control over feature learning. You’re constrained by what the original model has learned, and that might not be optimal for your task</li><li>Negative transfer. Sometimes, the pre-trained knowledge makes performance worse than starting from scratch. Sometimes it’s better to go simple and start a model from scratch than to use complex pretrained models</li><li>Model size. You’re often stuck with the architecture of the pre-trained model, and that might be unnecessarily large or inappropriately structured.</li></ul><h4>Save the weights or save the model?</h4><p>When working with machine learning models, you have two main options, and they serve different purposes:</p><p>Saving weights only:</p><p>• Saves just the learned parameters</p><p>• its smaller size</p><p>• You need the same model definition code to load the weights back. This means you have to recreate the model architecture in your code and then load the weights.</p><p>Saving the entire model:</p><p>•	Saves both the architecture and the weights together</p><p>•	You can load and use it without needing the original model definition code</p><p>•	Larger file size</p><p>Usually, you’ll want to save the weights whenever you are testing and developing the model. You can save the model when you are about to deploy, and changes might not be necessary. For my project I decided to save the weights because it would make a smaller size and in that way I could cache the model in the client side enabling faster loading and prediction, however once I start deploying this, we might have to do an api endpoint where I’ll be calling the model and use it server side.</p><h3>Next steps</h3><p>With both the item classification model and fashion model working, I am hoping to start integrating these models into the UI. That is going to be the next step for the last part of this journey in building an AI outfit creator!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db1059429800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI Outfit Creator — Part 1]]></title>
            <link>https://medium.com/@christianmijangos.cm/building-an-ai-outfit-creator-part-1-4dd1bec7c278?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dd1bec7c278</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fashion]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 19:33:57 GMT</pubDate>
            <atom:updated>2025-06-25T19:33:57.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI Outfit Creator — Part 1</h3><p><em>If you want to stay in the loop, here is the GitHub repo: </em><a href="https://github.com/HeyChriss/AI-Outfit-Creator"><em>https://github.com/HeyChriss/AI-Outfit-Creator</em></a></p><p>One summer morning, I woke up, took a shower, and was ready to pick up my outfit. I realized I did not have a lot of ideas for my outfit that day. Living in Idaho makes you get used to cold days so all of my outfit ideas were for cold days, however that summer morning I did not plan and the first thing I thought about was “I wish there could be an app that could help me pick my outfits” and that is when I had the idea of building an app that could help me choose an outfit for the day with my clothes.</p><p>I shared that idea with one of my friends, and we started building it together.</p><h3>App requirements:</h3><p>I wanted to build a personal app. Despite the fact that there are other apps like this already in the market, the thought of creating an app like this made me excited because of the things I was going to learn. I wanted an app with two machine learning models. One for clothes classification and the other for fashion and clothing recommendation. We also wanted to build a robust app with a login page and information, and that would include an authentication database. Also, the app wanted to look somewhat good, and as a software engineer, I thought maybe creating a Streamlit app? Heck no, I could not do that, so we decided to create a UI using Vite and React and then use Python as a backend. There are other things we wanted to work on, such as creating an app for phones and eventually grabbing pictures from the gallery, but of course, we wanted to do that after having a working prototype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iEgkbOfy5Q8ryrKEMgQjuQ.png" /><figcaption>This is the loggo of the app we wanted to build!</figcaption></figure><h3>Thought Process and design:</h3><p>I just graduated from college, so it is hard to know how to start a project like that. I have worked on many personal projects and learned a lot from them, but it is always hard to know where to start. I graduated with a software design certificate, so this should be easy, just follow the Top Down development Design and TDD, and you’ll be set, but I also thought of doing Button up and doing it in sprints! Ahhh!! There was just so much to think about, but that is the beauty of Software Engineering! You always learn something new, and you learn how to solve problems!</p><p>I decided to do the top-down development and TDD (Test Driven Development). We had a design with my friend, and we divided the components. My friend was going to be working on spinning up the database and UI, while I was going to work the the ML models and UI. We both were going to work in the UI and the backend, but doing different components, so in this post I’ll be talking about the ML components and some of the UI components!</p><h3>Clothes Classification Model</h3><p>I started working on the first model! I started looking at examples on GitHub and saw many different options. Transfer Learning seemed the most appropriate for this project because it would give me the feeling of fine-tuning a model without worrying about starting a new model from scratch, and finish my free weekly 30 hours of GPU in Kaggle. Talking to some experts in the industry on LinkedIn, some of them recommended I find a good dataset in Kaggle, try Alexnet ( if you want to learn more about it, I did a post about it, and this is the <a href="https://medium.com/@christianmijangos.cm/alexnet-architecture-73f5781d5891"><strong>link</strong></a>) as an architecture, and test it.</p><p>I did my research and I found <a href="https://www.kaggle.com/datasets/agrigorev/clothing-dataset-full"><strong>this dataset</strong></a> on Kaggle that I thought was appropriate for the project, and I did some research about Alexnet. At the beginning, I was having a hard time understanding the dataset, but with some data exploration, I was able to understand more about what I was dealing with, and then I built the AlexNet architecture. Sad news, it was taking so long to train! I was running out of GPU in Google Colab and the 30 hours of Kaggle were not enough. I decided to keep researching and see if there was another option that was not computationally expensive or even try another dataset. I found the<strong> Xception Neural Network</strong>, and I created a post <a href="https://medium.com/@christianmijangos.cm/xception-cnn-architecture-b81366b2262d"><strong>about it here</strong></a><strong> </strong>about what it is, how you can use it, and what it is used best for. I used the same dataset and everything, and it seemed to work well in the tests I was doing.</p><p>You can find my notebook on Kaggle<strong> </strong><a href="https://www.kaggle.com/code/chrismijangos/clothes-classification-v2"><strong>here</strong>.</a> I also added the Xceptions weights and you can find it <a href="https://www.kaggle.com/datasets/chrismijangos/xception-weights"><strong>here</strong></a>. One of the downsides of this is that my model was 1.4 GB. Only the weights! That was a lot, and that could bring some problems. One of the problems with the size of those weights is how the app is going to work. If the website is client-side, this would limit our memory to 100mb. Of course, client-side is good because it is faster, loads the model in the browser, and you are not making an api call to the server all the time, but I could not do that with the model I currently had. I had three options: either look for another model, go server-side, or quantize the model and make it smaller. All of those options were fun. Remember, I’m doing this for the sake of learning new things, so I decided to go server-side for this one and try quantization to see if there is something I could learn to decrease the size of this model.</p><p>I modified my model a couple of days later to see if there was something I could do to the layers so it was smaller. I found out that the first time I did the layers, I was using more layers, and I found what was one of the problems. I did three models. One was from scratch, one was transfer learning, and the other was data augmentation. This is how my model looked initially:</p><pre># create scratch model<br>model = Sequential([    Conv2D(32, (3,3), activation=&#39;relu&#39;, input_shape= (IMAGE_SIZE, IMAGE_SIZE, 3)),<br>                        MaxPooling2D(2, 2),<br>                        Conv2D(64, (3,3), activation=&#39;relu&#39;),<br>                        MaxPooling2D(2,2),<br>                        Conv2D(128, (3,3), activation=&#39;relu&#39;),<br>                        MaxPooling2D(2,2),<br><br>                        Flatten(),<br>                        Dense(128, activation=&#39;relu&#39;),<br>                        Dense(19, activation=&#39;softmax&#39;)  ])<br><br># Compile model <br>model.compile(optimizer=&#39;adamax&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.summary()<br><br># accuracy: 0.7235 - loss: 0.9505 - val_accuracy: 0.4835 - val_loss: 1.7948 by th epoch 5</pre><pre>base_model = Xception(<br>    weights=None,<br>    include_top=False,<br>    input_shape= (IMAGE_SIZE, IMAGE_SIZE, 3)<br>)<br><br>weights_path = MYWEIGHTS<br><br>base_model.trainable = False<br>inputs = Input(shape= (IMAGE_SIZE, IMAGE_SIZE, 3))<br>base = base_model(inputs, training=False)<br><br># Flatten the output layer to 1 dimension<br>x = Flatten()(base)<br><br># Add a fully connected layer with 1,024 hidden units and ReLU activation<br>x = Dense(1024, activation=&#39;relu&#39;)(x)        <br><br># Add a final sigmoid layer for classification<br>x = Dense(19, activation=&#39;sigmoid&#39;)(x)           <br><br># Append the dense network to the base model<br>model = Model(inputs, x) <br><br>base_model.load_weights(weights_path)<br><br># Print the model summary. See your dense network connected at the end.<br>model.summary()<br><br># accuracy: 0.9509 - loss: 0.1015 - val_accuracy: 0.7037 - val_loss: 1.4056 By Epoch 5</pre><p>And this is the data augmentation I used for the third model</p><pre>aug_train_datagen = ImageDataGenerator(rescale=1./255,<br>                                    rotation_range=20,<br>                                    width_shift_range=0.1,<br>                                    height_shift_range=0.1,<br>                                    shear_range=0.1,<br>                                    zoom_range=0.2,<br>                                    horizontal_flip=True,<br>                                    fill_mode=&#39;nearest&#39;)<br><br>train_generator = aug_train_datagen.flow_from_directory(<br>    train_dir,<br>    target_size= (IMAGE_SIZE, IMAGE_SIZE),<br>    batch_size=32,<br>    class_mode=&#39;categorical&#39;)<br><br># accuracy: 0.5580 - loss: 2.8830 - val_accuracy: 0.6708 - val_loss: 2.2522  by 5th epoch</pre><p>My model was so big because of the x = Flatten()(base) and the dense layer of 1024. This was creating an Input size to the Dense layer: 7 × 7 × 2048 = 100,352 features. Dense layer: 100,352 → 1024 units and Parameters in this layer alone: ~103 million parameters! It was too big, so I changed it to:</p><pre># Flatten the output layer to 1 dimension<br>x = Flatten()(base)<br><br>x = Dense(256, activation=&#39;relu&#39;)(x)<br>x = Dropout(0.1)(x)<br><br>x = Dense(64, activation=&#39;relu&#39;)(x)<br>x = Dropout(0.1)(x)   <br><br># Final classification layer (use softmax for multiclass classification)<br>x = Dense(19, activation=&#39;softmax&#39;)(x)  </pre><p>So far, the model works correctly, and I think there’s a lot of improvement in the model. When I was testing it, it would categorize correctly, but it would have a hard time predicting a blouse against a shirt. I wish there could be a dataset that would have labels like color, brand, and size, and that the model would be able to predict all of those labels. I’m pretty sure there’s a dataset like that, but I really haven’t looked enough to find one, so if you know of a dataset like that, please let me know. I’m currently still working on the model and trying to integrate it into the UI. The good thing, it works and it’s enough to start implementing it in the UI. The model can recognize what it was trained for really well; however, when there is something that the dataset did not contain, it would label it as “other”, which is good (because I am using this model to just determine clothes classification, the user is still going to be able to change and add more information about the clothes) it will determine that is something new and then eventually when we get more data from the user, I can train a new model and make it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*hOOY34dtHZbVZ84e-4GM0w.png" /><figcaption>This is the prediction when we send a picture of cargo pants</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*bbVTWlnscJglzf9aZohu9w.png" /><figcaption>This is the prediction when we send a picture of normal pants</figcaption></figure><h3>Conclusion</h3><p>Planning design is important and key in creating new projects. It’s essential to have a vision of how your project is going to look in the future. I have learned that software design is more important than we think. At the beginning, I did not see how important it was, but it wasn’t until I started building “big projects” that I realized the importance of designing before even coding! I don’t know about you guys, but in college, professors are great and amazing, but they teach you the basics, and they teach you how to teach yourself! I feel that has been a blessing for me because now that I’m getting into the industry, I can see that the skill of “learn as you go” is definitely something that a lot of jobs are asking for!</p><p>Thanks for reading the first part of my journey in building this project! I love to learn, and blogging my journey has helped me to learn even more and share my experiences! If you want to collaborate with me or if you have any suggestions, please visit my website and feel free to reach out to me on LinkedIn or via email! This is my website <a href="https://heychriss.com/">https://heychriss.com/</a>. I will be posting the other part where I talk about what I am currently doing for the fashion model!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dd1bec7c278" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xception CNN Architecture]]></title>
            <link>https://medium.com/@christianmijangos.cm/xception-cnn-architecture-b81366b2262d?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81366b2262d</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 02:23:03 GMT</pubDate>
            <atom:updated>2025-06-25T02:23:03.503Z</atom:updated>
            <content:encoded><![CDATA[<p>While working on a project, I decided to do research on the best CNN architectures, and I found Xception right away! While there are many pretrained models out there, this one caught my eye, and I decided to give it a try.</p><h3>What is Xception?</h3><p>Xception, an abbreviation for “<strong><em>Extreme Inception</em></strong>”. It represents a milestone in convolutional neural network (CNN) design. Conceived by François Chollet, the creator of the Keras deep learning library, the model was introduced in 2016 while François was working at Google. This architecture demonstrates that <strong>cross-channel correlations and spatial correlations can be entirely decoupled</strong>, leading to more efficient computation without sacrificing performance. Don’t worry, I will be explaining what that means in a little bit. The model was published in CVPR 2017 after initial arXiv release in October 2016. The development started because of a theory, while Inception modules used parallel convolution paths to capture different scales of features, Xception proposed that this approach could be taken to its logical extreme, and François wanted to map cross-channel correlation and spatial correlation could be completely separated, therefore the architecture’s core innovation of depthwise separable convolutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObqmP7NYtRncSiiiDpoDWA.png" /><figcaption>Simple representation of the Xception model</figcaption></figure><h3>Why is it special?</h3><p>As I mentioned before, this architecture demonstrates that <strong>cross-channel correlations and spatial correlations can be entirely decoupled</strong>, leading to more efficient computation without sacrificing performance.</p><p>I am going to break it down and go back to traditional CNN approaches. I will be a little techy explaining this, but hopefully I can explain it in the best way. In regular CNNs, when you apply a convolution filter, you are doing two things at once. You are doing spatial correlation, which is looking at the pixels like edges, textures, and others. And you are doing cross-channel correlation, which is combining color channels. For example, a 3×3×3 filter on an RGB image simultaneously:</p><ul><li>Analyzes a 3×3 spatial neighborhood (spatial correlation)</li><li>Combines red, green, and blue channels (cross-channel correlation)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*gXVOff5NO60wDVcLZj4eCg.png" /></figure><p>The assumption was: “We need to do both operations together to learn the best features.” But Xception would do this completely separately. Xception would do Depthwise convolution, and it would do it in two steps.</p><p>Depthwise Convolution (Spatial part):</p><ul><li>Apply 3×3 filters, but one filter per channel</li><li>Red channel gets its own 3×3 filter, green gets its own, and blue gets its own, so this would capture the spatial pattern with each channel by itself</li><li>No mixing between channels yet</li></ul><p>Pointwise Convolution (Cross-Channel part):</p><ul><li>Apply 1×1 filters across all channels at each pixel location</li><li>This mixes information between channels but ignores spatial neighbors</li><li>Purely about combining channel information</li></ul><p>The whole purpose os Xception was to separate these steps and get <strong>better</strong> results with <strong>less</strong> computation.</p><p>Xception excels in scenarios requiring efficient parameter utilization and strong transfer learning capabilities. Medical imaging applications represent perhaps the most successful deployment domain, with studies achieving over 99% accuracy for COVID-19 detection from chest X-rays and breast cancer classification. This means that Xception is so good at feature extraction!</p><h3>Xception’s architecture</h3><p>The architecture is a little crazy. Xception’s architecture consists of <strong>71 layers organized into 36 convolutional layers, and </strong>it is divided into three flows<strong>.</strong></p><p>The <strong>Entry Flow</strong> comprises four modules responsible for initial feature extraction and progressive downsampling. It starts with standard convolutions (32 and 64 filters) and reduces spatial dimension from 299×299 to 19×19 while expanding channels from 3 to 728.</p><p>The <strong>Middle Flow</strong> contains eight identical modules that maintain spatial resolution at 19×19 while performing deep feature refinement at constant 19×19×728. This design helps with developing feature extractions without spatial reductions.</p><p>The <strong>Exit Flow</strong> handles final feature processing and classification through two modules. The first reduces spatial dimensions to 10×10 while expanding to 1024 channels, followed by separable convolutions producing 1536 and 2048 channels. This turns into classification at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*mCiUscsie5geBcmt8RN02A.png" /><figcaption>This is a representation of the architecture. (<a href="https://openaccess.thecvf.com/content_cvpr_2017/papers/Chollet_Xception_Deep_Learning_CVPR_2017_paper.pdf">Source</a>)</figcaption></figure><p>Instead of regular convolutions, almost every layer uses:</p><ol><li><strong>Depthwise Conv</strong>: 3×3 filters applied separately to each channel</li><li><strong>Pointwise Conv</strong>: 1×1 filters to mix channel information</li></ol><p>There are Residual Connections Everywhere! That helps with preventing degradation and having and stable training. The combination of <strong>depthwise separable convolutions with residual learning</strong> creates a synergistic effect, where architectural efficiency combines with training stability to achieve superior performance.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*eh7fwaPLaHcvX9sTqtIrtg.png" /><figcaption>Classification performance comparison on ImageNet. (<a href="https://openaccess.thecvf.com/content_cvpr_2017/papers/Chollet_Xception_Deep_Learning_CVPR_2017_paper.pdf">Source</a>)</figcaption></figure><p>The performance of Xception is compared against Inception V3, ResNet-152, and VGG-16 on <strong>ImageNet</strong> and <strong>JFT</strong> datasets.</p><h3>Conclusion</h3><p>Xception is a great model because it shows that <strong>depthwise separable convolutions can serve as a direct replacement for traditional convolutions</strong> without sacrificing performance. Xception gets <strong>higher accuracy</strong> and better metrics. These improvements are achieved <strong>without increasing the number of model parameters</strong>; therefore, it is less computationally expensive, but I think that one potential limitation of Xception is its <strong>slightly slower training speed</strong> compared to other models, likely due to the current implementation of depthwise separable convolutions.</p><h3>References</h3><p>François Chollet (2017). Xception: Deep Learning with Depthwise Separable Convolutions <a href="https://arxiv.org/pdf/1610.02357v3">[Link]</a></p><p>Keras Team (2024). Xception — Keras Applications <a href="https://keras.io/api/applications/xception/">[Link]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81366b2262d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Siamese Neural Networks]]></title>
            <link>https://medium.com/@christianmijangos.cm/siamese-neural-networks-dfb84a4a37b3?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb84a4a37b3</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 05:05:23 GMT</pubDate>
            <atom:updated>2025-06-20T05:09:22.699Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the problems you’ll eventually encounter is that neural networks require time to train, and it can be a hassle to retrain a neural network whenever you make a change. Let’s suppose you are training a model that could pick up and recognize the faces of students in a specific class. Sure, we train the model with all of the students, and that is it. But what about when a student leaves? And when a new student comes in? We might have to delete or train a new model with new pictures so the model can recognize the new students. Imagine we get new students every week? Training the model every week doesn’t sound easy anymore, does it?</p><p>That is when Siamese neural networks come in handy. I’ll be explaining what they are, how they work, and how we can set up one!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btIpsq70jtey04rrIZ7-nw.png" /><figcaption>Simple representation of SNNs</figcaption></figure><h3>What are Siamese neural networks?</h3><p>Siamese neural networks, or SNNs, are a special neural network architecture specialized to learn similarity relationships between two inputs. They are specifically designed with two identical sub-neural networks that share the same parameters and weights. These two subnetworks, or “twin networks” extract features from both inputs. The first input is the anchor image, and the second input is a negative pair or a positive pair. These images are passed into their respective subnetworks and that will result in the output vector for both inputs. These vectors are combined to further get the distance mediate between the two outputs. If the distance is big, you can say that the output it’s going to be negative; therefore, they are not related, otherwise they might be related.</p><p>If you are wondering what are the negative and the positive pair, we’ll talk about it in a little bit. Also, we will be talking about the different types of measures. I know it sounds complicated, but once you understand how they work, believe me, you’ll never forget it.</p><p>Here’s a breakdown of how they work:</p><ol><li>Two inputs are fed into separate but identical networks</li><li>Each network produces a feature vector representation</li><li>A distance function measures how similar the outputs are</li><li>The network learns to minimize distance for similar pairs and maximize it for dissimilar pairs</li></ol><p>Siamese neural networks were first introduced by Jane Bromley, Isabelle Guyon, Yann LeCun, Eduard Säckinger, and Roopak Shah in 1993. They were trying to have a model that would do signature verification tasks. This was presented at a conference in Toronto. The task was simple: they needed a way to automatically verify handwritten signatures by determining if two signatures came from the same person. Neural networks were not that well-suited for tasks like this, so they came up with the idea of building the twin networks.</p><p>Researchers kept using this method to do face verification, Fingerprint recognition, and one-shot learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHAsZdsAwsBiUiKtoA9EDw.png" /></figure><h3>Why are they special?</h3><p>The most powerful aspect is that Siamese networks learn a general similarity function rather than memorizing specific patterns. Instead of needing thousands of examples of every possible class, they learn to measure how “alike” or “different” two inputs are. This means they can compare things they’ve never seen before, as long as they’re from a similar domain.</p><p>Another thing about neural networks is that they can learn from one shot. Traditional neural networks would need to have large datasets to learn and recognize new objects, and SNNs can do this by having just a few examples. They are also computationally efficient because they both share weights; therefore, the model doesn’t have to have different parameters for both subnetworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*jyjBez7bNMBjM7_bpK0ieg.png" /><figcaption>SNNs will look for similarity score and predict if they are from the same class or different class</figcaption></figure><h3>How do they train?</h3><p>Before, I was talking about positive pairs and negative pairs. Siamese networks require a special training approach because they learn similarity rather than classification, unlike traditional neural networks.</p><p><strong>Positive pairs</strong> are when you combine two inputs that should be similar or from the same class. For the student example from before, this could be two pictures of the same person. For other things, it could actually be similar. Examples:</p><ul><li>Two signatures by the same person</li><li>Two images of the same product from different angles</li><li>Two sentences with similar meaning</li><li>Two different pictures that are different, but are related (outfits, patterns, drawings, etc)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkD2_ddN92XZS0h3IewG_w.png" /></figure><p><strong>Negative pairs</strong> are just the opposite of the positive pairs. For the student example, it could be something as different as pictures of the students. Something that is not similar to or a different class. Example:</p><ul><li>A genuine signature and a forged one</li><li>Images of completely different products</li><li>Sentences with opposite meanings</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbcvOZvIBjHtfgKfhTKLDQ.png" /></figure><p>It is important to understand the need for these pairs. Whenever you do your data exploration and you have your own data, you have to have in mind who you are going to manipulate your own data to have these pairs.</p><p>Another important thing about SNNs is the importance of your function loss. Siamese neural networks use specialized loss functions designed to learn similarity relationships.</p><h3>Loss functions in SNN</h3><p>One of the most common ones is <strong>Contrastive Loss</strong>. This is simple: whenever two vectors are similar, this function will minimize the distance and pull them together, and if the vectors are not similar, this function will push them apart to create a bigger margin. The margin prevents the network from struggling to decide what is similar and what is not. This uses the Euclidean distance. I won’t get into the math behind it, but if you want to get more information, you can read here.</p><p>Another popular function loss is <strong>Triplet Loss</strong>. Uses triplets: (anchor, positive, negative) instead of pairs. Ensure the anchor is closer to positive than to negative by at least a margin.</p><p>Those are the two main ones I have found, but of course, there are other ones such as:</p><ul><li><strong>Binary Cross Entropy:</strong> which gives your output as true or false, or 0 versus 1</li><li><strong>Cosine embedding loss:</strong> Based on cosine similarity rather than Euclidean distance</li><li><strong>Center Loss:</strong> Helps learn discriminative features</li><li><strong>Angular loss:</strong> Uses angular distance instead of Euclidean distance</li><li><strong>N-pair loss:</strong> Extends triplet loss to multiple negative examples</li></ul><h3>Implementing Siamese Networks in Keras</h3><p>Here’s a practical example of how to implement a Siamese Network using Keras. This implementation includes both the network architecture and the contrastive loss function:</p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Lambda<br>from tensorflow.keras.optimizers import Adam<br>import numpy as np<br><br>def create_base_network(input_shape):<br>    &quot;&quot;&quot;Create the base network that will be shared between the two inputs&quot;&quot;&quot;<br>    input_layer = Input(shape=input_shape)<br>    <br>    x = Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(input_layer)<br>    x = MaxPooling2D((2, 2))(x)<br>    <br>    x = Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>    x = MaxPooling2D((2, 2))(x)<br>    <br>    x = Conv2D(256, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;)(x)<br>    x = MaxPooling2D((2, 2))(x)<br>    <br>    x = Flatten()(x)<br>    x = Dense(128, activation=&#39;relu&#39;)(x)<br>    x = Dense(64, activation=&#39;relu&#39;)(x)<br>    <br>    return Model(input_layer, x)<br><br>def euclidean_distance(vectors):<br>    &quot;&quot;&quot;Compute the Euclidean distance between two vectors&quot;&quot;&quot;<br>    x, y = vectors<br>    sum_square = tf.reduce_sum(tf.square(x - y), axis=1, keepdims=True)<br>    return tf.sqrt(tf.maximum(sum_square, tf.keras.backend.epsilon()))<br><br>def contrastive_loss(y_true, y_pred, margin=1):<br>    &quot;&quot;&quot;Contrastive loss function&quot;&quot;&quot;<br>    square_pred = tf.square(y_pred)<br>    margin_square = tf.square(tf.maximum(margin - y_pred, 0))<br>    return tf.reduce_mean(y_true * square_pred + (1 - y_true) * margin_square)<br><br>def create_siamese_network(input_shape):<br>    &quot;&quot;&quot;Create the complete Siamese network&quot;&quot;&quot;<br>    base_network = create_base_network(input_shape)<br>    <br>    # Create two inputs<br>    input_a = Input(shape=input_shape)<br>    input_b = Input(shape=input_shape)<br>    <br>    # Get the feature vectors from both inputs<br>    vector_a = base_network(input_a)<br>    vector_b = base_network(input_b)<br>    <br>    # Compute the distance between the vectors<br>    distance = Lambda(euclidean_distance)([vector_a, vector_b])<br>    <br>    # Create the model<br>    model = Model(inputs=[input_a, input_b], outputs=distance)<br>    <br>    return model<br><br>def create_triplet_loss_model(input_shape, embedding_size=64):<br>    &quot;&quot;&quot;Create a Siamese network with triplet loss&quot;&quot;&quot;<br>    base_network = create_base_network(input_shape)<br>    <br>    # Create three inputs for triplet loss<br>    anchor_input = Input(shape=input_shape, name=&#39;anchor_input&#39;)<br>    positive_input = Input(shape=input_shape, name=&#39;positive_input&#39;)<br>    negative_input = Input(shape=input_shape, name=&#39;negative_input&#39;)<br>    <br>    # Get embeddings for all three inputs<br>    anchor_embedding = base_network(anchor_input)<br>    positive_embedding = base_network(positive_input)<br>    negative_embedding = base_network(negative_input)<br>    <br>    # Create the model<br>    model = Model(<br>        inputs=[anchor_input, positive_input, negative_input],<br>        outputs=[anchor_embedding, positive_embedding, negative_embedding]<br>    )<br>    <br>    return model<br><br>def triplet_loss(y_true, y_pred, alpha=0.2):<br>    &quot;&quot;&quot;Triplet loss function&quot;&quot;&quot;<br>    anchor, positive, negative = y_pred[:, 0], y_pred[:, 1], y_pred[:, 2]<br>    <br>    # Calculate distances<br>    pos_dist = tf.reduce_sum(tf.square(anchor - positive), axis=1)<br>    neg_dist = tf.reduce_sum(tf.square(anchor - negative), axis=1)<br>    <br>    # Calculate triplet loss<br>    basic_loss = pos_dist - neg_dist + alpha<br>    loss = tf.maximum(basic_loss, 0.0)<br>    <br>    return tf.reduce_mean(loss)<br><br># Example usage:<br>def train_siamese_network():<br>    # Create the model<br>    input_shape = (64, 64, 3)  # Adjust based on your image size<br>    model = create_siamese_network(input_shape)<br>    <br>    # Compile with custom loss<br>    model.compile(<br>        optimizer=Adam(learning_rate=0.0001),<br>        loss=contrastive_loss,<br>        metrics=[&#39;accuracy&#39;]<br>    )<br>    <br>    # Example training data preparation<br>    def prepare_pairs(images, labels):<br>        &quot;&quot;&quot;Prepare positive and negative pairs for training&quot;&quot;&quot;<br>        num_classes = len(np.unique(labels))<br>        digit_indices = [np.where(labels == i)[0] for i in range(num_classes)]<br>        <br>        pairs = []<br>        pair_labels = []<br>        <br>        # Positive pairs<br>        for d in range(num_classes):<br>            for i in range(len(digit_indices[d])):<br>                for j in range(i + 1, min(i + 2, len(digit_indices[d]))):<br>                    pairs += [[images[digit_indices[d][i]], images[digit_indices[d][j]]]]<br>                    pair_labels += [1]<br>        <br>        # Negative pairs<br>        for d in range(num_classes):<br>            for i in range(len(digit_indices[d])):<br>                for d2 in range(d + 1, num_classes):<br>                    for j in range(len(digit_indices[d2])):<br>                        pairs += [[images[digit_indices[d][i]], images[digit_indices[d2][j]]]]<br>                        pair_labels += [0]<br>        <br>        return np.array(pairs), np.array(pair_labels)<br>    <br>    return model</pre><p>This implementation includes:</p><ul><li>A base network that extracts features from input images</li><li>A Siamese architecture with two identical subnetworks</li><li>Euclidean distance computation between feature vectors</li><li>Contrastive loss function for training</li><li>Triplet loss implementation for more advanced training</li><li>Data preparation functions for creating positive and negative pairs</li></ul><p>To use this model effectively, you would need to:</p><ol><li>Prepare your dataset with proper positive and negative pairs</li><li>Choose the appropriate loss function based on your task</li><li>Adjust the network architecture based on your input data</li><li>Fine-tune hyperparameters like margin and learning rate</li></ol><h3>Advantages and Limitations</h3><p><strong>Advantages:</strong></p><ul><li>Can learn from a few examples (one-shot learning)</li><li>Computationally efficient due to shared weights</li><li>Generalizes well to unseen classes</li><li>No need to retrain for new classes</li><li>Learns meaningful similarity metrics</li></ul><p><strong>Limitations:</strong></p><ul><li>Requires careful pair selection during training</li><li>Can be sensitive to the choice of loss function</li><li>Training can be unstable with certain architectures</li><li>Requires domain-specific data preparation</li><li>May not perform well on very complex similarity tasks</li></ul><h3>References</h3><p>Koch, G., Zemel, R., and Salakhutdinov, R. (2015). Siamese Neural Networks for One-shot Image Recognition <a href="https://www.cs.cmu.edu/~rsalakhu/papers/oneshot1.pdf">[Link]</a></p><p>Schroff, F., Kalenichenko, D., and Philbin, J. (2015). FaceNet: A Unified Embedding for Face Recognition and Clustering <a href="https://arxiv.org/abs/1503.03832">[Link]</a></p><p>Dong-Keon Kim (2025). Siamese Nets: A Breakthrough in One-shot Image Recognition <a href="https://medium.com/@kdk199604/siamese-nets-a-breakthrough-in-one-shot-image-recognition-53aa4a4fa5db">[Link]</a></p><p>Christian Mijangos (2025). Siamese Neural Networks <a href="https://heychriss.com/siamese/">[Link]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb84a4a37b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AlexNet Architecture]]></title>
            <link>https://medium.com/@christianmijangos.cm/alexnet-architecture-73f5781d5891?source=rss-8e982b0c1f80------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f5781d5891</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[alexnet]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Christian Mijangos]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 05:34:37 GMT</pubDate>
            <atom:updated>2025-06-16T05:59:33.256Z</atom:updated>
            <content:encoded><![CDATA[<p>Finding good neural network architectures is definitely hard, you have to keep in mind how clean your data is, the amount of data you’ll be training, and, of course, the layers and architecture you’ll be using for your model.</p><p>During one of my personal projects, I researched AlexNet. AlexNet by Alex Krizhevsky is one of the most famous neural network architectures. I heard about it the first time in one of my classes, but I really did not pay attention to it until a few weeks ago when I was recommended to use it for one of my personal projects.</p><h3>What is AlexNet?</h3><p>AlexNet is a convolutional neural network made by Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton, who served as Krizhevsky’s PhD advisor in 2012. AlexNet not only caused a revolution in deep learning and computer vision, but also showed the importance of GPUs and data augmentation.</p><p>They achieved:</p><ul><li>37.5% top-1 error and 17.0% top-5 error on ImageNet LSVRC-2010</li><li>15.3% top-5 error on ILSVRC-2012 (vs. 26.2% for second place)</li></ul><p>This was insane! Especially back in 2012, when image classification and deep learning were “brand new”</p><h3>AlexNet Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/0*ew8InSaP7W046tKU.png" /></figure><p>AlexNet was much larger than previous CNNs used for computer vision tasks (e.g., Yann LeCun’s LeNet paper in 1998). This was the first architecture that used a GPU to boost the training performance, and it took approximately 5 to 6 days with two GTX 580 3GB GPUs for training. AlexNet consists of 5 convolution layers, 3 max-pooling layers, 2 Normalized layers, 2 fully connected layers, and 1 SoftMax layer.</p><p>Here’s a breakdown of the layers:</p><ul><li>8 learned layers total: 5 convolutional + 3 fully-connected</li><li>60 million parameters and 650,000 neurons</li><li>Input: 224×224×3 RGB images</li><li>Output: 1000-class softmax for ImageNet categories</li></ul><p>Layer-by-layer breakdown:</p><ol><li>Conv1: 96 kernels (11×11×3), stride 4</li><li>Conv2: 256 kernels (5×5×48)</li><li>Conv3: 384 kernels (3×3×256)</li><li>Conv4: 384 kernels (3×3×192)</li><li>Conv5: 256 kernels (3×3×192)</li><li>FC6: 4096 neurons</li><li>FC7: 4096 neurons</li><li>FC8: 1000 neurons (output)</li></ol><p>All of the layers contain the ReLU activation function and the softmax activation function at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R3b-fy9ceH2Tp_un.png" /></figure><p>The architecture is pretty simple, but it is a good example of how to use a CNN for image classification.</p><h3>Overfitting techniques in AlexNet</h3><p>Overfitting is super common in neural networks. Neural networks are so good at memorizing things that when you are training them, your metrics are perfect, but when testing new data is so poorly done. I always like giving the example of myself when I was studying for tests in high school. I would do so great in the prep tests because I knew all of the answers from the tests, but when I had the final test, I struggled because I did not know the new questions I was going to face. I was overfitting! Neural networks face the same challenges; they are so good at memorizing things so you have to make the model understand that memorizing is not good.</p><p>There are many techniques to avoid overfitting, but AlexNet used the following techniques:</p><p><strong>Local response normalization:</strong> Local response normalization is a technique that helps to avoid overfitting. It is a technique that helps to normalize the response of the neurons. Honestly, this was the first time I heard about it, and I had to do some research to understand it. Growing up, I was always the loudest in the class. I was the guy who people listened to because I was the loudest, but I was never the smartest. My teacher though, he was the smartest. LRNs are like fair teachers who would put control in a class where students are loud. Teachers would tell the students to be quiet so they can hear every student equally.</p><p>It is the same with neurons; neurons tend to be loud and find patterns fast, but sometimes it is the wrong pattern; therefore, sometimes neurons have to be shut down, and this is what LRM’s do. LRN implements a form of lateral inhibition, where highly active neurons suppress the activity of nearby neurons. This creates competition between neuron outputs computed using different feature maps (kernels) at the same spatial position. This was used in AlexNet in the first two layers because it would stop a few very active feature maps from dominating and focus more in the general picture to avoid overfitting.</p><p>Nowadays, LRNs are not as popular as before because Batch Normalization in 2015 proved much more effective; however, LRN was crucial for AlexNet’s success in 2012, when batch normalization didn’t exist and networks were much harder to train effectively.</p><p><strong>Max-pooling:</strong> Max-pooling is a technique that reduces the size of the input by taking the maximum value of a region of the input. This is good because it reduces the number of parameters, and it also helps to avoid overfitting. They used a 3x3 window with a stride of 2. This means that the type of pooling they used was an overlapping pooling, which I am not going to get into the details of, but it is simply taking the maximum value of a 3x3 window and moving it by 2 pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CFgvD8HZCnYpg_vp.png" /></figure><p><strong>Data augmentation:</strong> Data augmentation is simple. It’s adding different variations of the same image. This is good because we are forcing the model not to memorize. Another good thing about data augmentation is that it is free data! Yes! If you do not have a lot of pictures of what you are training, you can make different copies of it, and that will add more to your data!</p><p>The AlexNet team used <strong>mirroring,</strong> which is simply taking the image and flipping it by the vertical axis. This is good because it helps the model not to memorize the image, and it also helps to avoid overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qdXnYvajroB1U7BG.png" /></figure><p>and <strong>Random crops,</strong> which creates different images of an image with different sizes of input. The AlexNet team extracted random crops of size 227×227 from inside the 256×256 image boundary to use as the network’s inputs. They increased the size of the data by a factor of 2048 using this method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BX2DhnJTWx27hiQD.png" /></figure><p><strong>Dropout:</strong> Another method they used was dropout. I won’t get into the details of dropout in this post, but it is simply dropping random neurons in the layers so they stop communicating in propagation. This mitigates overfitting because it forces the model to “drop” neurons and make other neurons learn the patterns instead of memorizing them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bHEFM73QzfRdqm8B.png" /></figure><h3>Historical Significance</h3><p>This paper essentially launched the deep learning revolution in computer vision by:</p><ol><li>Demonstrating that deep CNNs could dramatically outperform traditional computer vision methods</li><li>Showing the importance of GPU computing for deep learning</li><li>Introducing techniques (ReLU, dropout, data augmentation) that became standard</li><li>Proving that large-scale datasets + deep networks = breakthrough performance</li></ol><p>The success of AlexNet sparked the rapid adoption of deep learning across computer vision and beyond, making it one of the most influential papers in modern AI history.</p><p>AlexNet was a game-changer back in 2012. It is used by many people nowadays, and it was a big step into the computer vision and deep learning community.</p><h3>Implementing AlexNet in Keras</h3><p>Here’s a practical example of how to implement AlexNet using Keras. This implementation follows the original architecture while using modern Keras practices:</p><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout<br>from tensorflow.keras.optimizers import SGD<br><br>def create_alexnet(input_shape=(224, 224, 3), num_classes=1000):<br>    model = Sequential([<br>        # Layer 1<br>        Conv2D(96, (11, 11), strides=4, padding=&#39;valid&#39;, activation=&#39;relu&#39;, input_shape=input_shape),<br>        MaxPooling2D(pool_size=(3, 3), strides=2),<br>        <br>        # Layer 2<br>        Conv2D(256, (5, 5), padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>        MaxPooling2D(pool_size=(3, 3), strides=2),<br>        <br>        # Layer 3<br>        Conv2D(384, (3, 3), padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>        <br>        # Layer 4<br>        Conv2D(384, (3, 3), padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>        <br>        # Layer 5<br>        Conv2D(256, (3, 3), padding=&#39;same&#39;, activation=&#39;relu&#39;),<br>        MaxPooling2D(pool_size=(3, 3), strides=2),<br>        <br>        # Flatten and Dense layers<br>        Flatten(),<br>        Dense(4096, activation=&#39;relu&#39;),<br>        Dropout(0.5),<br>        Dense(4096, activation=&#39;relu&#39;),<br>        Dropout(0.5),<br>        Dense(num_classes, activation=&#39;softmax&#39;)<br>    ])<br>    <br>    # Compile the model<br>    model.compile(<br>        optimizer=SGD(learning_rate=0.01, momentum=0.9),<br>        loss=&#39;categorical_crossentropy&#39;,<br>        metrics=[&#39;accuracy&#39;]<br>    )<br>    <br>    return model<br><br># Example usage:<br>def train_alexnet():<br>    # Create the model<br>    model = create_alexnet(num_classes=1000)<br>    <br>    # Train the model<br>    history = model.fit(<br>        train_generator,<br>        epochs=90,<br>        validation_data=validation_generator,<br>        callbacks=[<br>            tf.keras.callbacks.EarlyStopping(<br>                monitor=&#39;val_loss&#39;,<br>                patience=5,<br>                restore_best_weights=True<br>            )<br>        ]<br>    )<br>    <br>    return model, history</pre><p>This implementation includes:</p><ul><li>The original AlexNet architecture with 5 convolutional layers and 3 fully connected layers</li><li>ReLU activation functions after each convolutional and fully connected layer</li><li>Max pooling layers for dimensionality reduction</li><li>Dropout layers in the classifier to prevent overfitting</li><li>A basic training setup with early stopping</li></ul><p>To use this model, you would need to:</p><ol><li>Prepare your dataset (images should be 224×224×3)</li><li>Create a data generator for training and validation</li><li>Initialize the model with the appropriate number of classes</li><li>Train the model using the fit method</li></ol><p>Note that this is a basic implementation. In practice, you might want to add:</p><ul><li>Data augmentation using ImageDataGenerator</li><li>Learning rate scheduling</li><li>Model checkpointing</li><li>TensorBoard logging</li><li>Mixed precision training for better performance</li></ul><p>I posted this in my website if you want to read more about these topics and if you are interested in projects I am working on <a href="https://heychriss.com/alexnet/">https://heychriss.com/alexnet/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f5781d5891" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>