<?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 Andy Wang on Medium]]></title>
        <description><![CDATA[Stories by Andy Wang on Medium]]></description>
        <link>https://medium.com/@andy-wang?source=rss-3de8e48ee2c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2r3NeX2xI0deFfBr0LHR-Q.jpeg</url>
            <title>Stories by Andy Wang on Medium</title>
            <link>https://medium.com/@andy-wang?source=rss-3de8e48ee2c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:59:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andy-wang/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 Machine Unlearning and Why Does it Matter?]]></title>
            <link>https://andy-wang.medium.com/what-is-machine-unlearning-and-why-does-it-matter-10eb328913bc?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/10eb328913bc</guid>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-unlearning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 05:56:01 GMT</pubDate>
            <atom:updated>2025-01-05T05:56:01.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uI6gzgXtKGW_k_Gx" /><figcaption>Photo by <a href="https://unsplash.com/@wrzepka?utm_source=medium&amp;utm_medium=referral">Wojciech Rzepka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Coined as “machine unlearning,” this concept represents the converse of machine learning — it serves to unlearn or forget. These algorithms, applied to previously trained models, force them to expunge specific portions of the training dataset. The beginnings of machine unlearning lies in the response to the “<a href="https://gdpr-info.eu/issues/right-to-be-forgotten/">Right to be Forgotten</a>” legislation, a provision of the European Union’s General Data Protection Regulation (GDPR).</p><p>This regulation primarily focuses on the internet, specifically dealing with any links to or replicas of personal data. Technically speaking, the removal of website links or references to an individual is relatively straightforward. However, achieving this within machine learning models is often regarded as almost an insurmountable task.</p><p>Machine learning has infiltrated virtually all areas of modern software development and the internet. Particularly in recent years, models like Flux and GPT-4 have amplified the discussions around AI’s privacy and security concerns. There have been cases where artists’ and writers’ works were used in model training without consent — essentially “stealing” their work. Large Language Models (LLMs) may contain substantial bias or leak sensitive information, potentially leading to severe consequences.</p><p>Efforts to impede certain types of information in production models have been made, but they seem to falter under the weight of numerous ChatGPT jailbreaks, despite OpenAI’s consistent model enhancements.</p><h3>Challenges and Limitations</h3><p>Despite its promise, machine unlearning remains a nascent and unrefined subfield of machine learning. The apparent solution — removing sensitive data points and retraining the model — seems straightforward, but is not practical. The retraining of deep learning models is typically an expensive and time-consuming process, with the training of GPT-4 alone costing over $100 million. Moreover, removing specific data points could adversely impact the model’s performance.</p><p>Despite potential methods to excise certain “knowledge” fragments from machine learning models, numerous obstacles persist:</p><p>1. There is no universally accepted gauge to determine the effectiveness of machine unlearning. For larger, more complex deep learning models, ensuring complete data point forgetting is almost impossible.<br>2. Training in most models is interdependent. Consequently, all subsequent updates and predictions depend, to some extent, on previous updates.<br>3. Larger deep learning models are effectively “black boxes” to humans. Quantifying the exact influence of data points on the model, and how their removal changes the model’s overall operation, is challenging.</p><p>Despite these hurdles, a plethora of algorithms capable of machine unlearning for various models exist.</p><h3>Methods and Techniques</h3><p>Existing algorithms typically leverage reverse-engineered, traditional machine learning methodologies. These are generally classified into two main categories: exact unlearning methods and approximate unlearning methods.</p><p>Exact unlearning methods concentrate on precisely eliminating the impact of individual data points on the model. Techniques such as Reverse Nearest Neighbors (RNN), which find and adjust the model based on the nearest neighbors of the data points set for removal, and K-Nearest Neighbors (KNN), which remove data points based on their closeness to the nearest neighbors, provide an intricate strategy for effective data point exclusion.</p><p>In contrast, approximate unlearning methods incorporate various data sources for efficient data elimination. For example, the Local Outlier Factor (LOF) identifies and purges outliers in the dataset to boost the model’s performance. In a similar vein, Isolation Forest (IF) constructs random forests and determines the anomaly scores of data points, isolating and discarding those with elevated scores. These methods present a more efficient alternative to exact unlearning by utilizing additional data to be expunged or retained after removal.</p><p>Exploring the concept of “knowledge unlearning” in large language models (LLMs), a fascinating approach was introduced in the <a href="https://arxiv.org/abs/2210.01504">paper</a> titled “Knowledge Unlearning for Mitigating Privacy Risks in Language Models” The authors developed a methodology for training LLMs to forget, by optimizing the negative log-likelihood objective function. The authors demonstrated the efficiency of this straightforward unlearning technique in smaller versions of the GPT model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwKFFKoNzoD_EQt-jHrcNg.png" /><figcaption>Proposed unlearning method from “Knowledge Unlearning for Mitigating Privacy Risks in Language Models”. Diagram from paper.</figcaption></figure><h3>Outlook</h3><p>With the recent buzz surrounding LLMs and numerous large tech companies venturing into creating their own, ensuring personal information privacy in the digital world is of paramount importance. It might be challenging and unnecessary to filter out every piece of personal information from LLM training data. However, it is undoubtedly feasible to “unlearn” this information without sacrificing performance.</p><p>The outlook might not be as straightforward as merely reversing these LLMs’ objective functions. Recent research on the inverse <a href="https://arxiv.org/abs/2306.09479">scaling law</a> of LLMs revealed that bigger models aren’t always better. Indeed, these larger models are more susceptible to generating “memorized” responses that were enforced during training, however they are often incorrect or illogical. Furthermore, the paper discovered that larger models are prone to “distractor tasks” whereas a brief mention of another topic in the context diverges the model’s response to follow the logic of the insignificant part.</p><p>The good news though, we see that on the other frontier of generative machine learning, diffusion models are already attempting to respect artists’ works with <a href="https://stability.ai/news/stable-diffusion-3">Stable Diffusion 3.0</a> allowing artists to remove their artwork in the training data.</p><p>Further study and development of machine unlearning could lead to the creation of more refined models that respect individual privacy rights while maintaining their utility. It may also give rise to novel applications and innovations within the machine learning field, opening up unexplored areas of research and development. However, the challenges cannot be ignored, and addressing them will be a critical part of the development of effective and efficient machine unlearning algorithms.</p><p>With all these in mind, machine unlearning stands at a crossroads of great potential and significant challenges. It’s an exciting space to watch as the industry continues to evolve and adapt to new demands and expectations. As the development of generative models accelerate, machine unlearning receives very little attention yet should be regarded as importantly as training those generative models themselves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10eb328913bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flux.1: The New Stable Diffusion Killer? Complete Guide to Running it Locally]]></title>
            <link>https://andy-wang.medium.com/flux-1-the-new-stable-diffusion-killer-complete-guide-to-running-it-locally-aece1c453691?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/aece1c453691</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[flux]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 00:37:59 GMT</pubDate>
            <atom:updated>2024-11-11T00:37:59.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wkai0s_07MMxsyHB" /><figcaption>Photo by <a href="https://unsplash.com/@nasimdadfar?utm_source=medium&amp;utm_medium=referral">nasim dadfar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Stable Diffusion has been the cornerstone of open-source diffusion models since the day it was released. Its incredible performance coupled with the cheap resources required to run locally has inspired thousands of fine-tunes of the model to specialize in generating anything you can imagine. But recently, a new model has risen to the public’s attention, looking to dethrone the king of open source diffusion models.</p><p>Flux.1 was released on August 1st, 2024 from <a href="https://blackforestlabs.ai/">Black Forest Labs</a> as the diffusion model behind Elon Musk’s Grok’s image generator. The model was trained with limited safeguards in mind, allowing users to generate almost anything that comes to their mind. Black Forest Labs has $31 million in seed funding with their co-founders having worked for Stability.AI to develop the Stable Diffusion model.</p><p>The research lab has big plans for the future with their <a href="https://blackforestlabs.ai/up-next/">what’s next</a> page simply stating “State-of-the-Art Text to Video for all”, clearly demonstrating their commitment to the idea of open source models.</p><h3>The Flux Model Family</h3><p>The Flux.1 model has three variants with varying abilities: the Flux 1 Schnell, Flux 1 Dev, and Flux 1 Pro. All models have 12 billion parameters. For reference, the previous state-of-the-art open source diffusion model, SDXL, has only 3.5 billion parameters.</p><p>The Flux 1 Schnell model produces the lowest image quality among the Flux family but is optimized for speed and efficiency. Released under the Apache 2.0 License, it can be used for personal, scientific, and commercial purposes. Flux 1 Schnell was trained using latent adversarial diffusion distillation, allowing it to generate images in a fraction of the time compared to Flux 1 Dev.</p><p>The Flux 1 Dev model produces higher quality and more accurate images compared to Schnell, but comes under a more restrictive license that prohibits commercial use.</p><p>The Flux 1 Pro model is the best of the three, offering superior visual quality, prompt adherence, and output diversity. However, it’s not open source and is only accessible through Black Forest Lab’s API.</p><h3>How to Run Flux Locally</h3><p>The best way to run both Flux Dev and Schnell locally is through ComfyUI. ComfyUI offers a balance between ease of use and versatility for those who want to customize models and workflows specific to their needs. While there are similar platforms like automatic1111 or Forge, this article focuses on running Flux with ComfyUI.</p><p>Running Flux on ComfyUI is straightforward: follow their installation <a href="https://github.com/comfyanonymous/ComfyUI">instructions</a> and the steps detailed in their <a href="https://comfyanonymous.github.io/ComfyUI_examples/flux/">Flux Example</a> page. You’ll need to download a few files, place them in their respective folders, start the server with python main.py, then drag the provided example image into the workflow space.</p><p>The original model requires a GPU with more than 32 GB of VRAM to run smoothly, whether using an Apple Silicon machine or an NVIDIA graphics card. An alternative is the fp8 version, which halves the memory requirements.</p><p>However, even the fp8 version needs more than 16GB of VRAM, which isn’t feasible for many users. Additionally, due to lack of support on Apple Silicon machines, the fp8 version <a href="https://huggingface.co/black-forest-labs/FLUX.1-schnell/discussions/13#:~:text=MacOS%20can&#39;t%20run%20FLUX,bf16%20and%20using%20pyTorch%202.3.">cannot</a> run on GPU, significantly slowing generation times.</p><p>A better solution is the GGUF quantized version of Flux, with the smallest quantization being just 4 gigabytes. GGUF is a binary file format designed for fast loading and saving of machine learning models based on <a href="https://github.com/ggerganov/ggml/tree/master">GGML</a>. It was first adopted by Large Language Models before being used by diffusion models.</p><p>The largest quant of Flux, Q8_0, shows almost <a href="https://www.reddit.com/r/LocalLLaMA/comments/1eu6c32/flux1_quantization_quality_bnb_nf4_vs_ggufq8_vs/">no quality degradation</a> compared to the original fp16 model while using less than half the memory. All generated images in this article use the Q8_0 version of Flux Dev.</p><p>To run the GGUF models, you’ll need to complete some additional installation steps. First, install a <a href="https://github.com/city96/ComfyUI-GGUF">custom node</a> by following the GitHub instructions to clone the repository into the ComfyUI/custom_nodes directory and install the required dependencies.</p><p>Three additional models are needed other than the main GGUF model:</p><ul><li>ae.safetensors, download from <a href="https://huggingface.co/black-forest-labs/FLUX.1-dev/tree/main">Black Forest Labs HF Repository</a> and move it into ComfyUI/models/vae</li><li>Clip_l.safetensors, download from <a href="https://huggingface.co/comfyanonymous/flux_text_encoders/tree/main">Comfyanonymous HF Repository</a> and move it into ComfyUI/models/clip</li><li>t5xxl_fp8_e4m3fn.safetensors , download from <a href="https://huggingface.co/comfyanonymous/flux_text_encoders/tree/main">Comfyanonymous HF Repository</a> and move it into ComfyUI/models/clip</li></ul><p>Then install the workflows <a href="https://civitai.com/models/664346?modelVersionId=743498">here</a> and drag the “model_Q8_CLIP_FP_16_FLUX_DEV.json&quot; file onto the ComfyUI workspace. With the Q2 and Q3 models, GPUs with as little as 6GB of VRAM can run Flux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgqpAMdYcaU5S77_Dto1tw.png" /><figcaption>Text-to-image workflow for Flux Dev.</figcaption></figure><p>The installed folder includes additional workflows beyond basic text-to-image generation, such as LoRA integration and image-to-image generation. You can try these by simply dragging the corresponding JSON files into the workspace.</p><p>Next, install a version of <a href="https://huggingface.co/city96/FLUX.1-dev-gguf/tree/main">Flux Dev</a> or <a href="https://huggingface.co/city96/FLUX.1-schnell-gguf">Flux Schnell</a> that suits your needs. Keep in mind that smaller models run faster but produce lower quality images. To generate an image, click the “queue prompt” button in the sidebar.</p><p>When using the models, Flux Dev needs 20 or more steps to generate decent quality images (adjustable under the basic scheduler node), while Schnell can work with just 1 to 4 steps.</p><h3>How to Get the Best Results: Tips and Tricks</h3><p>While Flux is designed for users of all technical backgrounds, certain techniques can improve generation quality for specific use cases.</p><h3>Understanding The Flux Guidance Parameter</h3><p>The Flux Guidance parameter is crucial for determining the style and quality of generated images. It functions similarly to the “Classifier-Free Guidance (CFG)” parameter used in other diffusion models.</p><p>Higher guidance values lead to better prompt adherence, while lower values allow more creative freedom at the cost of prompt accuracy. While this general principle is helpful, the guidance parameter has many nuances.</p><p>For example, longer and more detailed prompts typically work better with lower guidance values, while shorter, simpler prompts often need higher guidance values for satisfactory results.</p><h3>Optimizing Guidance Values for Different Styles</h3><p>For photorealistic generations, lower guidance values typically produce better quality images than higher values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zg9ZD2kTdI0XUsJXagUlw.png" /><figcaption>Left: 2.2 guidance. Right: 3.5 guidance. Prompt: old man with glasses portrait, photo, 50mm, f1.4, natural light, Pathéchrome.</figcaption></figure><p>Although the difference is subtle in this generation, we can see that the model with a higher guidance produced an image with more saturation and a “vibrant” color, which is somewhat typical of usual AI generated images. Additionally, the background appears to be more “smoothed out” on a higher guidance value, possibly due to the lack of description for the background.</p><p>A guidance value of around 2 will produce the best photography generations while a higher guidance value, such as 6 or above, is more suited for cartoon and anime styled images. For paintings with distinctive brush strokes, a guidance value of 1 to 1.5 is recommended.</p><h3>The Impact of Capitalization in Prompts</h3><p>On a side note, one <a href="https://www.reddit.com/r/StableDiffusion/comments/1ej2txw/flux1_is_actually_quite_good_for_paintings/">reddit</a> user pointed out that Flux’s text encoder also encodes capitalization, which means phrases like “vincent van gogh’s style” may be drastically different than “Vincent Van Gogh’s style”. This difference applies not only to artists but any well-known people.</p><h3>Generating Accurate Text and Letters</h3><p>To produce accurate text, regardless of the medium (billboards, posters, or clothing), higher guidance values are more likely to generate correct results than lower values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9smDegMuS0_McBkE--cl4w.png" /><figcaption>Left: 2.0 guidance. Right: 3.5 guidance. Prompt: Create an avant-garde concert flyer for a fictional interplanetary music festival. The background should depict a cosmic landscape with swirling nebulae and distant galaxies. Floating in space, arrange various musical instruments from different cultures, each one morphing into a unique alien lifeform. The event name “COSMIC HARMONY: INTERGALACTIC MUSIC CONVERGENCE” should be written in a dynamic, electrode-inspired font that appears to be made of pulsating energy. Include smaller text that says “Where musical dimensions collide” at the bottom.</figcaption></figure><p>While both attempts failed to generate all text accurately, the image with higher guidance came much closer to the desired result.</p><p>To improve text accuracy while maintaining low guidance, increasing the resolution can help. The images above were generated at 512x512 resolution. At 1024x1024, even an image with 2.0 guidance produces more accurate text than the smaller image with higher guidance, though generation takes more than twice as long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsu2SDeU5HZ0FZyMx_YuPA.png" /><figcaption>Guidance: 2.0, same prompt and seed as above with 1024x1024 resolution</figcaption></figure><h3>Leveraging Natural Language in Prompts</h3><p>Flux’s text encoder handles natural language with precision. Prompts should sound like conversational requests to ChatGPT rather than detailed scene descriptions.</p><p>For example, when generating an image with a specific mood, simply state the desired mood rather than describing color gradients and atmosphere in detail. Flux understands these natural instructions easily.</p><h3>Specifying Text Placement in Prompts</h3><p>Despite its excellent language understanding, Flux struggles to interpret generic terms like “labels” or “captions” when placing text on posters or products.</p><p>For best results, be direct with text placement instructions. Instead of using “labels,” specify exactly where text should appear: “small words on the bottom of the product that read: blah blah blah.”</p><h3>Was Flux Overhyped?</h3><p>The Flux family of models showcases impressive performance metrics, with both Dev and Pro models surpassing all other diffusion models, open source or proprietary. However, the model isn’t without flaws. It still stumbles over common text-to-image generation challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPdzwuOMbCiHvYQm7WjAeg.png" /><figcaption>Performance Chart from <a href="https://blackforestlabs.ai/announcing-black-forest-labs/">Black Forest Labs</a></figcaption></figure><p>According to most <a href="https://arstechnica.com/information-technology/2024/08/flux-this-new-ai-image-generator-is-eerily-good-at-creating-human-hands/">articles</a> and <a href="https://www.reddit.com/r/open_flux/comments/1eo8c4f/flux_really_good_with_hands_prompt_in_comments/">posts</a>, while Flux seems perfect at generating hands and text, closer inspection reveals its limitations. Flux excels at close-up shots of hands with simple gestures but struggles with scenes containing multiple people or hands at a distance (try generating two people holding hands — even close-up shots rarely come out correct).</p><p>Similarly with text, Flux can generate simple text scenes with impressive accuracy, even handling multiple sentences. However, when dealing with complex scenes or text at different angles, such as vertical text, the output often becomes unintelligible gibberish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*naUMh0y_aUwL8js4Fci4Zw.png" /><figcaption>Guidance: 3.2 Prompt: Closeup product photo of a FLUX swag water bottle thermos, printed with large “FLUX” text, intricate marble geode patterned exterior, futuristic minimalism, sleek professional design, plain solid background.</figcaption></figure><p>Regardless, the Flux family represents an incredible leap forward for diffusion models, both open source and proprietary. Over time, we can expect to see specialized fine-tunes emerge for specific use cases, improving quality much like we’ve seen with Stable Diffusion variants (such as <a href="https://civitai.com/models/133005/juggernaut-xl">Juggernaut XL</a>).</p><p>Article was originally published <a href="https://deepgram.com/learn/is-flux-overhyped-how-to-run-flux-locally">here</a> by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aece1c453691" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Underlying Dangers Behind Large Batch Training Schemes]]></title>
            <link>https://medium.com/data-science/the-underlying-dangers-behind-large-batch-training-schemes-6cdc0e511ef1?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cdc0e511ef1</guid>
            <category><![CDATA[thoughts-and-theory]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Sat, 12 Nov 2022 07:11:22 GMT</pubDate>
            <atom:updated>2022-11-15T07:53:18.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-0R43xTwwjG--E_G" /><figcaption>Photo by <a href="https://unsplash.com/@julianhochgesang?utm_source=medium&amp;utm_medium=referral">Julian Hochgesang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>The hows and whys behind the generalization gap and how to minimize it</h4><p>In recent years, Deep Learning has stormed the field of Machine Learning with its versatility, wide range of applications, and parallelization training ability. Deep Learning algorithms are typically optimized with gradient-based methods, referred to as “Optimizers” in Neural Networks. Optimizers use the gradients of the loss function to determine an optimal adjustment to the parameter values of the network. Most modern optimizers deviated from the original Gradient Descent algorithm and adopted it to compute an approximation of the gradient within a batch of samples extracted from the entire dataset.</p><p>The nature of Neural Networks and their optimization technique allowed for parallelization or training in batches. Large batch sizes are often adopted when computation powers are allowed to significantly speed up the training of Neural Networks with up to millions of parameters. Intuitively, having a larger batch size increases the “effectiveness” of each gradient update as a relatively significant portion of the dataset was taken into account. On the other hand, having a smaller batch size translates to updating the model parameters based on gradients estimated from a smaller portion of the dataset. Logically, a smaller “chunk” of the dataset will be less representative of the overall relationship between the features and the labels. This can lead to one concluding that large batch sizes are always beneficial to training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_pEyxszOMjlIncf9IXiAw.png" /><figcaption>Large vs. Small Batch Sizes. Image by the author.</figcaption></figure><p>However, the assumptions above are deduced without considering the model’s ability to generalize to unseen data points and the non-convex optimization nature of modern Neural Networks. Specifically, it has been empirically proven and observed by various research studies that increasing the batch size of a model typically decreases its ability to generalize to unseen datasets, regardless of the type of Neural Network. The term “Generalization Gap” was coined for the phenomenon.</p><p>In a convex optimization scheme, having access to a more significant portion of the dataset would directly translate to better results (as depicted by the diagram above). On the contrary, having access to less data or a smaller batch size would reduce training speed, but decent results can still be obtained. In the case of non-convex optimizations, which is the case for most Neural Networks, the loss landscape&#39;s exact shape is unknown, and thus matters become more complicated. Specifically, two research studies have attempted to investigate and model the “Generalization Gap” caused by the difference in batch sizes.</p><h3>The How and the Why of Generalization Gap</h3><p>In the research paper “<strong><em>On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima</em></strong>” from Keskar et al. (2017), the authors made several observations surrounding large-batch training regimes:</p><ol><li>Large Batch Training methods tend to overfit compared to the same network trained with smaller batch size.</li><li>Large Batch Training methods tend to get trapped or even attracted to potential saddle points in the loss landscape.</li><li>Large Batch Training methods tend to zoom in on the closest relative minima that it finds, whereas networks trained with a smaller batch size tend to “explore” the loss landscape before settling on a promising minimum.</li><li>Large Batch Training methods tend to converge to completely “different” minima points than networks trained with smaller batch sizes.</li></ol><p>Furthermore, the authors tackled the Generalization Gap from the perspective of how Neural Networks navigate the loss landscape during training. Training with a relatively large batch size tends to converge to sharp minimizers, while reducing the batch size usually leads to falling into flat minimizers. A sharp minimizer can be thought of as a narrow and steep ravine, whereas a flat minimizer is analogous to a valley in a vast landscape of low and mild hill terrains. To phrase it in more rigorous terms:</p><blockquote><strong>Sharp minimizers</strong> are characterized by a significant number of large positive eigenvalues of the Hessian Matrix of f(x),<em> </em>while <strong>flat minimizers</strong> are characterized by a considerable number of smaller positive eigenvalues of the Hessian Matrix of<em> </em>f(x)<em>.</em></blockquote><p>“Falling” into a sharp minimizer may produce a seemingly better loss than a flat minimizer, but it’s more prone to generalizing poorly to unseen datasets. The diagram below illustrates a simple 2-dimensional loss landscape from Keskar et al.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGaJF1I5uzBqNfMrf9D7TA.png" /><figcaption>A sharp minimum compared to a flat minimum. From Keskar et al.</figcaption></figure><p>We assume that the relationship between features and labels of unseen data points is similar to that of the data points that we used for training but not exactly the same. As the example shown above, the “difference” between train and test can be a slight horizontal shift. The parameter values that result in a sharp minimum become a relative maximum when applied to unseen data points due to its narrow accommodation of minimum values. With a flat minimum, though, as shown in the diagram above, a slight shift in the “Testing Function” would still put the model at a relatively minimum point in the loss landscape.</p><p>Typically, adopting a small batch size adds noise to training compared to using a bigger batch size. Since the gradients were estimated with a smaller number of samples, the estimation at each batch update will be rather “noisy” relative to the “loss landscape” of the entire dataset. Noisy training in the early stages is helpful to the model as it encourages exploration of the loss landscape. Keskar et al. also stated that…</p><blockquote>“We have observed that the loss function landscape of deep Neural Networks is such that large-batch methods are attracted to regions with sharp minimizers and that, unlike small-batch methods, are <strong>unable to escape basins of attraction of these minimizers.</strong>”</blockquote><p>Although larger batch sizes are considered to bring more stability to training, the noisiness that small batch training provides is actually beneficial to explore and avoiding sharp minimizers. We can effectively utilize this fact to design a “batch size scheduler” where we start with a small batch size to allow for exploration of the loss landscape. Once a general direction is decided, we hone in on the (hopefully) flat minimum and increase the batch size to stabilize training. The details of how one can increase the batch size during training to obtain faster and better results are described in the following article.</p><p><a href="https://towardsdatascience.com/why-using-learning-rate-schedulers-in-nns-may-be-a-waste-of-time-8fa20339002b">Why Using Learning Rate Schedulers In NNs May Be a Waste of Time</a></p><p>In a more recent study from Hoffer et al. (2018) in their paper “<strong><em>Train longer, generalize better: closing the generalization gap in large batch training of neural networks</em></strong>”, the authors expanded on the idea previously explored in Keskar et al. and proposed a simple yet elegant solution to reducing the generalization gap. Differently to Keskar et al., Hoffer et al. attacked the Generalization Gap from a different perspective: the number of weight updates and its correlation to the network loss.</p><p>Hoffer et al. offer a somewhat different explanation for the Generalization Gap phenomenon. Note that the batch size is inversely proportional to the number of weight updates; that is, the larger the batch size, the fewer updates there are. Based on empirical and theoretical analysis, with a lower number of weight/parameter updates, the chances of the model approaching a minimum are tremendously smaller.</p><p>To start, one needs to understand that the optimization process of Neural Networks through batch-based gradient descent is stochastic in nature. Technically speaking, the term “loss landscape” refers to a high dimensional surface in which all the possible parameter values are plotted against the loss value across all possible data points produced by those parameter values. Note that the loss value is computed across all possible data samples, not just the ones available in the training dataset, but all possible data samples for the scenario. Each time a batch is sampled from the dataset and the gradient is computed, an update is made. That update would be considered “stochastic” on the scale of the entire loss landscape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pnr1K2CP9XuW1lBzpq1sg.png" /><figcaption>An example of a possible loss landscape. Here, the z-axis would be the loss value while the x and y axis would be possible parameter values. Image by the author.</figcaption></figure><p>Hoffer et al. make the analogy that the optimization of Neural Networks through stochastic gradient-based approaches is a particle performing a random walk on a random potential. One can picture the particle as a “walker”, blindly exploring an unknown high-dimensional surface with hills and valleys. On the scale of the entire surface, each move that the particle take is random, and it could go in any direction, whether towards a local minimum, a saddle point, or a flat area. Based on previous studies of random walks on a random potential, the distance that the walker travels from its starting position scales exponentially with how many steps it takes. For example, to climb over a hill with height <em>d</em>, it will take the particle <em>eᵈ</em> random walks to reach the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyM_Qb_-lHZPZlNQwFD-rw.png" /><figcaption>An Illustration of the exponential relationship between the number of “walks” and distance walked.</figcaption></figure><p>The particle that’s walking on the random high-dimensional surface can be interpreted as the weight matrix, and each “random” step, or each update, can be seen as one random step taken by the “particle”. Then, going from the traveling particle intuition that we built above, at each update step <em>t</em>, the distance that the weight matrix is to its initial values can be modeled by</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FsWf7W3sGpYnUA2mxDzuWkG&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FsWf7W3sGpYnUA2mxDzuWkG&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a6ec6b55604ed92a0b87b179b5078f0/href">https://medium.com/media/4a6ec6b55604ed92a0b87b179b5078f0/href</a></iframe><p>where <strong>w</strong> is the weight matrix. The asymptotic behavior of the “particle” walking on a random potential is referred to as “ultra-slow diffusion”. From this rather statistical analysis and basing off of Keskar et al.’s conclusion of flat minimizers are typically better to “converge into” than sharp minimizers, the following conclusion can be made:</p><blockquote>During the initial training, to search for a flat minimum with “width” <strong>d</strong>, the weight vector, or the particle in our analogy, has to travel a distance of <strong>d</strong><em>,</em> thus taking at least <strong>eᵈ</strong><em> </em>iterations<em>. </em>To achieve this, a high diffusion rate is needed, which retains numerical stability and a high number of iterations in total.</blockquote><p>The behavior described in the “random walk on a random potential” can be empirically proven in the experiments performed by Hoffer et al. The graph below plots the number of iterations against the euclidean distance of the weight matrix from initialization for different batch sizes. A clear logarithmic (at least asymptotic) relationship can be seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AobQz8AuEQ-6JyOe8kYvQ.png" /><figcaption>The number of iterations plotted against the distance of the weight matrix from initialization. From Hoffer et al.</figcaption></figure><h3>Methods to Reduce the Generalization Gap</h3><p>There is no inherent “Generalization Gap” in Neural Network training, adaptations can be made to learning rate, batch sizes, and training method to (theoretically) completely eliminate the Generalization Gap. Based on the conclusion made by Hoffer et al., to increase the diffusion rate during the initial steps of training, the learning rate can be set to a relatively high number. This allows the model to take rather “daring” and “large” steps to explore more areas of the loss landscape, which is beneficial to the model eventually reaching a flat minimizer.</p><p>Hoffer et al. also proposed an algorithm to decrease the effects of the Generalization Gap whilst being able to keep a relatively large batch size. They examined Batch Normalization and proposed a modification, Ghost Batch Normalization. Batch Normalization reduces overfitting and increases generalization abilities as well as speeds up the convergence process by standardizing the outputs from the previous network layer, essentially putting values “on the same scale” for the next layer to process. Statistics are calculated over the entire batch, and after standardization, a transformation is learned to accommodate for the specific needs of each layer. A typical Batch Normalization algorithm looks something like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8J8JxZwDmjmU2sixdS8bk7&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F8J8JxZwDmjmU2sixdS8bk7&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="379" height="213" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca3544e5d66ffa5e3df494e4983c1ec9/href">https://medium.com/media/ca3544e5d66ffa5e3df494e4983c1ec9/href</a></iframe><p>where <em>γ</em> and <em>β</em> represent the learned transformation, and <strong><em>X</em></strong> is the output from the previous layer for one batch of training samples. During inference, Batch Normalization uses precomputed statistics and the learned transformation from training phase. In most standard implementations, the mean and the variance are stored as an exponential moving average across the entire training process, and a momentum term controls how much each new update will change the current moving average.</p><p>Hoffer et al. propose that by using “ghost batches” to compute statistics and perform Batch Normalization, the Generalization Gap was able to be reduced. By using “ghost batches”, small chunks of samples are taken from the entire batch, and statistics are computed over those small “ghost batches”. By doing so, we applied the concept of increasing the number of weight updates to Batch Normalization, which doesn’t modify the entire training scheme as much as reducing the batch size as a whole. However, during inference, the entire batch statistics are used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C54h-qHmNKFre8Om03TEcw.png" /><figcaption>The Ghost Batch Normalization algorithm. From Hoffer et al.</figcaption></figure><p>In Tensorflow/Keras, Ghost Batch Normalization can be used by setting the virtual_batch_size parameter in the BatchNormalization layer to the size of ghost batches.</p><h3>Conclusion</h3><p>In real-world practices, the Generalization Gap is a rather overlooked topic, but its importance in Deep Learning cannot be ignored. There are simple tricks to reduce or even eliminate the gap, such as</p><ul><li>Ghost Batch Normalization</li><li>Using a relatively large learning rate during the initial phases of training</li><li>Start from a small batch size and increase the batch size as training progresses</li></ul><p>As research progresses and Neural Network interpretability improves, the Generalization Gap can hopefully completely become a thing of the past.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cdc0e511ef1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-underlying-dangers-behind-large-batch-training-schemes-6cdc0e511ef1">The Underlying Dangers Behind Large Batch Training Schemes</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Using Learning Rate Schedulers In NNs May Be a Waste of Time]]></title>
            <link>https://medium.com/data-science/why-using-learning-rate-schedulers-in-nns-may-be-a-waste-of-time-8fa20339002b?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fa20339002b</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Fri, 05 Aug 2022 13:18:30 GMT</pubDate>
            <atom:updated>2022-08-05T13:18:30.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Using Learning Rate Schedulers in NNs May Be a Waste of Time</h3><h4>Hint: Batch size is the key, and it might not be what you think!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H-NPJXpUJHNptEHo" /><figcaption>Photo by <a href="https://unsplash.com/es/@andriklangfield?utm_source=medium&amp;utm_medium=referral">Andrik Langfield</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>TL;DR:</strong> instead of decreasing the learning rate by a factor, increase the batch size using the same factor to achieve faster convergence and, if not better, training results.</blockquote><p>In recent years, the continuous development of neural networks has led to an increasing amount of applications of them in the real world. Despite the popularity surrounding neural networks and other similar deep learning methods, they still contain significant drawbacks that influence their usability or performance on unseen datasets.</p><p>Neural Networks are notoriously known for consuming significant computational resources and time. As the continuing research for neural networks progresses, more and more complex architectures are being proposed and put into practice. However, even though some larger networks may be able to obtain decent performance compared to their smaller counterparts, the sheer amount of training and inference time it takes deems them inapplicable to many real-world scenarios. One standard solution to decrease the training time for neural networks is increasing the batch size, or how much data the network sees for one update of its parameters. Logically, if the network sees more data for each update, then the total number of parameter updates would decrease compared to a network that updates its parameters every time a new sample is presented. We can effectively reduce network training time by decreasing the number of parameter updates.</p><h4>Batch Size and Generalization Gaps</h4><p>However, recent studies show that larger batch sizes lead to bigger generalization gaps (see Nitish Shirish Keskar et al. “On large-batch training for deep learning: Generalization gap and sharp minima”). The term generalization gap is synonymous with overfitting, describing the phenomenon where there is a “gap” in performance between training and testing data, the latter being worse than the first. To increase performance on unseen datasets, models need to have the ability to generalize and apply what they have learned in training to new, unseen samples.</p><p>To explain why increased batch size leads to significant generalization gaps, imagine a string of numbers in increasing order by 2, starting from “1, 3, 5, …”, all the way up to “…,37, 39”. Now, say that you were told to select 15 numbers randomly from the list without looking. After you open your eyes, how likely will you discover the increment pattern in the original list (assuming that you were not told the pattern beforehand)? After some rearranging, the answer is expected to be very likely. This is because you were given 15 out of 20 values in the list; by chance, some combinations can give away the pattern. What if you could only randomly select three values from the list? Would you still be able to identify the pattern? The answer will not be as certain because three values out of the 20 in the list may give little to no information about the original relationship between each number (increment by 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0TpRNIL-3LDl_VurtSuHw.png" /><figcaption>A thought experiment on the difference between larger vs. smaller batch sizes. Image from the author.</figcaption></figure><p>The effect that batch sizes have on the model performances works the same way as the thought experiment presented above: the larger the batch size, the more likely that the model will be able to discover relationships between features and targets in fewer epochs. This finding may be beneficial to training since the model could reach the global minima quicker, but it comes at the cost of poorer generalization. When the model sees fewer data at every update step, it may not be able to find the best parameters that suit the training data, but it is more likely to generalize a universal rule for all datasets of the same type (just like how not every list of numbers in the world has the pattern of increment by 2). Models with larger batch sizes are more prone to overfit, creating bigger generalization gaps than models with smaller batch sizes that can perform well over unseen samples.</p><h4>How Batch Size and Learning Rate Relates to Noisy Training</h4><p>Samuel L. Smith and Quoc V. Le, in their study “A bayesian perspective on generalization and stochastic gradient descent,” further proves this point by proposing a “noise scale” calculation for the SGD optimizer:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F3oW9nPYJFd9QfDQQ3pcQ4L&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F3oW9nPYJFd9QfDQQ3pcQ4L&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/292880e22dca71a9148d085a2846abb5/href">https://medium.com/media/292880e22dca71a9148d085a2846abb5/href</a></iframe><p>where N is the number of training samples, B is the batch size, and epsilon is the learning rate. Due to B &lt;&lt; N in most cases, we can simplify the noise scale to</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2F8Bb8sHuEWb9cr66qrhzaFc&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2F8Bb8sHuEWb9cr66qrhzaFc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/96c785981c47087444eb140e5bf16f4c/href">https://medium.com/media/96c785981c47087444eb140e5bf16f4c/href</a></iframe><p>The “noise scale” value describes the magnitude of random fluctuations in SGD training due to batch updates. Intuitively, the smaller the noise, the better the training result, but note that keeping a reasonable amount of noise in training helps the model to generalize, serving as regularization to training. Setting the batch size to a relatively large value will produce minimal noise throughout training, resulting in worse generalization ability thus the intuition surroudning larger batch sizes leading to greater generalization gaps.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FnUhSKZXQ93oxWKS1btThQQ&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FnUhSKZXQ93oxWKS1btThQQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="261" height="153" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b88ed479fc40a35d6b552e5068576d/href">https://medium.com/media/b5b88ed479fc40a35d6b552e5068576d/href</a></iframe><p>Decaying learning rates are usually employed as a part of training to decrease noise. By having a larger learning rate value at the start of training, the network would be able to search a larger parameter space in the noisy situation. Once the model has found the optimal direction/step to take, extra noise may start to hurt the training (i.e., validation loss starts to increase), then the learning rate is slowly brought down. This action will reduce the noise as the model closes in on the global minima, slowing down to a more stable training phase. Doing so can ensure model generalization and decent training results but at the cost of lengthy training time of up to days or even weeks for complex ConvNets.</p><h4>Increase the Batch Size Instead of Decaying the Learning Rate</h4><p>Notice that not only can decaying the value of epsilon/learning rate decrease the noise level, but also increasing the value of B/batch size can achieve the same effect. Utilizing this fact, Samuel L. Smith, Pieter-Jan Kindermans, Chris Ying, and Quoc V. Le showed that learning rate and batch size are inversely proportional in their study “Do not Decay the Learning Rate, Increase the Batch Size.” The authors proposed that instead of using learning rate schedulers, the batch size should be increased during training which can empirically achieve the same results as decaying learning rates. In the authors’ experiment, they trained three types of models with the following conditions:</p><ol><li>Decaying learning rate: learning rate is repeatedly decreased by a factor of 5</li><li>Hybrid: batch size is increased at the first step while holding the learning rate constant, then the training style reverts to #1. This training method simulates potential hardware limits where a larger batch size is not feasible</li><li>Increasing batch size: batch size is increased by a factor of 5 at the same rate as #1.</li></ol><p>The diagram shown below presents their training results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjaWeqe9AyykBPHXz4XPDQ.png" /><figcaption>Experiment results from 3 types of models. From Samuel L. Smith et al.</figcaption></figure><p>On the left, we observe that the training result of the model with the increasing batch size is equivalent to training with a decaying learning rate. However, the model with increased batch size achieved the result of 67% fewer parameter updates than the traditional decaying learning rate model. More specifically, the authors stated that batch size should be increased until it is around N/10; then, the model will revert to the traditional decaying learning rate training style for the rest of the training duration.</p><p>Essentially, we can replace learning rate schedulers with “batch size schedulers” and substantially decrease training time. Below is a simple demonstration of the authors’ method in Keras. The forest cover type dataset is used (can be found in Scikit-learn).</p><pre>from sklearn.datasets import fetch_covtype</pre><pre>dataset = fetch_covtype()<br>X = pd.DataFrame(dataset.data)<br>y = pd.DataFrame(dataset.target)<br>y = pd.get_dummies(y[0])</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)</pre><p>The model used for demonstration is a rather deep network for tabular data with seven hidden layers and a bottleneck-like design.</p><pre>def create_testing_model():<br>    <br>    inp = L.Input(X.shape[1])<br>    x = L.Dense(512, activation=&quot;relu&quot;)(inp)<br>    x = L.Dropout(0.25)(x)<br>    x = L.Dense(256, activation=&quot;relu&quot;)(x)<br>    x = L.Dense(256, activation=&quot;relu&quot;)(x)<br>    x = L.Dropout(0.25)(x)<br>    x = L.Dense(128, activation=&quot;relu&quot;)(x)<br>    x = L.Dense(256, activation=&quot;relu&quot;)(x)<br>    x = L.Dense(256, activation=&quot;relu&quot;)(x)<br>    x = L.Dropout(0.25)(x)<br>    x = L.Dense(512, activation=&quot;relu&quot;)(x)<br>    x = L.Dropout(0.25)(x)<br>    out = L.Dense(7, activation=&quot;softmax&quot;)(x)<br>    normal_model = M.Model(inputs=inp, outputs=out)<br>    normal_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=6e-4), loss=tf.keras.losses.CategoricalCrossentropy())<br>    <br>    return normal_model</pre><p>By mimicking the Keras ReduceLROnPlateau callback, batch size is increased by a factor of 5 starting at 256 when the validation loss does not improve for three epochs.</p><pre># timing purposes<br>batch_start = time.time()<br># total epoch number<br>epoch=60<br># ensure the batch size is 256 on the first epoch<br>batch_size=256/reduce_fac<br># for recording training history<br>batch_history_total = pd.DataFrame([], columns=[&quot;loss&quot;, &quot;val_loss&quot;])<br># init model<br>batch_model = create_testing_model()</pre><pre># make sure batch size does not exceed sample size/10 and epoch doens&#39;t go below 0<br>while epoch &gt; 0 and batch_size &lt;= len(X_train)/10:<br>    <br>    print(F&quot;CURRENT BATCH SIZE: {batch_size*reduce_fac}&quot;)<br>    # early stop if val loss stops improving for 3 epochs<br>    early_stop = C.EarlyStopping(monitor=&quot;val_loss&quot;, patience=3, verbose=2)</pre><pre>batch_history = batch_model.fit(X_train, y_train, epochs=epoch, batch_size=int(batch_size*reduce_fac), <br>                                    validation_data=(X_test, y_test), callbacks=[early_stop], verbose=2)<br>    cur_history = pd.DataFrame(batch_history.history)<br>    # concat the current training history to the total dataframe<br>    batch_history_total = pd.concat([batch_history_total, cur_history], axis=0).reset_index(drop=True)<br>    # adjust batch size<br>    batch_size = batch_size*(reduce_fac)<br>    # decrease total epoch by the number of epochs trained<br>    epoch_trained = len(cur_history)<br>    epoch -= epoch_trained</pre><pre>if epoch &gt; 0: <br>    # reverting to reduce lr training<br>    print(&quot;reverting to reduce lr training&quot;)<br>    reduce_lr = C.ReduceLROnPlateau(monitor=&quot;val_loss&quot;, factor=(1/reduce_fac), patience=3, verbose=2)<br>    batch_history = batch_model.fit(X_train, y_train, epochs=epoch, batch_size=int(batch_size), validation_data=(X_test, y_test), callbacks=[reduce_lr], verbose=2)<br>    batch_history_total = pd.concat([batch_history_total, pd.DataFrame(batch_history.history)], axis=0).reset_index(drop=True)</pre><pre>batch_end = time.time()</pre><p>For comparison, the same model was trained with a constant batch size of 256 while reducing the learning rate for every three epochs that the validation loss did not improve. Both models were trained for 60 epochs, and the model trained solely with ReduceLROnPlateau was astoundingly two times slower (on GPU) with a slightly worse validation performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phPkW-SNQ6rTufkPWEttHQ.png" /><figcaption>Training result comparison between the reduce batch size method and the decay lr method. Image from the author.</figcaption></figure><p>Next time, when training any neural networks, regardless of image classification, tabular data, or audio tasks, give “batch size schedulers” a try. The results might save you some time (and subtle improvements)!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fa20339002b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-using-learning-rate-schedulers-in-nns-may-be-a-waste-of-time-8fa20339002b">Why Using Learning Rate Schedulers In NNs May Be a Waste of Time</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Really “Fair” in Machine Learning?]]></title>
            <link>https://medium.com/data-science/what-is-really-fair-in-machine-learning-1fcdb6f35313?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fcdb6f35313</guid>
            <category><![CDATA[discrimination]]></category>
            <category><![CDATA[fairness]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Wed, 06 Oct 2021 22:12:05 GMT</pubDate>
            <atom:updated>2021-10-08T06:08:12.896Z</atom:updated>
            <content:encoded><![CDATA[<h4>Looking at ways to measure and visualize fairness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-qfSkFXpT-cMf2uJdhTFA.jpeg" /><figcaption><a href="https://unsplash.com/photos/FO7bKvgETgQ">Source</a></figcaption></figure><h3>(In)Equality In Machine Learning</h3><p>A s the field of machine learning expands and the power of AI is being used to make crucial decisions, we start to wonder if machine learning algorithms are really “fair.” Machine Learning algorithms are affecting decisions where discrimination and bias are present; our goal is to measure the outcome of such decisions and ensure equality during our predictions. Although Machine Learning models may help with human decision-making while saving time, results produced by ML algorithms can also show bias in favor of specific groups. Equality in machine learning is a new field being constantly explored by researchers as the need to measure and maintain fairness is becoming increasingly important.</p><p>Machine learning algorithms cannot function without data. Data is the key to decision-making in Machine learning; thus, many biases emerge from the training data. Bias in data is mostly caused by <em>human collection methods</em> and <em>misinformation or little information towards minority groups</em>. While some could argue that changing data-gathering methods can reduce the favor of one group over the other, the truth is, in most scenarios equality during data collection cannot be ensured. Instead, we need to have models produce outputs that are not affected by potential bias factors such as race or gender. Knowing that the data could be unfair is by no means enough, <strong>we need to be able to measure and represent relations through these sensitive attributes to our predictions.</strong> These relations can be calculated and even visualized through tools and metrics thus better helping us understand inequalities in models and data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0iCUa8XOvAmGLgsY0nRlQ.png" /><figcaption>Image by author created using Canva</figcaption></figure><h3>Defining the Problem</h3><p>As mentioned before, unfairness to certain groups is caused by “<strong>sensitive attributes</strong>” that may separate one category from another such as ethnicity or sex. In a perfect scenario, a model would predict some targets based on features provided without discrimination to any groups. The simplest solution would be to remove such “sensitive attributes”. However, simply taking those features away will not do much. Since most sensitive attributes are very <em>distinctive</em> among people, the model would still be able to infer the removed features based on other information provided. There are certain measurements or statistical properties that the predictions or the data must satisfy to be considered “fair”.</p><p>Imagine a situation where multiple people are applying for a job with different experiences. Our goal is to predict whether someone will be offered the job based on their features. Here, <strong><em>A</em></strong> will represent the sensitive or protected feature, <strong><em>X</em></strong> will be any other information that tells us about the person applying, <strong><em>Y</em></strong> being the ground truth and <strong><em>Ŷ</em></strong> being our predictions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FwYQyT6HdbgTcEGD2mNdhjA&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FwYQyT6HdbgTcEGD2mNdhjA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/201483d7cddb12553ccd32fd166848e8/href">https://medium.com/media/201483d7cddb12553ccd32fd166848e8/href</a></iframe><p>We can formulate the problem by estimating the probability distribution of <strong><em>Y</em></strong> given features <strong><em>X</em></strong> and <strong><em>A. </em></strong>Then we can represent our prediction for a certain person as</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FmCQHcdQyCHS5izTqk6huWW&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FmCQHcdQyCHS5izTqk6huWW&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/478a2293050f45cbf977e9c7dd979415/href">https://medium.com/media/478a2293050f45cbf977e9c7dd979415/href</a></iframe><p>when the ground truth is 1 concerning feature <strong><em>X</em></strong> and protected attribute <strong><em>A</em></strong>.</p><h3>Evaluation Methods and Metrics</h3><p>One of the most widely used criteria for measuring model prediction is the <strong>Demographic Parity</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FsV5ZWqyaawkVxdeV2zuzWd&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FsV5ZWqyaawkVxdeV2zuzWd&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="439" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/cee08b1144f8d81f56a057b1d9e9145f/href">https://medium.com/media/cee08b1144f8d81f56a057b1d9e9145f/href</a></iframe><p>To satisfy this property, <strong><em>Ŷ</em></strong> must be statistically independent of <strong><em>A</em></strong>. Simply, <strong><em>A</em></strong> cannot relate to the prediction of <strong><em>Y</em></strong> in any way no matter the values of the ground truth.</p><p>The demographic parity can be further expanded into the <strong>Strong Demographic Parity</strong>. In the previous case of Demographic Parity, we state that the <strong>binary</strong> model output must be independent of the sensitive attribute. A binary outcome is determined by a threshold on the continuous output of the model where if the prediction is greater than the threshold, we consider it 1. Demographic Parity can be enforced for a certain threshold but does not ensure it applies for all cases. On the other hand, Strong Demographic Parity imposes statistical independence between <strong><em>A</em></strong> and the continuous output from the model, further ensuring unbiases. In our scenario, without any other features, everyone should have the same chances of being offered a job no matter their sensitive attribute.</p><p>Similarly to Demographic Parity, there’s <strong>Equality of Opportunity</strong>. Equality of Opportunity only constrains equality in the advantaged outcome group. In our situation, it’s being offered the job. Equality of Opportunity allows the prediction to depend on <strong><em>A</em></strong> but <em>only through the ground truth</em>. Note that this method allows for using features that directly relate to the outcome, but does not tolerate using <strong><em>A</em></strong> to represent the result.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Fk9ZNPrfJPRfqGMXbPcXLXq&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Fk9ZNPrfJPRfqGMXbPcXLXq&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="397" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/3251d99b5789c13551c3dc639073a49b/href">https://medium.com/media/3251d99b5789c13551c3dc639073a49b/href</a></iframe><p>The true positive rate should remain the same for all values of <strong><em>A</em></strong> in the advantaged outcome. It’s less strict than the Demographic Parity, which ensures that the probability of our prediction being a certain class <strong>remains the same across</strong> all values of A no matter if the ground truth. Simply put, with a group of people with the same qualifications, they have the <strong>equal</strong> <strong>opportunity </strong>to be offered the job no matter their “sensitive attribute”. This has a wider range of applications since most people only care about non-discrimination in the “positive group”.</p><p>Finally, there’s Predictive Parity. Predictive parity, or sometimes called the outcome test, focuses more on the ground truth of <strong><em>Y</em></strong>. It requires given our prediction y-hat, the ground truth cannot depend on <strong><em>A</em></strong> as opposed to equality of opportunity it’s our predictions <strong><em>Ŷ</em></strong> that cannot relate to <strong><em>A</em></strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FrBLvvMkqk1vBRoMnynt6G5&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FrBLvvMkqk1vBRoMnynt6G5&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="411" height="96" frameborder="0" scrolling="no"><a href="https://medium.com/media/30cd280c2862762d34323302867e327e/href">https://medium.com/media/30cd280c2862762d34323302867e327e/href</a></iframe><p>This shows that the precision of our model, or the probability of <strong><em>Ŷ </em></strong>being positive and it truly belong to the positive class, should remain the same across all values of <strong><em>A</em>.</strong></p><h3>A Gentle Intro to CBNs</h3><p>Now that we’ve established a sense of how fairness is measured and evaluated through our predictions, we turn our hands to visualizations. A Causal Bayesian network can represent scenarios and illustrate fairness through arrows and diagrams. Back to our situation:</p><ul><li>For each person, we have features x that tell us about the person in some ways.</li><li>We also have <strong><em>A</em></strong>, the protected attribute, in our case, it’ll be gender.</li><li>Our predictions <strong><em>Ŷ </em></strong>will produce a probability between 0 and 1 representing whether the person will be offered a job or not.</li></ul><p>Such a situation can be represented using a <em>direct acyclic graph</em> with nodes and edges called Casual Bayesian Network(CBN). In the bayesian network, nodes represent random variables or features relating to the problem while the edge between them shows their statistical dependencies.</p><p>As shown in the figure on the right below, <strong><em>A</em></strong> is considered a direct influence on <strong><em>Y</em></strong> if the path directly points to <strong><em>Y.</em></strong> This is considered a casual path. On the other hand(figure to the left), if <strong>A</strong> does not directly point to <strong><em>Y</em></strong>, it indicates that for <strong><em>A</em></strong> to potentially influence <strong><em>Y</em></strong>, it must go through <strong><em>X</em></strong>. When the influence of the sensitive attribute is represented through other features <strong><em>X</em></strong>, it is considered fair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Dh7uYuyqzMbpDcCERi9mg.png" /><figcaption>CBNs, Image by author using LucidChart</figcaption></figure><p>In this particular figure, the path from <strong><em>A</em></strong> to <strong><em>X</em></strong> represents the probability of <strong><em>X</em></strong> based on <strong><em>A</em></strong>, i.e. <strong><em>p(X|A)</em></strong>. The path from <strong><em>X</em></strong> to <strong><em>Y</em></strong> again is the chances of Y being true based on X, <strong><em>p(Y|X)</em></strong>. In a situation where there is no casual path from A to X, the<strong> joint distribution </strong>of the 3 variables is</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FtfhaMsctbsGNTwv93M2q27&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FtfhaMsctbsGNTwv93M2q27&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="137" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e4cfe7cefeec350d4f2d1ddbc5bb66b/href">https://medium.com/media/6e4cfe7cefeec350d4f2d1ddbc5bb66b/href</a></iframe><p><strong><em>A</em></strong> may influence <strong><em>Y</em></strong>, but not directly.</p><p>When any casual path is established between A and Y, the metrics mentioned above cannot be satisfied. There’s a lot more to CBNs and even using it to quantify unfairness, however, the basics of it are as simple as described above.</p><h3>Conclusion</h3><p>In this post, we have discussed various methods to measure fairness and even visualize relations associated with it. Unfairness may be hard or even impossible to eliminate in data, thus we need to be able to discover such inequality and able to decipher its influence on our model predictions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fcdb6f35313" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-really-fair-in-machine-learning-1fcdb6f35313">What is Really “Fair” in Machine Learning?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey to Kaggle Master at the Age of 14]]></title>
            <link>https://medium.com/data-science/my-journey-to-kaggle-master-at-the-age-of-14-e2c42b19c6f7?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c42b19c6f7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 21:35:29 GMT</pubDate>
            <atom:updated>2021-08-30T14:24:59.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i22o8wLum7I8N_7OrAK2eA.png" /><figcaption><a href="https://www.kaggle.com/andy1010">Author’s Kaggle profile</a></figcaption></figure><p>Some people may find the terms “Data Science” and “Machine Learning” intimidating, believing that they require professional skills to succeed. First glance into the field of Data Science and Machine Learning might be overwhelming, staring at endless lines of code and technical terms, not sure where to start.</p><p>Kaggle is one of the places where many people start their journey. For others, Kaggle is where they compete, earn reputations, and dive deep into the fields of Machine Learning.</p><p>In this article, I will take you through my journey on how I became one of the youngest Kaggle Competition Master at the age of 14.</p><h3>About Myself</h3><p>I’m Andy Wang, a high school freshman with a strong interest in math, artificial intelligence, and computer science. I compete on Kaggle to learn and enhance my skills, earning 2 silver medals and 1 gold medal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2Y7WYbAc6kRT6SjG04rZQ.jpeg" /><figcaption>Image by author</figcaption></figure><h4>Early Experiences</h4><p>A few years ago, I became interested in mathematics and started learning more advanced topics than those taught in school on my own. Not long after, I started looking into programming since I was fascinated with computer science from a young age. My search for online courses led me to several courses that taught Python and basic coding concepts. Before long, I was programming on my own, making small projects such as a Sudoku solver using the <a href="https://en.wikipedia.org/wiki/Backtracking">backtracking algorithm</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EQuMTtWqUA3SqI9z1NgFg.png" /><figcaption>Snippet of code from my Sudoku Generator. Image by author.</figcaption></figure><p>At this point, I am a bit skeptical of where I should go with the knowledge I have in my hands. That is until one day when my friend introduced me to the field of Machine Learning and Data Science where I was truly amazed by its power. I then found Kaggle, a website that has expanded my knowledge of what’s possible with the current computing and AI technologies.</p><h3>How Did I Progress and Learn</h3><p>My knowledge of programming and machine learning concepts is largely derived from the Internet. <strong>The internet is your best teacher when in doubt</strong>. No school taught Data Science or Neural Networks, I’m on my own if I were to succeed on Kaggle.</p><p>Data Science and Machine Learning present a daunting task for many people. With all the resources and subjects presented, people don’t know where to start or how to learn. Because there are so many areas associated with the terms “Data Science” and “Machine Learning”, being proficient in every category is nearly impossible. The power of ML and DS is fascinating. For a beginner like I was, <strong>you need to find what interests you and fully explore the potential of what it can achieve.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlN8J1aC-zHJ64d4QvNXIQ.png" /><figcaption>Different areas of Machine Learning. Image by author created on LucidSpark.</figcaption></figure><p>Learning ML and DS can be different for many based on their prior knowledge, here’s the path I took which I found success in.</p><ol><li>I knew mathematics is the foundation of everything ahead. <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab">Linear algebra</a> and <a href="https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr">calculus</a> are two of the most important math concepts used in Machine Learning. Almost all Machine Learning algorithms are related to these two areas of in one way or another. Data is represented and processed as vectors and matrices. Thus, having an understanding of fundamental operations on matrices is required. One of the most common use for calculus in Machine Learning is <a href="https://en.wikipedia.org/wiki/Gradient_descent"><em>Gradient Descent</em></a>. It’s an algorithm that aims to minimize an objective function by iteratively taking steps to the global minima using the function’s gradient.</li><li>Statistics cannot be left out either. By its name, Data Science are all about data. Although computers can predict certain trends in the data, humans are the only ones who can analyze them, calculate certain properties, and finally come to conclusions about the data. Preprocessing and feature engineering of data heavily rely on statistics. I learned statistics in bits and pieces, scraping off internet articles, and finding appropriate online courses.</li><li>After knowing about the foundations, I turned my hands to coding. With a basic knowledge of <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">Object-Oriented Programming</a>(OOP) and Python, I found online courses that taught me about all the libraries commonly used in Machine Learning. As opposed to simply following the code presented and copy-pasting, I ensured that I understood the math behind what was written.<em> It is impossible to fully utilize anything to your advantage if you do not understand its inner workings</em>. I started with simple algorithms like <a href="https://en.wikipedia.org/wiki/Linear_regression">Linear Regression</a>, up to more complex algorithms like <a href="https://en.wikipedia.org/wiki/Gradient_boosting">Gradient Boosting</a> and <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">Neural Networks.</a></li></ol><blockquote><strong>Learning bits and pieces, one step at a time, the knowledge that you gain from the very beginning can be built up into complicated things in the future with ease.</strong></blockquote><h4>Joining Kaggle</h4><p>At this point, I wanted to build on my knowledge on Kaggle competitions. I joined a starter competition predicting house prices using regression techniques. I discovered what I learned was far from enough. What I’m missing the most is <em>experience</em>. <strong>The best way to learn is through failing and experimenting with new things.</strong> I familiarized myself with the environment of Kaggle, scrolling through discussions and notebooks for explanations surrounding the problem. Not long after, I felt like I was ready for my first real competition. I joined the <a href="https://www.kaggle.com/c/lish-moa">Mechanism of Action competition</a> with my friend <a href="https://www.kaggle.com/washingtongold">Andre Ye</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTzETnP0-Ju5VPDgGF9kOQ.png" /><figcaption>Our first competition, MoA. <a href="https://www.kaggle.com/c/lish-moa/leaderboard">Source</a></figcaption></figure><p>We were both complete novices to competitions at the time. All the professional-looking code and technical discussions in the forums left us dumbfounded. I decided to start from scratch instead of forking a starter notebook. With the help of discussion posts, I was able to establish a baseline in a short time. Being innovative is important to succeeding in the competition. I dug through papers and articles concerning the problem, then combined those with the methods presented on the forums, landing our solution in the top 4%. Afterwards, with some more experience, we joined two more competitions, earning another silver and our first gold medal. The results are a genuine surprise to me and <em>I cannot thank the Kaggle community enough for guiding me through</em>. Here are some tips and tricks I observed and learned while participating in competitions.</p><h3><strong>My General Pipeline for Kaggle Competitions</strong></h3><p>From the competitions that I’ve joined, there’s a general pipeline that I follow which not only organizes work but also produces meaningful result efficiently.</p><ol><li><strong>Read the data description and overview carefully. </strong>Gently explore domain knowledge if possible.</li><li><strong>Before reading any paper, discussion or notebook, try to create a baseline on your own. </strong>This helps with generating brand new ideas before locking your mind onto what’s said by other people.</li><li><strong>Build a viable cross-validation strategy and submit to leaderboard.</strong> It’s important to make sure your CV strategy also works for the LB.</li><li><strong>Read, read and learn! </strong>Fully explore papers related to the topic, look for inspiration in forums and notebooks.</li><li><strong>Get started on tweaking the baseline, model-wise or feature-wise. </strong>Tweak only one thing at a time, so you know what caused the model to improve/perform worse.</li><li><strong>Explore as much new methods as possible</strong>, don’t dwell long on something that just couldn’t work.</li><li><strong>Ensemble! </strong>If everything else fails you, ensembling or stacking is the most stable way I found to improve.</li><li><strong>Only choose submission with good CV score</strong>(and make sure you know why it performs well).</li></ol><h3>What I learned and Utilized</h3><p>As I joined more and more competitions, I was amazed by the complexity of some solutions, from feature engineering to the structure of Neural Networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FogQ4Mo5H5B3c591udwdqQ.png" /><figcaption><a href="https://www.kaggle.com/c/ranzcr-clip-catheter-line-classification/discussion/226633">Amazing First Place Solution from RANZCR Competition</a></figcaption></figure><p>In general, machine learning algorithms can learn fairly well, only from informational data. Being able to utilize algorithms a bit different than what it’s intended could help in certain situations. For example, using <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">Principal Component Analysis(PCA)</a> to reduce the dimension of data <strong>then concatenating the reduced features back to the original ones</strong> helped me out in more than one situation.</p><p>With feature engineering comes feature selection. Removing features that are not important helps reduce the noise in the data. During the Mechanism of Action competition, the methods in forums and discussion posts were not helpful to the model that we designed. <strong>In cases like these, don’t be afraid to dive deep and read papers</strong>. Since the case that I was dealing with, multi-label classification, was not as common, there weren’t any easy tutorials that I could find. I found a paper aimed at comparing <a href="https://pdf.sciencedirectassets.com/272990/1-s2.0-S1571066113X00039/1-s2.0-S1571066113000121/main.pdf?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEHUaCXVzLWVhc3QtMSJHMEUCIQDWDERS1Anybn8Tk7OZfU6FOsRvWGLKevkcjCr9hMkm2QIgNBL%2ByaoQ%2FbUO7AMPvBBtJXjCCAqMkMEkGBXR9ElvBpMqgwQIrv%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARAEGgwwNTkwMDM1NDY4NjUiDO2P%2BmVv3tdhCOz%2FhCrXA5qGE6hv%2BXFhhR1DJmTiwK8%2B0q0UiZUfRE0L9XAEmdCU%2BaX8sCjMCprRPk9HEOWnB7ulAw54YnnBIQmvekngY8%2FJgTWk%2BWGCxuiCCd%2FpAxRivOT36J0ovuZ46YUoRIi0qUKX7FWdrYMeaFmj0OcYpYCD07AYwkiD0LuPsP%2BhW79ha9j%2FP5IoR48i32C97WP9gusoLlSZFW1DPcmvcnBV0Un0NQ8zoMVcDMd7vPC7%2B3aPTNj3%2BLAQFEo%2Fw4xVrRxlWdyjJifV2c6t35hmsaW%2BEdSNxLfRD8SeWv5vuIIuiSIr%2BNbInGFI55XmF8%2B16ZOn9yknM%2Bbv5Pl23I8Hr1WfN0RwrhIchdL0BhAXD%2Byu9GG3rpGSFie7AE%2BeQYkPT5aXVNJRr7QjLO1R6AZKb7KdyKs8e9z0FlfV%2F0Af9D%2BlYJUbVqs1zwQaHV0lYAGVVmEBSyFdZaONS2dceET%2FNak5%2FSEU5eIBBVJU5a%2Bjm21NY2FurOAL1HJom6SfqNoK9GlSEcEz1tKemqJeBWWZuIwEjgb%2BBoIDPrsps0mKZspkM%2BlzqY2KfN3lxV3QxzB6SP4LU0h5YwsuXlR6Bolnpp6RO%2BQYR79yRzcisfgP%2BjMIGYxNYbNX5l8%2F6zCe4q%2BJBjqlAVpD3N9RmPt4QrinMx8PjNM3Pb80qp4bkdZpEVU7BWFGnp29Od1bDIp0g%2B4Bpn22ImolcUKBQNrK3idTVEqhNt9KRpBbooM0qeSsFOTXF1XEd6tFQ6gfCJFRchz%2FLe3%2BaqhLjo%2BN07skCNl50MmBJNGSymcZq3y%2FQhjch9Psh1aPDk07kjmGSqFTg%2FvejlpVwF8XRraDbe5fODe2K5OP7LXu%2B%2FmYgw%3D%3D&amp;X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Date=20210829T212731Z&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Expires=300&amp;X-Amz-Credential=ASIAQ3PHCVTY7XJCOEJF%2F20210829%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Signature=89a596986f75f736a06ce18f3253501e11624d5b8940384098449f531a99dcdc&amp;hash=c25de17c701a704871a346d424f4c7a55e2f1e8478c368d82cee4bf44fe23bc4&amp;host=68042c943591013ac2b2430a89b270f6af2c76d8dfd086a07176afe7c76c2c61&amp;pii=S1571066113000121&amp;tid=spdf-b9c2166a-010a-47ee-b683-3ebc16df1ba6&amp;sid=c12253453b7c964fa09b3c70456df8c898adgxrqa&amp;type=client">multi-label feature selection using Problem Transformation.</a></p><p>Reading research papers might seem daunting, <strong>but being able to skim through them and grasp keywords from long pages of technical terms is a crucial skill.</strong> Trying to understand every bits and piece of every paper that you come across just wasn’t possible for a beginner like me. Only when I land on the paper that I need and will use, I then try to understand every word and reference made in the paper.</p><p>During modeling, the biggest lesson that I learned is <em>creativity</em>. Not only in model structures but think outside of the box on how fundamentally models work on different types of data.</p><ul><li>Tweaking the model to have a <strong>non-linear topology</strong> or building a ResNet-like structured network for tabular data led to some amazing results during not only the MoA competition but also the following one, Jane Street Market Prediction, in which we placed 16th out of 4.2k teams.</li><li>Exploring different types of <strong>autoencoders</strong> such as <a href="https://towardsdatascience.com/denoising-autoencoders-explained-dbb82467fc2">denoising</a>, <a href="https://en.wikipedia.org/wiki/Variational_autoencoder">variational</a> and <a href="https://web.stanford.edu/class/cs294a/sparseAutoencoder.pdf">sparse</a> encoders could bring surprising changes to your data, more than what simple feature engineering and selection can achieve.</li><li><strong>Ensemble</strong>. Combing the results of different models adds variety to your solution thus making it more robust and stable. No matter what modeling tricks worked or not, ensembling was always my “last resort” during competitions.</li><li>Always keep an eye on new papers and explore things outside of what’s mentioned in forums. Tweaking small things like <strong>activation functions</strong> (try <a href="https://arxiv.org/pdf/1710.05941v1.pdf">swish</a> instead of ReLU), and <strong>optimizers</strong> (try <a href="https://arxiv.org/abs/2010.07468">AdaBelief</a> instead of Adam, etc.) might just squeeze some performance out of the model.</li><li>Think outside of the box! Using <a href="https://www.kaggle.com/c/lish-moa/discussion/202256">1D CNN to perform feature extraction on tabular data</a>. Or using <a href="https://www.nature.com/articles/s41598-019-47765-6">DeepInsight</a>, transforming tabular data into images, utilizing the advantages of CNNs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A48XjZVQhuEwbcz1WNJceQ.png" /><figcaption><a href="https://www.kaggle.com/general/248026">Image from Kaggle</a></figcaption></figure><p>Finally, strategies that worked in one competition might not necessarily improve your solution in another. During the Jane Street Market Prediction challenge, I discovered that feature engineering did not help with results at all. I instead found the magic in modeling. A general rule of thumb to keep in mind:</p><blockquote>In situations like these, <strong>don’t dwell on things that “worked before” or “worked for others”, move on and spend more time exploring new things that could bring improvement</strong>.</blockquote><p>Participating in Kaggle competitions and earning medals is no easy feat, but the process can be made easier with the right learning methods and tools.</p><ul><li>Checking the discussion posts and reading through public notebooks is extremely helpful. New ideas emerge every day, I’ve learned about some of the newest and fascinating models and tools through papers mentioned in forums and libraries used in notebooks. One of them being <a href="https://arxiv.org/abs/1908.07442"><strong>TabNet</strong></a>, a new way to model tabular data by incorporating feature selection within the model using sequential attention. This model is what got me to silver in the MoA competition.</li><li>In the end, <strong>having a stable and robust pipeline</strong> is the most crucial to an excellent performance in the final private leaderboard. There’s no point in wasting time overfitting to get an extra .0001 in the public leaderboard.<strong> Always trust your local cross-validation score </strong>since the amount of training data is greater than that of the public leaderboard.</li></ul><blockquote><strong>Despite all the tips and tricks, the most important part of my success has been my consistent modeling pipeline and a stable CV.</strong></blockquote><h4>For a strong, robust CV….</h4><p>When setting up a local cross validation scheme. Here’s a couple things I keep in mind:</p><ol><li><em>Fold number &gt; 3.</em> With smaller fold numbers, the training split is not sufficient to represent the whole data.</li><li><em>Making sure there’s no leak in data. </em>Especially in cases such as time series forecasting, normal cross validation introduces leaking from future data, some form of time series split should be used.</li><li><em>Used stratified folds when there’s an imbalance in targets. </em>Stratified KFold methods attempts to split targets equally among folds.</li><li><strong><em>Making sure you know why something improves. </em></strong>This is very essential since results could be effected by random seed and other unknown factors. This can lead to significant uncertainty in unseen data (private leaderboard).</li></ol><p>Just pressing copy-paste will not help with learning or winning competitions. My most important motto throughout Kaggle is to never copy someone else’s work, I can be inspired by their ideas or even use their modeling methods, but I never submit other’s work as my solution. When approaching new things, I have developed a habit of looking up everything that I do not understand, until I can confidently explain the subject to other people.</p><h3>Lastly….</h3><p>This article might not help you win a competition, but I assure you that they will guide you through your journey through ML and DS with less failure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c42b19c6f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/my-journey-to-kaggle-master-at-the-age-of-14-e2c42b19c6f7">My Journey to Kaggle Master at the Age of 14</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bags of Tricks for Multi-Label Classification]]></title>
            <link>https://andy-wang.medium.com/bags-of-tricks-for-multi-label-classification-dc54b87f79ec?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc54b87f79ec</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 04:19:58 GMT</pubDate>
            <atom:updated>2021-08-26T04:19:58.683Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tips and essentials to for boosting your model performance in multi-label classification</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gVSaCNVNB7Zjgm01gI8fQ.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/c0rIh0nFTFU">Unsplash</a></figcaption></figure><h3>What is Multi-Label Classification?</h3><p>As we all may know, <strong><em>binary classification</em></strong> classifies the given input into two classes, 1 or 0. Multi-label, or multitarget classification simultaneously predicts multiple binary targets at once from the given input. For example, our model can predict whether the picture given is a dog or a cat <strong><em>and</em></strong> if it has long or short fur.</p><p>The targets are <strong><em>mutually</em></strong> <strong><em>exclusive</em></strong> in multi-label classification, meaning that one input can belong to multiple classes. Here, I will be showing a few tips that could improve the performance of your multi-label classification model.</p><h3>Scoring Metrics</h3><p>Most metrics that are used for binary classification can be applied to multi-label by calculating the metric for <strong><em>each column</em></strong>, then taking the<strong> <em>average</em></strong> of the scores. One metric that we could use is log loss or binary cross-entropy. For a better metric that considers class imbalance, we could use ROC-AUC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_ifIH856I5sauRgx8CxCQ.png" /><figcaption>The ROC-AUC Curve from <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">Wikipedia</a></figcaption></figure><h3>Modeling Tricks</h3><p>Before we start on the fancy tricks for the features, I have a few tips on designing a model that suits the situation of multi-label classification.</p><p>For most non-NN models, our only option is to train one classifier for each of the targets and combine the predictions afterward. The library scikit-learn provides a simple wrapper class to do this, the OneVsRestClassifier.</p><p>Although this will make your classifier be able to perform multi-label tasks, this is not an approach that you should take. This has a couple of disadvantages. First, the training time will be relatively long, as for each target, we are training a new model. Second, the models cannot learn the relationship between different labels, or label correlation.</p><p>The second problem could be resolved by performing a two-stage training where we use the prediction of the targets combined with the original features as the input data for our second-stage training. The downside to this is that the training time will be increased drastically since now you’ll have to train double the amount of models of what you had before.</p><p>Neural Networks, or NN, are more suitable for this situation. The number of labels is the number of output neurons in the network. Now we can just apply any binary classification loss to the model and the model will output all the targets simultaneously. This fixes both problems of non-NN models as we will only need to train one model and the network can learn different label correlations through the output neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*l7NrWDWuycAF4dRjFolfsA.jpeg" /><figcaption>Source: <a href="https://medium.com/@guntapallisuresh28/build-your-first-multi-label-image-classification-model-with-neural-network-d4d42d779ab4">Medium</a></figcaption></figure><h3>Supervised Feature Selection Methods</h3><p>Before you get started on any feature engineering or selection, your features should be <strong>normalized</strong> or <strong>standardized. </strong>Using <strong>Quantile Transformer</strong> will reduce the skewness of your data, so that the features follows a <strong>normal distribution. </strong>Another option is to <strong>standardize</strong> the features, which can be done by subtracting the mean from the data, then dividing it by its standard deviation. This accomplishes a similar job compared to Quantile Transformer, with both aiming to transforming your data to be more robust, however the Quantile Transformer is more computational expensive.</p><p>Using supervised feature selection methods is a bit tricky in this situation as most algorithms are designed for single targets. To solve this, we can convert the multi-label situation to a multi-class problem. One popular approach is the LabelPowerset where each unique label combination of the training data is converted into one class. The scikit-multilearn library has tools for <a href="http://scikit.ml/api/skmultilearn.problem_transform.lp.html">this</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Ggt3EvR9nJBfJinaUgaNng.png" /><figcaption>Source: <a href="https://www.researchgate.net/figure/Label-combination-process-of-the-Label-Powerset-method_fig4_216746557">ResearchGate</a></figcaption></figure><p>After the transformation, we can use methods such as <strong>information gain</strong> and <strong>chi2</strong> to select features. While this approach is viable, things become tricky when we have hundreds or even thousands of different unique combinations of labels, this is where unsupervised feature selection methods could be better.</p><h3>Unsupervised Feature Selection Methods</h3><p>In unsupervised methods, we don’t need to consider the nature of the multi-label situation since unsupervised methods do not depend on the label.</p><p>Here are a few algorithms:</p><ul><li>Principal Component Analysis or other similar Factor Analysis methods. This removes redundant information from features and extracts useful insights for the model. One important note to this is that make sure to standardize the data first before applying PCA as this way every feature contributes equally to the analysis. Another tip to using PCA is that instead of taking the reduced features that the algorithm provides, we can concatenate those reduced features back to the original data as extra information which is model can choose to use.</li><li>Variance Threshold. This is a simple yet effective way to reduce the dimensionality of the features. We throw out the features that have a low variance or spread. This could be optimized by finding a better threshold for selection, a good start would be 0.5.</li><li>Clustering. We can create new features by creating clusters from the input data, then assigning the corresponding cluster to each row of input data as a new column of feature.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*E9R_N48ftoul7kp1y9-OIg.gif" /><figcaption>KMeans Clustering</figcaption></figure><h3>Upsampling Methods</h3><p>Upsampling methods are used when our classification data is highly imbalanced, we then generate artificial samples for the rare class(es) so that the model focuses on rarer classes. For creating new samples in multi-label situations, we can use MLSMOTE or Multi-label Synthetic Minority Over-sampling Technique. An implementation can be found <a href="https://github.com/niteshsukhwani/MLSMOTE">here</a>.</p><p>This is a modification from the original SMOTE method. Where in this case after we generate the data for the minority class and assign the corresponding minority label, we also generate the other labels associated with the data point by counting the number of times each label appear in neighboring data points and take the label that has a frequency more than half of the data points counted.</p><h3>Conclusion</h3><p>In this article, we discussed multiple methods and approaches that can be utilized to improve the performance of your multi-label classification model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc54b87f79ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Novel Approaches to Similarity Learning]]></title>
            <link>https://medium.com/data-science/novel-approaches-to-similarity-learning-e680c61d53cd?source=rss-3de8e48ee2c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e680c61d53cd</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Andy Wang]]></dc:creator>
            <pubDate>Thu, 25 Mar 2021 15:57:38 GMT</pubDate>
            <atom:updated>2021-09-12T19:08:06.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNXdDiQ2e0S0pnW3ib3lXw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nathan Dumlao</a> on <a href="https://unsplash.com/s/photos/similar?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>From Siamese network and Triplet Loss to ArcFace Loss</h4><h3>What is Similarity Learning?</h3><p>A Neural Network can be trained to classify images or predict the prices of certain products, namely classification, and regression. These two methods are commonly used not only in deep learning but across machine learning in general. Instead of classifying images or objects into two categories, <strong>similarity learning</strong> determines if the two objects are in the same category or similar, thus the name “similarity learning”.</p><p>Many fields such as facial verification/identification and recommendation systems utilize similarity learning to achieve their goal. Similarity Learning is mostly applied to images.</p><h3>An Intuitive Understanding</h3><p>When we want to compare two images and decide whether they are similar or not, it’s best to compare their <strong>embeddings</strong> produced by a trained CNN. Simply put, embedding is just vectors extracted from the network that contains important patterns and information learned by the network.</p><p>For example, if we want to compare if a picture of a dog is similar to a cat, we would put the images through the same neural network with the same weights. Then we will take the activation of the last layer before the output layer. The vectors produced are the embedding for the images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afjpbpBlYhMM2CgER5rXVg.png" /><figcaption>Embeddings. <em>Image by author</em></figcaption></figure><p>To compare the differences between the images, we can find the distance between the two vectors. Mathematically, we can compute a distance function of the two vectors as the L2-norm of the difference between the vectors, written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*NvpByJUu_TLIDohHYAM2YA.png" /><figcaption>Created at <a href="https://math.embed.fun/">https://math.embed.fun</a></figcaption></figure><p>Where x1 and x2 are the embeddings of the cat and the dog, respectively. If the two images are similar, which, in this case, they are not, the result should be minimal. However, the result in this case, where the two images are very different, should be larger.</p><p>The concept of comparing two images from their embeddings created by the same neural network is called the <strong>Siamese Network. </strong>We can train the network using<strong> </strong>the<strong> Triplet Loss.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JYrVgVKGvf36fLkm.png" /><figcaption><a href="https://www.mdpi.com/symmetry/symmetry-10-00385/article_deploy/html/images/symmetry-10-00385-g001.png">Source</a></figcaption></figure><h3>Triplet Loss</h3><p>Still using the example of the cats and dogs, let’s call the dog image the <strong>anchor</strong> image or the original image that we will be comparing with. We have our second image of another dog, similar to the first, but slightly different in the details, let’s call this image <strong>positive</strong>. We want the network to classify these two images as the same category. Finally, we have the <strong>negative</strong> image of a cat, which is not in the same category as the dog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v71sJU6_aKEL893zcOwRQQ.png" /><figcaption>Sources: <a href="http://absfreepic.com/free-photos/download/brown-dog-in-wood-house-4288x2848_68272.html">Top left image</a>. <a href="http://absfreepic.com/free-photos/download/brown-dog-lying-front-of-white-background-2835x2126_82078.html">Top right dog image</a>. <a href="http://absfreepic.com/free-photos/download/small-baby-cat-4272x2848_82519.html">Bottom cat image.</a></figcaption></figure><p>For the network to correctly classify if the images belong in the same category, we want the difference between the positive and the anchor to be smaller than the difference between the anchor and the negative. Using the distance function above, we can write this as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*tdHBT3-EONphL9pwsVuuuA.png" /></figure><p>Where A, P, and N represent the embedding vectors of anchor, positive and negative. Moving the terms on to one side, the equation becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*EJ1TKJkXunIbuz0eXVfOcg.png" /></figure><p>However, the network can find a way “around” this function without any actual learning by setting both embedding vectors to zero. To fix this, we can add a “margin” to the equation, call it alpha.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*cOmLeCmHcvI0fLuX5aKwVA.png" /></figure><p>This way, the network cannot find a “trivial” solution to this and has to learn. Formalizing this into a loss function, we will take the max between the computed difference of (A, P), (A, N) (equation above), and 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*EeNjSHKjvYnieoSzzorUIA.png" /></figure><p>Then the loss becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*X1iuweIOVC2PxDvVDvf4WA.png" /></figure><p>The loss will result in zero when the network has discovered a difference between the anchor and the negative. On the other hand, if the network wasn’t able to find the difference between the negative and the anchor, the loss will produce a measure of the error.</p><p>The triplet loss has a couple of disadvantages that should be considered.</p><p>First, it requires a careful selection of the anchor, positive, and negative images. The difference between the negative and the anchor images can’t be too much, if it was, the network will satisfy the loss function easily without learning anything. The anchor and the negative images must be similar but shouldn’t belong in the same class.</p><p>Second, it’s computationally expensive and lastly, the triplet loss requires the hyperparameter alpha, or the margin. it can lead to worse results when not chosen carefully.</p><h3>Alternatives: ArcFace Loss and the Angle Margin Penalty</h3><p>There are many alternatives to the triplet loss, one of them is the <strong>ArcFace Loss</strong>. This is a loss based on the cross-entropy loss aiming to maximize the decision boundary between classes thus grouping similar data points closer together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YV3f-_-jKrVQVcLV0JgV8Q.png" /><figcaption><a href="https://arxiv.org/pdf/1801.07698.pdf">Source</a></figcaption></figure><p>The idea behind ArcFace is that it maximizes the angle between interclass and minimizes the angle between intraclass on a hypersphere. We then add the angular margin penalty which is inserted between the weight of the true logit and the embedding. This adds a angle penalty to the original angle between the logit and the embedding.</p><p>The angle margin penalty helps in penalizing the embedding vectors that goes far and help in bringing the embedding features of a certain class come more closer.</p><p>There are many other losses out there that operates on a similar idea compared to ArcFace, such as SphereFace, CosFace.</p><p>Using the triplet loss with the Siamese Network are early approaches to similarity learning and thus have many problems and disadvantages. On the other hand, ArcFace achieves the goal of maximizing the decision boundary between classes cleverly without wasting computational resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e680c61d53cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/novel-approaches-to-similarity-learning-e680c61d53cd">Novel Approaches to Similarity Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>