<?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 Ander on Medium]]></title>
        <description><![CDATA[Stories by Ander on Medium]]></description>
        <link>https://medium.com/@aaqumon?source=rss-880271f569ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*huY0F7vODNuaZZZ49Ny0Ew.jpeg</url>
            <title>Stories by Ander on Medium</title>
            <link>https://medium.com/@aaqumon?source=rss-880271f569ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:50:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aaqumon/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[Best chunking strategies for RAG (by scratch)]]></title>
            <link>https://aaqumon.medium.com/best-chunking-strategies-for-rag-by-scratch-dd58d375bd65?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd58d375bd65</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 17:04:22 GMT</pubDate>
            <atom:updated>2025-07-07T17:04:22.268Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why Write Chunking Strategies for RAG From Scratch?</strong></h3><p>In the rapidly evolving AI ecosystem, libraries like LangChain have made it incredibly easy to build Retrieval-Augmented Generation (RAG) pipelines. With just a few lines of code, you can ingest documents, chunk them into smaller pieces, and query them using language models to generate contextualized answers. But while these abstractions offer speed and convenience, they can come at a cost.</p><p>Writing your own chunking logic from scratch might seem like unnecessary work at first — but it unlocks a level of flexibility, control, and understanding that high-level libraries often obscure. By building your chunking functions manually, you gain several key advantages:</p><ul><li><strong>Tailored behavior for your specific use case</strong>, whether you need to chunk by token count, semantic boundaries, logical sections, or custom metadata.</li><li><strong>Freedom from third-party dependencies</strong>, making your codebase more portable, maintainable, and future-proof.</li><li><strong>Performance and efficiency optimizations</strong>, since you eliminate layers of abstraction and have full visibility into every step of the pipeline.</li><li><strong>Deeper understanding of how retrieval and generation actually work</strong>, which is essential for debugging, auditing, and improving your system.</li></ul><p>Implementing chunking from scratch isn’t just a technical exercise — it’s an investment in building a more robust, transparent, and adaptable RAG system that fits your exact needs.</p><h3>Best chunking strategies</h3><h4>Character chunking</h4><p><strong>Character chunking</strong> is a technique that divides text into fixed-size sections according to the character count, sometimes with the use of overlapping windows. In RAG pipelines, it’s frequently the earliest and most basic technique.</p><h4>✅<strong><em>Pros</em></strong></h4><ul><li><strong>Simlicity</strong>: It may be applied to any text, regardless of formatting or structure, and is simple to apply.</li><li><strong>Control over chunk size</strong>: Keeping input chunk sizes under control guarantees that queries remain below the token restrictions imposed by various LLM APIs.</li><li><strong>Effective retrieval</strong>: At chunk boundaries, overlapping windows lessen the chance of losing crucial context.</li></ul><h4>⚠️<strong><em>Counts</em></strong></h4><ul><li>It may split sentences or paragraphs in inconvenient places because it doesn’t take the content’s semantics or structure into account.</li><li>More clever techniques, such as semantic chunking or separating by headers, are typically preferable for structured documents (like Markdown or PDFs).</li></ul><pre>def character_chunking(text, chunk_size=500, overlap=50):<br>    &quot;&quot;&quot;<br>    Splits the input text into overlapping chunks based on character count.<br><br>    Args:<br>        text (str): The full text to chunk.<br>        chunk_size (int): The maximum number of characters in each chunk.<br>        overlap (int): Number of overlapping characters between chunks.<br><br>    Returns:<br>        List[str]: A list of text chunks.<br>    &quot;&quot;&quot;<br>    chunks = []<br>    start = 0<br>    text_length = len(text)<br><br>    while start &lt; text_length:<br>        end = start + chunk_size<br>        chunk = text[start:end]<br>        chunks.append(chunk)<br><br>        # Move the start forward by chunk_size - overlap<br>        start += chunk_size - overlap<br><br>    return chunks</pre><h4>Recursive chunking</h4><p><strong>Recursive chunking</strong> consists of dividing the text in order of semantic separators. That is to say, it will be divided starting with paragraphs, followed by line breaks… until all the chunks are of the specified size.</p><h4>✅<strong><em>Pros</em></strong></h4><ul><li><strong>Maintains semantic integrity</strong>: It avoids breaking in the middle of thoughts or logical units, improving chunk coherence.</li><li><strong>Flexible</strong>: You can customize the delimiter hierarchy depending on the data (e.g., Markdown headers, HTML tags).</li></ul><h4>⚠️<strong><em>Counts</em></strong></h4><ul><li>Depending on text quality, recursive chunking may still need post-processing to ensure chunk consistency.</li></ul><pre>def recursive_chunking(text, chunk_size=500, overlap=50, split_levels=None):<br>    &quot;&quot;&quot;<br>    Recursively splits text into chunks by progressively less granular delimiters,<br>    falling back to character-based chunking when necessary.<br><br>    Args:<br>        text (str): The full text to chunk.<br>        chunk_size (int): Maximum number of characters per chunk.<br>        overlap (int): Overlap size between chunks.<br>        split_levels (List[str]): Delimiters to try in order (e.g., [&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;]).<br><br>    Returns:<br>        List[str]: List of chunks.<br>    &quot;&quot;&quot;<br>    if split_levels is None:<br>        # Start from coarse to fine: paragraphs, lines, sentences<br>        split_levels = [&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;]<br><br>    def split_recursively(t, levels):<br>        if len(t) &lt;= chunk_size:<br>            return [t]<br>        if not levels:<br>            # Fallback: simple character chunking<br>            return character_chunking(t, chunk_size, overlap)<br><br>        delimiter = levels[0]<br>        parts = t.split(delimiter)<br>        chunks = []<br>        current = &quot;&quot;<br><br>        for part in parts:<br>            part = part + delimiter  # Keep delimiter context<br>            if len(current) + len(part) &lt;= chunk_size:<br>                current += part<br>            else:<br>                if current:<br>                    chunks.append(current.strip())<br>                if len(part) &gt; chunk_size:<br>                    # If the part is still too big, go deeper<br>                    chunks.extend(split_recursively(part, levels[1:]))<br>                    current = &quot;&quot;<br>                else:<br>                    current = part<br><br>        if current:<br>            chunks.append(current.strip())<br><br>        # Add overlap<br>        if overlap &gt; 0 and len(chunks) &gt; 1:<br>            overlapped_chunks = []<br>            for i in range(len(chunks)):<br>                prev = chunks[i - 1][-overlap:] if i &gt; 0 else &quot;&quot;<br>                overlapped_chunks.append(prev + chunks[i])<br>            return overlapped_chunks<br><br>        return chunks<br><br>    return split_recursively(text, split_levels)</pre><h4>Semantic chunking</h4><p><strong>Semantic chunking</strong> consists of dividing the text into chunks and merging chunks in a row according to the semantic similarity between them.</p><h4>✅ Advantages</h4><ul><li><strong>Highly coherent chunks</strong>: Each chunk contains sentences that <em>belong together</em> contextually, improving retrieval relevance.</li><li><strong>Boosts accuracy in RAG systems</strong>: Because the retrieved chunks contain semantically unified information, the model’s generated outputs are typically more relevant and grounded.</li></ul><h4>⚠️ Trade-offs</h4><ul><li><strong>Performance cost</strong>: Computing embeddings for every sentence can be expensive, especially on large documents.</li><li><strong>Threshold tuning</strong>: The similarity threshold may need tuning per dataset.</li><li><strong>Dependencies</strong>: Requires models like SentenceTransformer and additional NLP tooling like nltk.</li></ul><pre>from sentence_transformers import SentenceTransformer, util<br><br>def semantic_chunking(text, model_name=&#39;all-MiniLM-L6-v2&#39;, chunk_size=500, overlap=50):<br>    &quot;&quot;&quot;<br>    Splits text into semantically meaningful chunks using sentence embeddings.<br><br>    Args:<br>        text (str): Full input text.<br>        model_name (str): Name of the embedding model to use.<br>        chunk_size (int): Approximate target chunk size in characters.<br>        overlap (int): Overlapping characters between chunks for context preservation.<br><br>    Returns:<br>        List[str]: List of semantically grouped chunks.<br>    &quot;&quot;&quot;<br>    import nltk<br>    nltk.download(&#39;punkt&#39;)<br>    from nltk.tokenize import sent_tokenize<br><br>    model = SentenceTransformer(model_name)<br><br>    # Step 1: Split text into sentences<br>    sentences = sent_tokenize(text)<br><br>    chunks = []<br>    current_chunk = &quot;&quot;<br>    for sentence in sentences:<br>        if len(current_chunk) + len(sentence) &lt;= chunk_size:<br>            current_chunk += sentence + &quot; &quot;<br>        else:<br>            # Get embeddings for current chunk and sentence to check semantic continuity<br>            chunk_embedding = model.encode(current_chunk.strip(), convert_to_tensor=True)<br>            sentence_embedding = model.encode(sentence, convert_to_tensor=True)<br>            similarity = util.cos_sim(chunk_embedding, sentence_embedding).item()<br><br>            if similarity &gt; 0.5:<br>                # If semantically similar, include sentence<br>                current_chunk += sentence + &quot; &quot;<br>            else:<br>                chunks.append(current_chunk.strip())<br>                current_chunk = sentence + &quot; &quot;<br><br>    if current_chunk:<br>        chunks.append(current_chunk.strip())<br><br>    # Add overlap (optional, character-based)<br>    if overlap &gt; 0 and len(chunks) &gt; 1:<br>        overlapped_chunks = []<br>        for i in range(len(chunks)):<br>            prev = chunks[i - 1][-overlap:] if i &gt; 0 else &quot;&quot;<br>            overlapped_chunks.append(prev + chunks[i])<br>        return overlapped_chunks<br><br>    return chunks</pre><h4>Markdown chunking</h4><p><strong>Markdown chunking</strong> is a highly effective strategy when working with well-structured content like documentation, technical blogs, or knowledge bases. It respects the natural organization of the content by leveraging Markdown’s native structure (headings, lists, code blocks, etc.), making it ideal for context-preserving chunking.</p><pre>import re<br><br>def markdown_chunking(markdown_text, max_chunk_size=1000, overlap=100):<br>    &quot;&quot;&quot;<br>    Splits a Markdown document into chunks based on header hierarchy.<br><br>    Args:<br>        markdown_text (str): Markdown content as a single string.<br>        max_chunk_size (int): Maximum number of characters per chunk.<br>        overlap (int): Number of overlapping characters between chunks.<br><br>    Returns:<br>        List[str]: A list of chunked sections.<br>    &quot;&quot;&quot;<br>    # Step 1: Split by top-level and sub-level headers (e.g., #, ##, ###)<br>    header_pattern = re.compile(r&#39;^(#{1,6})\s+(.*)&#39;, re.MULTILINE)<br>    sections = []<br>    current_section = {&quot;header&quot;: &quot;&quot;, &quot;content&quot;: &quot;&quot;}<br>    lines = markdown_text.splitlines()<br><br>    for line in lines:<br>        header_match = header_pattern.match(line)<br>        if header_match:<br>            if current_section[&quot;content&quot;]:<br>                sections.append(current_section)<br>            current_section = {<br>                &quot;header&quot;: line.strip(),<br>                &quot;content&quot;: &quot;&quot;<br>            }<br>        else:<br>            current_section[&quot;content&quot;] += line + &quot;\n&quot;<br><br>    if current_section[&quot;content&quot;]:<br>        sections.append(current_section)<br><br>    # Step 2: Combine smaller sections, and chunk large ones further if needed<br>    chunks = []<br>    for section in sections:<br>        text = section[&quot;header&quot;] + &quot;\n&quot; + section[&quot;content&quot;]<br>        if len(text) &lt;= max_chunk_size:<br>            chunks.append(text.strip())<br>        else:<br>            # Fallback: split by paragraphs inside the large section<br>            paragraphs = text.split(&quot;\n\n&quot;)<br>            current_chunk = &quot;&quot;<br>            for para in paragraphs:<br>                if len(current_chunk) + len(para) + 2 &lt;= max_chunk_size:<br>                    current_chunk += para + &quot;\n\n&quot;<br>                else:<br>                    chunks.append(current_chunk.strip())<br>                    current_chunk = para + &quot;\n\n&quot;<br>            if current_chunk:<br>                chunks.append(current_chunk.strip())<br><br>    # Step 3: Add optional overlap<br>    if overlap &gt; 0 and len(chunks) &gt; 1:<br>        overlapped_chunks = []<br>        for i in range(len(chunks)):<br>            prev = chunks[i - 1][-overlap:] if i &gt; 0 else &quot;&quot;<br>            overlapped_chunks.append(prev + chunks[i])<br>        return overlapped_chunks<br><br>    return chunks</pre><h4>🛠 Use Cases</h4><ul><li>Technical documentation (e.g. APIs, DevOps guides)</li><li>Markdown-based knowledge bases (e.g. Notion exports, GitHub repos)</li><li>Structured long-form content like e-books or manuals</li></ul><h4>⚠️ Limitations</h4><ul><li>Markdown parsing assumes consistent header formatting — malformed documents may be missed.</li><li>Large sections still need fallback chunking (e.g., by paragraphs or character length).</li><li>Does not account for meaning — only structure. Combining with semantic chunking can yield even better results.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd58d375bd65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Balancing Non Tabular Data (Data Augmentation)]]></title>
            <link>https://aaqumon.medium.com/balancing-non-tabular-data-data-augmentation-77388cb34fdb?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/77388cb34fdb</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 18:18:02 GMT</pubDate>
            <atom:updated>2024-03-05T18:18:02.650Z</atom:updated>
            <content:encoded><![CDATA[<p>In data analysis and machine learning, the quality and representativeness of the dataset play a key role in the performance and reliability of models. Often, datasets are imbalanced, where one or more categories are significantly outweighs the others. This inherent imbalance can pose significant challenges, leading to biased model predictions and decreased performance on minority classes.</p><p>In other article called <a href="https://medium.com/@anderaquerretamontoro/techniques-for-balancing-tabulated-data-samples-92d2ef102d36"><em>Techniques for Balancing Tabulated Data Samples</em></a><em> </em>we explored the different techniques to deal with imbalanced tabular data. In these article we will see how to balanced non-tabular data like images, text, temporal series… These technique is called Data Augmentation.</p><p>Data augmentation is a technique used in machine learning and computer vision to artificially increase the size of a dataset by applying transformations to the train data. These transformations can include rotations, translations, scaling, flipping, adding noise, or changing brightness and contrast (in case of images). By creating new variations of the original data, data augmentation helps improve the generalization and robustness of machine learning models, reducing overfitting and enhancing performance, especially when training data is limited.</p><h3>Image Data Augmentation</h3><p>For data augmentation on imeges we will use Keras and we will see the most common parameters of that applied on one image.</p><pre>import numpy as np<br>import os<br>import PIL<br>import PIL.Image<br>import tensorflow as tf<br>import tensorflow_datasets as tfds<br>import matplotlib.pyplot as plt<br><br>import pathlib<br>dataset_url = &quot;https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz&quot;<br>data_dir = tf.keras.utils.get_file(origin=dataset_url,<br>                                   fname=&#39;flower_photos&#39;,<br>                                   untar=True)<br>data_dir = pathlib.Path(data_dir)<br><br>roses = list(data_dir.glob(&#39;roses/*&#39;))<br>image_path = str(roses[5])<br><br>img = PIL.Image.open(image_path)<br>plt.imshow(img)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><p>The image we will use is that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*0oqxn0eEyelSs9dNZb9r-Q.png" /><figcaption>Image of a Rose</figcaption></figure><p>These are the constructor of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator">ImageDataGenerator</a>:</p><p><em>tf.keras.preprocessing.image.ImageDataGenerator(<br> featurewise_center=False,<br> samplewise_center=False,<br> featurewise_std_normalization=False,<br> samplewise_std_normalization=False,<br> zca_whitening=False,<br> zca_epsilon=1e-06,<br> rotation_range=0,<br> width_shift_range=0.0,<br> height_shift_range=0.0,<br> brightness_range=None,<br> shear_range=0.0,<br> zoom_range=0.0,<br> channel_shift_range=0.0,<br> fill_mode=’nearest’,<br> cval=0.0,<br> horizontal_flip=False,<br> vertical_flip=False,<br> rescale=None,<br> preprocessing_function=None,<br> data_format=None,<br> validation_split=0.0,<br> interpolation_order=1,<br> dtype=None<br>)</em></p><h4>Rotation Range</h4><p>Degree range for random rotations. Creates a new image with a random rotation between -<em>rotation_range </em>and <em>rotation_range </em>degrees.</p><pre>img = PIL.Image.open(image_path)<br><br>img_array = np.array(img)<br><br>data_augmentation = tf.keras.preprocessing.image.ImageDataGenerator(<br>    rotation_range = 40,<br>)<br><br>transformed_image = data_augmentation.random_transform(img_array)<br><br>plt.imshow(transformed_image)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*Y0KMkRx9ywRTaNUQ2ym0Sg.png" /><figcaption>Image of a Rose with random rotation</figcaption></figure><h4>Brightness Range</h4><p>Tuple or list of two floats. Range for picking a brightness shift value from.</p><pre>data_augmentation = tf.keras.preprocessing.image.ImageDataGenerator(<br>    brightness_range=[0.5, 1.5]<br>)<br><br>transformed_image = data_augmentation.random_transform(img_array)<br>transformed_image = transformed_image / 255<br><br>plt.imshow(transformed_image)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*qPtPdRr25rlvH8kD60VvpQ.png" /><figcaption>Image of a Rose changing brightness</figcaption></figure><h4>Zoom range</h4><p>Float or [lower, upper]. Range for random zoom. If a float, <em>[lower, upper] = [1-zoom_range, 1+zoom_range].</em></p><pre>data_augmentation = tf.keras.preprocessing.image.ImageDataGenerator(<br>    zoom_range=[0.5, 1.5]<br>)<br><br>transformed_image = data_augmentation.random_transform(img_array)<br>transformed_image = transformed_image / 255<br><br>plt.imshow(transformed_image)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*_pKbv6n9u6fS9sYlPfbJlw.png" /><figcaption>Image of a Rose aplying zoom</figcaption></figure><h4>Flip (horizontal or vertical)</h4><p>Boolean. Randomly flip inputs horizontally.</p><pre>data_augmentation = tf.keras.preprocessing.image.ImageDataGenerator(<br>    vertical_flip = 0.5<br>)<br><br>transformed_image = data_augmentation.random_transform(img_array)<br>transformed_image = transformed_image / 255<br><br>plt.imshow(transformed_image)<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*3w6fUJnaaySIL6t_EFBovg.png" /><figcaption>Image of a Rose with Verical Flip</figcaption></figure><h3>NLP Data Augmentation</h3><p>Data augmentation plays key role in enhancing the performance and robustness of machine learning models in Natural Language Processing (NLP). By generating diverse variations of the original text data, data augmentation helps to overcome limitations posed by limited training data. Techniques like synonym replacement, random insertion, deletion, and swapping introduce variations in the text, effectively expanding the training dataset. This not only helps in improving the model’s ability to generalize to unseen data but also makes it more resilient to noise and variations in input.</p><p>We will use as input the sentence <em>I don’t want to play again with you </em>to see the new syntetic sentences generated by data augmentation techniques.</p><h4>Back translation</h4><p>These techniques is based on translate the input sentence to a other or others language and then translate back to the original language. We will use the neural translator Marian.</p><pre>from transformers import MarianMTModel, MarianTokenizer<br><br>model_name = &#39;Helsinki-NLP/opus-mt-en-es&#39;<br>tokenizer = MarianTokenizer.from_pretrained(model_name)<br>model = MarianMTModel.from_pretrained(model_name)<br><br>text_to_translate = &quot;I don&#39;t want to play again with you.&quot;<br><br>inputs = tokenizer(text_to_translate, return_tensors=&quot;pt&quot;, truncation=True, padding=True)<br><br>translated_ids = model.generate(**inputs)<br><br>translated_text = tokenizer.batch_decode(translated_ids, skip_special_tokens=True)[0]<br><br>print(&quot;Spanish:&quot;, translated_text)<br><br>model_name = &#39;Helsinki-NLP/opus-mt-es-en&#39;<br>tokenizer = MarianTokenizer.from_pretrained(model_name)<br>model = MarianMTModel.from_pretrained(model_name)<br><br>text_to_translate = translated_text<br><br>inputs = tokenizer(text_to_translate, return_tensors=&quot;pt&quot;, truncation=True, padding=True)<br><br>translated_ids = model.generate(**inputs)<br><br>translated_text = tokenizer.batch_decode(translated_ids, skip_special_tokens=True)[0]<br><br>print(&quot;English Back:&quot;, translated_text)</pre><p>The results are:</p><ul><li>Spanish: <em>No quiero volver a jugar contigo.</em></li><li>English Back: <em>I don’t want to play with you again.</em></li></ul><h4><strong>Synonym Replacement</strong></h4><p>The approach involves replacing words in a sentence with their synonyms while preserving the overall meaning of the sentence. These technique helps generating new training examples that retain the original context but introduce variations in the choice of words.</p><p>Here’s how Synonym Replacement works in practice:</p><ol><li>Tokenize the input text into words or subwords.</li><li>Identify candidate words in the sentence that can be replaced with synonyms. We can evaluate these candidates with any distance function like cosine.</li><li>For each candidate word, retrieve its synonyms from the lexical resource.</li><li>Replace the word with one of its synonyms randomly to generate a new sentence.</li><li>Repeat the process for multiple words in the sentence to generate a set of augmented examples.</li></ol><p>For example, consider the sentence:</p><ul><li>Original: <em>“The cat is sleeping on the mat.”</em></li></ul><p>After applying Synonym Replacement, it could become:</p><ul><li>Augmented: <em>“The feline is sleeping on the mat.”</em></li></ul><p>In this example, “cat” was replaced with its synonym “feline,” while the rest of the sentence remained unchanged.</p><h3>Time Series Augmentation</h3><p>While traditionally associated with image data, data augmentation is equally important in the domain of time series analysis. Time series data, which consists of observations collected over time, often present challenges such as limited availability of labeled data, noise, and variations in data distribution.</p><p>In this context, data augmentation for time series involves generating synthetic data by applying transformations to the original time series. These transformations aim to simulate variations and introduce diversity in the data, enabling machine learning models to learn more effectively and generalize better.</p><p>We will explore three common data augmentation techniques for time series data: time warping, adding noise, and data interpolation. These techniques will be applied to synthetic time series data, allowing us to observe their effects on the data and evaluate their potential benefits in improving the performance of machine learning models. Through experimentation with synthetic data, we can gain insights into how these augmentation techniques can be effectively utilized in real-world scenarios with actual time series datasets.</p><h4>Time warping</h4><p>It involves modifying the time axis of a time series by stretching or compressing it, effectively changing the speed at which events occur while preserving the underlying patterns in the data.</p><pre>def time_warping(t, y, scale_factor):<br>    t_warped = t * scale_factor<br>    f = interp1d(t_warped, y, kind=&#39;linear&#39;, fill_value=&#39;extrapolate&#39;)<br>    t_new = np.linspace(min(t_warped), max(t_warped), len(t))<br>    y_warped = f(t_new)<br>    return t_new, y_warped<br><br>scale_factor = 0.9 + np.random.rand() * 0.2<br>t_warped, y_warped = time_warping(t, y, scale_factor)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*AE8MiPflBfkzBUHFe_PcWA.png" /><figcaption>Plot of Time Series Augmentation with Time Warping</figcaption></figure><h4>Adding Gaussian Noise</h4><p>The technique is based on adding gaussian noise to the original time series to help with the robustness of the model.</p><pre>def add_noise(y, noise_level):<br>    noise = np.random.normal(0, noise_level, len(y))<br>    y_noisy = y + noise<br>    return y_noisy<br><br>noise_level = 0.05<br>y_noisy = add_noise(y, noise_level)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*0aq1JpZlZgE6zs62C2f4PA.png" /><figcaption>Plot of Time Series Augmentation adding Gaussian Noise</figcaption></figure><h4>Data interpolation</h4><p>Is a technique used to fill in missing values in a time series by estimating the values based on the existing data points.</p><pre>def data_interpolation(t, y, missing_ratio):<br>    mask = np.random.choice([True, False], size=len(y), p=[1-missing_ratio, missing_ratio])<br>    t_missing = t[mask]<br>    y_missing = y[mask]<br>    f = interp1d(t_missing, y_missing, kind=&#39;linear&#39;, fill_value=&#39;extrapolate&#39;)<br>    y_interpolated = f(t)<br>    return y_interpolated<br><br>missing_ratio = 0.1<br>y_interpolated = data_interpolation(t, y, missing_ratio)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyCPUBNT8Wm3vdn7j3afQg.png" /><figcaption>Plot of Time Series Augmentation with Data Interpolation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77388cb34fdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Techniques for Balancing Tabulated Data Samples]]></title>
            <link>https://aaqumon.medium.com/techniques-for-balancing-tabulated-data-samples-92d2ef102d36?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/92d2ef102d36</guid>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 18:04:20 GMT</pubDate>
            <atom:updated>2024-03-01T18:04:20.335Z</atom:updated>
            <content:encoded><![CDATA[<p>In data analysis and machine learning, the quality and representativeness of the dataset play a key role in the performance and reliability of models. Often, datasets are imbalanced, where one or more categories are significantly outweighs the others. This inherent imbalance can pose significant challenges, leading to biased model predictions and decreased performance on minority classes.</p><p>In this article, we delve into the techniques and strategies employed to address the issue of imbalanced datasets, focusing particularly on tabulated data. We will explore all these tecniques from the python library imblearn. In order to show that we will use these syntetic data:</p><pre>import dataset as ds<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>from sklearn.datasets import make_classification<br>from collections import Counter<br><br>import imblearn.under_sampling as us<br>import imblearn.over_sampling as os<br>import imblearn.combine as hib</pre><pre>X, y = make_classification(n_samples = 500, n_features = 2, n_informative = 2, n_redundant = 0, n_clusters_per_class = 1, n_classes = 2, class_sep = 0.5, weights = [0.1,0.9], random_state = 10)<br><br>negativeClass = y == 1<br>positiveClass = y == 0<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X[negativeClass,0], X[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X[positiveClass,0], X[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Q1fhWg8WkJ9_gHPIn3nhvA.png" /><figcaption>Plot of the syntetic data</figcaption></figure><h3>Simple Tecniques</h3><h4>Random Under Sampler (RUS)</h4><p>R<a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.RandomUnderSampler.html">US</a> is a technique for balancing imbalanced datasets by randomly reducing examples from the majority class until the class samples are more equitable.</p><p><em>rus = RandomUnderSampler(sampling_strategy=estrategy, random_state=seed,replacement=repl)</em></p><p>The input parameters of the method are:</p><p>-<strong>strategy</strong>: determines how the resampling is performed. It can take various values:</p><ul><li><em>Real number (between 0 and 1)</em>: determines the ratio between the number of examples of the minority class over the majority class after resampling.</li><li><em>String</em>: determines the class to be resampled. The options are:</li><li>‘majority’: resamples only the majority class.</li><li>‘not minority’: resamples all classes except the minority class.</li><li>‘not majority’: resamples all classes except the majority class.</li><li>‘all’: resamples all classes.</li><li>‘auto’: equivalent to ‘not minority’. Default option.</li><li><em>Dictionary</em>: determines the number of examples (value) to obtain after applying resampling for each class (key).</li></ul><p>-<strong>seed</strong>: random seed.</p><p><strong>-replacement</strong>: boolean value that determines whether sampling is done with replacement or not. It defaults to False.</p><pre>rus = us.RandomUnderSampler(random_state = 42,replacement = False)<br>X_sampled, y_sampled = rus.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*5jyKa4XedXfzkiKWl9jwmg.png" /><figcaption>Plot of syntetic data after RUS</figcaption></figure><h4>Tomek Links</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.TomekLinks.html">Tomek links</a> is a technique for identifying and removing pairs of instances that are close to each other but belong to different classes, aiming to clarify the decision boundary and improve the separation between classes in imbalanced datasets.</p><p><em>TomekLinks(sampling_strategy=strategy)</em></p><p>The input parameters of the method are:</p><ul><li><strong>strategy string</strong>: Same as RUS</li></ul><pre>tl = us.TomekLinks()<br>X_sampled, y_sampled = tl.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()CondensedNearestNeighbour(sampling_strategy=estrategia, n_neighbors=numeroVecinos, random_state=semilla)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*f8zTNXn74gGVcXoPSTR4cw.png" /><figcaption>Plot of syntetic data after Tomek Links</figcaption></figure><h4>Condensed Nearest Neighbour (CNN)</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.CondensedNearestNeighbour.html">CNN</a> is a technique that aims to condense a dataset by iteratively removing redundant instances while preserving the classification structure.</p><p><em>CondensedNearestNeighbour(sampling_strategy=strategy, n_neighbors=neig, random_state=seed)</em></p><p>The new arguments are:</p><ul><li><strong>n_neighbors</strong>: Number of neighbors considered.</li></ul><pre>cnn = us.CondensedNearestNeighbour(random_state = 42)<br>X_sampled, y_sampled = cnn.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*HZ4nP4eze8h_2MGYTd_qUQ.png" /><figcaption>Plot of syntetic data after CNN</figcaption></figure><p><strong>One Sided Selection (OSS)</strong></p><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.OneSidedSelection.html">OSS</a> is a technique used to balance imbalanced datasets by removing majority class examples that are close to minority class examples.</p><p><em>OneSidedSelection(sampling_strategy=strategy, n_neighbors=neig, random_state=seed)</em></p><pre>oss = us.OneSidedSelection(random_state = 42)<br>X_sampled, y_sampled = oss.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*Qi4wIs1AX5vWA4IKwg1mFg.png" /><figcaption>Plot of syntetic data after OSS</figcaption></figure><h4>Neighbourhood Cleaning Rule (NCL)</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.NeighbourhoodCleaningRule.html">NCL</a> is a technique that identifies and removes instances from the majority class whose class label differs from the majority class of their nearest neighbors.</p><p><em>NeighbourhoodCleaningRule(sampling_strategy=strategy, n_neighbors=neig)</em></p><pre>ncl = us.NeighbourhoodCleaningRule()<br>X_sampled, y_sampled = ncl.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*XA5oh8Xp4xibWd1EBvhWDg.png" /><figcaption>Plot of syntetic data after NCL</figcaption></figure><h4>Random Over Sampler (ROS)</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.RandomOverSampler.html">ROS</a> is a technique used to balance imbalanced datasets by randomly duplicating instances from the minority class until a more equitable class distribution is achieved.</p><p><em>RandomOverSampler(sampling_strategy=strategy, random_state=seed)</em></p><pre>ros = os.RandomOverSampler(random_state = 42)<br>X_sampled, y_sampled = ros.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*uyleMsIYvPol2gstdubbjw.png" /><figcaption>Plot of syntetic data after ROS</figcaption></figure><h4>SMOTE</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.SMOTE.html">SMOTE</a> (Synthetic Minority Over-sampling Technique) is a method used to fix class imbalance by generating synthetic instances for the minority class based on the characteristics of existing minority class instances.</p><p><em>SMOTE(sampling_strategy=strategy, n_neighbors=neig, random_state=seed)</em></p><pre>smote = os.SMOTE(random_state = 42)<br>X_sampled, y_sampled = smote.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*_8HLJt938ydkB15gmkO7Rg.png" /><figcaption>Plot of syntetic data after SMOTE</figcaption></figure><h3>Combined Tecniques</h3><h4>Smote + Tomek Links</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.combine.SMOTETomek.html">SMOTE + Tomek Links</a> is a hybrid technique that combines SMOTE, which synthesizes minority class instances, with Tomek Links, which removes instances close to the decision boundary.</p><p><em>SMOTETomek(sampling_strategy=strategy, random_state=seed)</em></p><pre>smoteTomek = hib.SMOTETomek(random_state = 42)<br>X_sampled, y_sampled = smoteTomek.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*2IjJLRJFP9OR5loy1F3zLg.png" /><figcaption>Plot of syntetic data after SMOTE + Tomek Links</figcaption></figure><h4>SMOTE + ENN</h4><p><a href="https://imbalanced-learn.org/stable/references/generated/imblearn.combine.SMOTEENN.html">SMOTE + ENN</a> (Edited Nearest Neighbors) is a hybrid technique that combines SMOTE, which synthesizes minority class instances, with ENN, which removes noisy instances from the majority class.</p><p><em>SMOTEENN(sampling_strategy=strategy, random_state=seed)</em></p><pre>smoteEnn = hib.SMOTEENN(random_state = 42)<br>X_sampled, y_sampled = smoteEnn.fit_resample(X, y)<br><br>negativeClass = y_sampled == 1<br>positiveClass = y_sampled == 0<br><br>print(Counter(y))<br>print(Counter(y_sampled))<br><br>plt.figure(figsize=(10,6))<br>plt.scatter(X_sampled[negativeClass,0], X_sampled[negativeClass,1], marker=&#39;_&#39;, c=&#39;c&#39;, linewidth=2, s=60, label=&#39;Negative Class&#39;)<br>plt.scatter(X_sampled[positiveClass,0], X_sampled[positiveClass,1], marker=&#39;+&#39;, c=&#39;r&#39;, s=60, linewidth=2, label=&#39;Positive Class&#39;)<br>plt.xlabel(&#39;X1&#39;)<br>plt.ylabel(&#39;X2&#39;)<br>plt.legend(frameon= True, fancybox = True, loc=2)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*nvZZzeDWuETSUYkki_U4BQ.png" /><figcaption>Plot of syntetic data after SMOTE + ENN</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92d2ef102d36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The best CNN for CIFAR10 from scratch (93% accuracy)]]></title>
            <link>https://aaqumon.medium.com/the-best-cnn-for-cifar10-from-scratch-93-accuracy-bde35e17fca6?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde35e17fca6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cifar-10]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 08:26:41 GMT</pubDate>
            <atom:updated>2024-02-18T08:26:41.293Z</atom:updated>
            <content:encoded><![CDATA[<p>The objective of this practice is to improve the accuracy of CIFAR10 as much as possible, specifically we want to exceed 92%. To do this, we are going to use CNNs and techniques such as learning rate annealing and data augmentation.</p><pre>import torch<br>import torchvision<br>import torch.nn as nn<br>from tqdm import tqdm<br>import multiprocessing<br>import torch.optim as optim<br>import torch.nn.functional as  F<br>from torch.utils.data import Dataset<br>from torch.utils.data import DataLoader<br>from torchvision import transforms<br><br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>print(&quot;Device: &quot;, device)</pre><pre>## Data augmentation<br><br>train_transform = transforms.Compose([<br>  transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),  # Ajustes aleatorios de brillo, contraste, saturación y tono<br>    transforms.RandomPerspective(distortion_scale=0.5, p=0.5),<br>    transforms.RandomHorizontalFlip(p=0.5),<br>    transforms.ToTensor(),<br>])<br><br>test_transform = transforms.Compose([<br>    transforms.ToTensor(),<br>])</pre><pre>## Dataset class<br><br>class CIFAR10_dataset(Dataset):<br><br>    def __init__(self, partition = &quot;train&quot;, transform = None):<br><br>        print(&quot;\nLoading CIFAR10 &quot;, partition, &quot; Dataset...&quot;)<br>        self.partition = partition<br>        self.transform = transform<br>        if self.partition == &quot;train&quot;:<br>            self.data = torchvision.datasets.CIFAR10(&#39;.data/&#39;,<br>                                                     train=True,<br>                                                     download=True)<br>        else:<br>            self.data = torchvision.datasets.CIFAR10(&#39;.data/&#39;,<br>                                                     train=False,<br>                                                     download=True)<br>        print(&quot;\tTotal Len.: &quot;, len(self.data), &quot;\n&quot;, 50*&quot;-&quot;)<br><br>    def from_pil_to_tensor(self, image):<br>        return torchvision.transforms.ToTensor()(image)<br><br>    def __len__(self):<br>        return len(self.data)<br><br>    def __getitem__(self, idx):<br><br>        # Image<br>        image = self.data[idx][0]<br>        image_tensor = self.transform(image)<br><br>        # Label<br>        label = torch.tensor(self.data[idx][1])<br>        label = F.one_hot(label, num_classes=10).float()<br><br>        return {&quot;img&quot;: image_tensor, &quot;label&quot;: label}<br><br>train_dataset = CIFAR10_dataset(partition=&quot;train&quot;, transform=train_transform)<br>test_dataset = CIFAR10_dataset(partition=&quot;test&quot;, transform=test_transform)<br><br>batch_size = 100<br>num_workers = multiprocessing.cpu_count()-1<br>print(&quot;Num workers&quot;, num_workers)<br>train_dataloader = DataLoader(train_dataset, batch_size, shuffle=True, num_workers=num_workers)<br>test_dataloader = DataLoader(test_dataset, batch_size, shuffle=False, num_workers=num_workers)</pre><pre>## Define the CNN model<br>class AdvancedCNN(nn.Module):<br>    def __init__(self, num_classes=10):<br>        super(AdvancedCNN, self).__init__()<br><br>        self.conv1 = nn.Conv2d(in_channels=3, out_channels=32 * 2, kernel_size=3, padding=1)<br>        self.conv2 = nn.Conv2d(in_channels=32 * 2, out_channels=64 * 2, kernel_size=3, padding=1)<br>        self.conv3 = nn.Conv2d(in_channels=64 * 2, out_channels=64 * 2, kernel_size=3, padding=1)<br>        self.conv4 = nn.Conv2d(in_channels=64 * 2, out_channels=128 * 2, kernel_size=3, padding=1)<br>        self.conv5 = nn.Conv2d(in_channels=128 * 2, out_channels=128 * 2, kernel_size=3, padding=1)<br>        self.conv6 = nn.Conv2d(in_channels=128 * 2, out_channels=128 * 2, kernel_size=3, padding=1)<br>        self.conv7 = nn.Conv2d(in_channels=128 * 2, out_channels=256 * 2, kernel_size=3, padding=1)<br>        self.conv8 = nn.Conv2d(in_channels=256 * 2, out_channels=256 * 2, kernel_size=3, padding=1)<br>        self.conv9 = nn.Conv2d(in_channels=256 * 2, out_channels=256 * 2, kernel_size=3, padding=1)<br><br>        self.bn1 = nn.BatchNorm2d(32 * 2)<br>        self.bn2 = nn.BatchNorm2d(128 * 2)<br>        self.bn3 = nn.BatchNorm2d(256 * 2)<br><br>        self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)<br>        self.dropout = nn.Dropout2d(0.2)<br><br>        self.fc1 = nn.Linear(4096 * 2, 4096 * 2)<br>        self.fc2 = nn.Linear(4096 * 2, 2048 * 2)<br>        self.fc3 = nn.Linear(2048 * 2, num_classes)<br>        self.relu = nn.ReLU()<br><br>    def forward(self, x):<br><br>        x = self.relu(self.bn1(self.conv1(x)))<br>        x = self.relu(self.conv2(x))<br>        x = self.relu(self.conv3(x))<br>        x = self.maxpool(x)<br><br>        x = self.relu(self.bn2(self.conv4(x)))<br>        x = self.relu(self.conv5(x))<br>        x = self.relu(self.conv6(x))<br>        x = self.maxpool(x)<br>        x = self.dropout(x)<br><br>        x = self.relu(self.bn3(self.conv7(x)))<br>        x = self.relu(self.conv8(x))<br>        x = self.relu(self.conv9(x))<br>        x = self.maxpool(x)<br>        x = self.dropout(x)<br><br>        x = torch.flatten(x, start_dim=1)<br>        x = self.relu(self.fc1(x))<br>        x = self.relu(self.fc2(x))<br>        x = self.dropout(x)<br>        x = self.fc3(x)<br>        return x<br><br><br># Instantiating the network and printing its architecture<br>num_classes = 10<br>net = AdvancedCNN(num_classes)<br>print(net)<br><br>def count_parameters(model):<br>    return sum(p.numel() for p in model.parameters() if p.requires_grad)<br>print(&quot;Params: &quot;, count_parameters(net))</pre><pre># Training hyperparameters<br>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.SGD(net.parameters(), lr=0.01, weight_decay=1e-6, momentum=0.9)<br>lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.1, patience=10, min_lr=0.00001)<br>epochs = 100<br><br># Load model in GPU<br>net.to(device)<br><br>print(&quot;\n---- Start Training ----&quot;)<br>best_accuracy = -1<br>best_epoch = 0<br>for epoch in range(epochs):<br><br><br>    # TRAIN NETWORK<br>    train_loss, train_correct = 0, 0<br>    net.train()<br>    with tqdm(iter(train_dataloader), desc=&quot;Epoch &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>        for batch in tepoch:<br><br>            # Returned values of Dataset Class<br>            images = batch[&quot;img&quot;].to(device)<br>            labels = batch[&quot;label&quot;].to(device)<br><br>            # zero the parameter gradients<br>            optimizer.zero_grad()<br><br>            # Forward<br>            outputs = net(images)<br>            loss = criterion(outputs, labels)<br><br>            # Calculate gradients<br>            loss.backward()<br><br>            # Update gradients<br>            optimizer.step()<br><br>            # one hot -&gt; labels<br>            labels = torch.argmax(labels, dim=1)<br>            pred = torch.argmax(outputs, dim=1)<br>            train_correct += pred.eq(labels).sum().item()<br><br>            # print statistics<br>            train_loss += loss.item()<br><br>    train_loss /= (len(train_dataloader.dataset) / batch_size)<br><br>    # TEST NETWORK<br>    test_loss, test_correct = 0, 0<br>    net.eval()<br>    with torch.no_grad():<br>      with tqdm(iter(test_dataloader), desc=&quot;Test &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>          for batch in tepoch:<br><br>            images = batch[&quot;img&quot;].to(device)<br>            labels = batch[&quot;label&quot;].to(device)<br><br>            # Forward<br>            outputs = net(images)<br>            test_loss += criterion(outputs, labels)<br><br>            # one hot -&gt; labels<br>            labels = torch.argmax(labels, dim=1)<br>            pred = torch.argmax(outputs, dim=1)<br><br>            test_correct += pred.eq(labels).sum().item()<br><br>    lr_scheduler.step(test_loss)<br><br>    test_loss /= (len(test_dataloader.dataset) / batch_size)<br>    test_accuracy = 100. * test_correct / len(test_dataloader.dataset)<br><br>    print(&quot;[Epoch {}] Train Loss: {:.6f} - Test Loss: {:.6f} - Train Accuracy: {:.2f}% - Test Accuracy: {:.2f}%&quot;.format(<br>        epoch + 1, train_loss, test_loss, 100. * train_correct / len(train_dataloader.dataset), test_accuracy<br>    ))<br><br>    if test_accuracy &gt; best_accuracy:<br>        best_accuracy = test_accuracy<br>        best_epoch = epoch<br><br>        # Save best weights<br>        torch.save(net.state_dict(), &quot;best_model.pt&quot;)<br><br>print(&quot;\nBEST TEST ACCURACY: &quot;, best_accuracy, &quot; in epoch &quot;, best_epoch)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFl9kHJWpuquhLCgYbSyJw.png" /><figcaption>Final results of the training</figcaption></figure><p>In conclusion, we have been testing different modifications and seeing how our accuracy varied with them. At first we modify our initial network by adding more convolutional and linear layers. With this we saw that the net improved a lot, but at the same time it overtrained too much.</p><p>Seeing this, we tried adding dropout and our results worsened, but I overtrained less and less each time. Finally, inspired by the VGG16 architecture, we decided to add more convolutional layers and fewer poolings. With these changes we already achieved a network that did not overfit. However, we did not exceed 85% accuracy.</p><p>Once we have obtained this network that does not overfit, we add the data augmentation. As filters I decided to add color variations (cifar10 are color images) and horizontal flips. With these changes and the addition of LR annealing we achieved our goal of 92% at epoch 50. Finally, we reached 93,62% accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde35e17fca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tunning in colab with keras to image clasification]]></title>
            <link>https://aaqumon.medium.com/fine-tunning-in-colab-with-keras-to-image-clasification-106d9f99aa7c?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/106d9f99aa7c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 11:22:23 GMT</pubDate>
            <atom:updated>2023-12-26T11:22:23.181Z</atom:updated>
            <content:encoded><![CDATA[<p>In deep learning, fine-tuning is <strong>a</strong> transfer learning approach where the weights of a pre-trained model are trained with new data. Fine-tuning can be done on the entire neural network or only on a subset of its layers, in which case the layers that are not fine-tuned are <strong>“</strong>frozen<strong>”.</strong> (not updated during backpropagation phase). The model can also be completed with “adapters” which consist of much smaller parameters than the original model and are fine-tunned in an efficient way by adjusting the weights of the adapters and leaving the rest of the weights of the model frozen.</p><p>In keras we have several trained network architectures, they can be seen on this <a href="https://www.tensorflow.org/api_docs/python/tf/keras/applications">website</a> such as resnet, densenet or mobilenet.</p><h3><strong>Python code</strong></h3><p>First of all, we need to create a function that delete the last layers of the net to join our needly layers to train the dataset.</p><pre>import tensorflow as tf<br><br>def create_finetuned_model(base_model, num_classes):<br>    model = keras.Sequential([<br>        base_model,<br>        tf.keras.layers.Flatten(),<br>        tf.keras.layers.Dense(512, activation=&#39;relu&#39;),<br>        tf.keras.layers.Dense(256, activation=&#39;relu&#39;),<br>        tf.keras.layers.Dense(64, activation=&#39;relu&#39;),<br>        tf.keras.layers.Dense(num_classes, activation=&#39;softmax&#39;)<br>    ])<br>    return model</pre><p>Then we have to download the nets with the pretrained weights. For example, we will use VGG16. We have to adjust the input and output (num_classes) shape to our data.</p><pre># Cargamos modelos pre-entrenados<br>num_clases = 10<br>vgg16_base = tf.keras.applications.VGG16(weights=&#39;imagenet&#39;, include_top=False, input_shape=(32, 32, 3))<br>vgg16_model = create_finetuned_model(vgg16_base, num_clases)</pre><p>Now we can train the model.</p><pre># Entrenamos VGG16<br>vgg16_model.compile(optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[ &#39;accuracy&#39;])<br>vgg_history = vgg16_model.fit(x_train_cifar, y_train_cifar, batch_size=64, epochs=20, validation_data=(x_val_cifar, y_val_cifar))<br><br># Evalúa el modelo en el conjunto de prueba<br>test_loss, test_accuracy = vgg16_model.evaluate(x_test_cifar, y_test_cifar)<br>print(f&#39;Test loss: {test_loss}, Test accuracy: {test_accuracy}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*AwwTkQbOwIYSRPebM8w1Ww.png" /><figcaption>Plot about the accuracy on validation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=106d9f99aa7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimization of logistic centers with genetic algorithm in python (with code)]]></title>
            <link>https://aaqumon.medium.com/optimization-of-logistic-centers-with-genetic-algorithm-in-python-with-code-716d6fbfb76e?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/716d6fbfb76e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 12:20:23 GMT</pubDate>
            <atom:updated>2023-12-24T12:20:23.968Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Description of the problem</strong></h3><p>A retail chain with a presence in all Spanish provincial capitals wishes to determine the location for its logistics centers for storage and distribution of goods. The logistics centers cannot serve commercial centers located at a distance of more than 300 km.</p><p>Decide in which provincial capitals the logistics centers should be located to minimize their number and which commercial centers (provinces) should be assigned to each logistics center to minimize the distance traveled by transport to supply. It will be assumed that the distance from the logistics center to the shopping centers in the same capital city is zero and that the number of trips required to supply the shopping centers in other provinces is proportional to the population of the destination province.</p><p>Study how the best solution depends on the logistic capacity of the center, that is, on the value of the population P that can be served by a logistic center. A file is provided with the locations and distances between the provincial capitals and a file with the population and location of each province.</p><p>In summary, our objective in this problem is to minimize the number of logistics centers needed to supply all the Spanish peninsular provinces while minimizing the total distance. To do this we must make use of optimization algorithms such as genetic algorithms.</p><h4>Solution representation</h4><p>We will define two variables that we will use to optimize our problem. One of them will be d_ij, which represents the distance between province i and province j, and a binary variable X_i which takes the value 1 when province i contains logistics center.</p><p>Our objective is to minimize both variables, taking into account that the variable X is much more relevant than d. So the variable d will only come into play to tie solutions with the same number of logistic centers. To achieve this, we will have to penalize this secondary objective, as will be seen in the fitness function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*ceuuzpkbplBsjyDFoGFziw.png" /><figcaption>Fitness function</figcaption></figure><p>To represent a solution, therefore, we will have to store the two variables. Each solution will be a vector in which each component represents a province (sorted in alphabetical order). The value of each component will be a list, in which the first value is a binary variable in which 1 represents that the province contains a logistics center and 0 if it does not. The second value will be a string of the province with a logistics center from which it is supplied.</p><h3>Python code</h3><p>We will need some functions and librarys before defining the genetic algorithm.</p><pre>import pandas as pd<br>import numpy as np<br>from collections import defaultdict<br>import matplotlib.pyplot as plt<br>import time<br>import random<br>import copy<br><br>np.random.seed(123)<br>random.seed(123)<br><br>archivo = &#39;./distancia entre ciudades, localización y población.xlsx&#39;<br>df = pd.read_excel(archivo, sheet_name = &#39;Distancia entre capitales&#39;, index_col = 0)<br>dl = pd.read_excel(archivo, sheet_name = &#39;Localización de ciudades&#39;)<br><br>NUM_CIUDADES = 47<br>MAX_DISTANCIA = 300<br><br>ciudades = sorted(list(df.columns))<br>#Creación matriz de distancias<br>distance_matrix = defaultdict(dict)<br>for ka in ciudades:<br>    for kb in ciudades:<br>        distance_matrix[ka][kb] = df.loc[ka,kb]<br><br>index_ciudades = {}<br>for num in range(0, NUM_CIUDADES):<br>    index_ciudades[num] = ciudades[num]<br><br>ciudades_index = {}<br>i = 0<br>for ciudad in ciudades:<br>    ciudades_index[ciudad] = i<br>    i += 1<br><br>ciudades_cercanas = {}<br><br>for ciudad in distance_matrix.keys():<br>    if ciudad not in ciudades_cercanas.keys():<br>        ciudades_cercanas[ciudad] = []<br>        <br>    for ciud in distance_matrix[ciudad].keys():<br>        if distance_matrix[ciudad][ciud] &lt; 300:<br>            ciudades_cercanas[ciudad].append(ciud)<br><br>## Generamos un individuo que sera que cada ciudad tiene un centro logistico y se abastece a sí misma<br>solPrueba = []<br><br>for ciudad in ciudades:<br>    componente = [1, ciudad]<br>    solPrueba.append(componente)<br>solPrueba<br><br>def funcion_fitness(individuo, distance_matrix):<br>    numCentros = 0<br>    distanciaTot = 0<br>    <br>    i = 0<br>    for ciudad in individuo:<br>        ciudadIndex = index_ciudades[i]<br>        numCentros += ciudad[0]<br>        distanciaTot += distance_matrix[ciudadIndex][ciudad[1]]<br>        i += 1<br>    return numCentros + (1/100000) * distanciaTot<br>funcion_fitness(solPrueba, distance_matrix)<br><br>def verificar_factibilidad(solucion, distance_matrix):<br><br>    num_ciudades = len(solucion)<br>    centros_logisticos = [index_ciudades[i] for i, (tiene_centro, _) in enumerate(solucion) if tiene_centro == 1]<br>    <br>    ciu = 0<br>    for ciudad in solucion:<br>        if (ciudad[1] in centros_logisticos) and distance_matrix[index_ciudades[ciu]][ciudad[1]] &gt; 300:<br>            return False  # Condición de distancia no cumplida<br>        ciu += 1<br>    <br>    # Verificar que cada ciudad tiene asignada una ciudad con centro logístico<br>    for ciudad in solucion:<br>        if ciudad[1] not in centros_logisticos:<br>            return False  # Condición no cumplida<br><br>    return True  # Todas las condiciones se cumplen, la solución es factible<br><br>def arreglar_solucion_infactible(solucion, distance_matrix):<br><br>    num_ciudades = len(solucion)<br>    ciudades_con_centro = [index_ciudades[i] for i, (tiene_centro, _) in enumerate(solucion) if tiene_centro == 1]<br><br>    for ciudad_index in range(num_ciudades):<br>        ciudad_actual = index_ciudades[ciudad_index]<br>        centro_logistico_actual = solucion[ciudad_index][1]<br>        distancia_maxima = 300<br>        <br>        ciudades_centro_menos300 = []<br>        for ciudad_cer in ciudades_cercanas[ciudad_actual]:<br>            if ciudad_cer in ciudades_con_centro:<br>                ciudades_centro_menos300.append(ciudad_cer)<br>        <br>        if ciudad_actual in ciudades_con_centro:<br>            solucion[ciudad_index] = [1, ciudad_actual]<br>        <br>        elif centro_logistico_actual in ciudades_con_centro:<br>            # Verificar la distancia actual<br>            distancia_actual = distance_matrix[ciudad_actual][centro_logistico_actual]<br><br>            if distancia_actual &gt; distancia_maxima:<br>                if len(ciudades_centro_menos300) &gt;= 1:<br>                    solucion[ciudad_index] = [0, random.choice(ciudades_centro_menos300)]<br>                else:<br>                    solucion[ciudad_index] = [1, ciudad_actual]<br>                <br>        else:<br>            if len(ciudades_centro_menos300) &gt;= 1:<br>                solucion[ciudad_index] = [0, random.choice(ciudades_centro_menos300)]<br>            else:<br>                solucion[ciudad_index] = [1, ciudad_actual]<br>    return solucion<br><br>def verifica_arregla(solucion, distance_matrix):<br>    if verificar_factibilidad(solucion, distance_matrix):<br>        return solucion<br>    else:<br>        return arreglar_solucion_infactible(solucion, distance_matrix)</pre><h3>Genetic algorithm</h3><h4>First generation</h4><pre>def generar_poblacion_inicial(tamano_poblacion):<br>    poblacion = []<br>    for _ in range(tamano_poblacion):<br>        individuo = [[random.randint(0, 1), index_ciudades[random.randint(0, NUM_CIUDADES - 1)]] for _ in range(NUM_CIUDADES)]<br>        poblacion.append(individuo)<br>    return poblacion</pre><h4>Calculate fitness</h4><pre># Ejemplo de uso:<br>tamano_poblacion = 1000<br>poblacion = generar_poblacion_inicial(tamano_poblacion)<br>poblacion_factible = []<br><br>lista_fitness = []<br># Evaluar el fitness de la población<br>for individuo in poblacion:<br>    fitness = funcion_fitness(individuo, distance_matrix)<br>    <br>    if not verificar_factibilidad(individuo, distance_matrix):<br>        new_sol = arreglar_solucion_infactible(individuo, distance_matrix)<br>        poblacion_factible.append(new_sol)<br>        lista_fitness.append(funcion_fitness(new_sol, distance_matrix))</pre><h4>Selection</h4><p>In this step we must determine the individuals that will be crossed to create new individuals. The strategies that I have chosen are two of the most used, the elite selection and by tournament. We have chosen in the elite selection 20 individuals and the size of the tournaments to be 5, in order to choose the same number of individuals that will be crossed.</p><pre>def seleccion_elitista(soluciones, fitness, k):<br>    poblacion_ordenada = [x for _, x in sorted(zip(fitness, poblacion), reverse = False)]<br>    return poblacion_ordenada[:k]<br><br>def seleccion_por_torneo(soluciones, fitness, participantes_torneos):<br>    sol_fit = sorted(zip(fitness, poblacion))<br>    random.shuffle(sol_fit)<br>    <br>    seleccionados = []<br>    i = 0<br>    for torneo in range(0, len(soluciones), participantes_torneos):<br>        clasificacion = [x for _, x in sorted(zip(fitness[i:i+participantes_torneos], poblacion[i:i+participantes_torneos]))]<br>        seleccionados.append(clasificacion[0])<br>        i += participantes_torneos<br>    return seleccionados</pre><h4>Crossover</h4><p>After having selected the best adapted individuals of each generation we must cross them with a certain probability, which we have set at 0.35. The types of mutation we have chosen are uniform mutation and one-point mutation, which are two of the most typical methods.</p><pre>def cruce_npuntos(padre1, padre2, n_puntos):<br>    <br>    descendiente1 = padre1<br>    descendiente2 = padre2<br>    longitud = len(padre1)<br><br>    # Genera n_puntos índices de corte únicos<br>    puntos_de_cruzamiento = sorted(random.sample(range(1, longitud), n_puntos))<br><br>    # Realiza el cruzamiento en N puntos<br>    for i in range(0, n_puntos, 2):<br>        punto1 = puntos_de_cruzamiento[i]<br>        punto2 = puntos_de_cruzamiento[i + 1] if i + 1 &lt; n_puntos else longitud<br><br>        # Intercambia los segmentos entre los puntos de corte<br>        descendiente1[punto1:punto2], descendiente2[punto1:punto2] = descendiente2[punto1:punto2], descendiente1[punto1:punto2]<br><br>    return descendiente1, descendiente2<br><br>def cruce_uniforme(padre1, padre2):<br><br>    descendiente1 = []<br>    descendiente2 = []<br><br>    for i in range(len(padre1)): <br>        aleat = random.randint(0,1)<br>        if aleat == 0:<br>            descendiente1.append(padre2[i])<br>            descendiente2.append(padre1[i])<br>        else:<br>            descendiente1.append(padre1[i])<br>            descendiente2.append(padre2[i])<br><br>    return descendiente1, descendiente2</pre><h4>Mutation</h4><p>After the crossing we will have the individuals of the previous generation plus some new ones, fruits of the crossing. To these individuals we will apply a mutation (small alteration in the structure) that will help to escape from local optima and obtain more diverse solutions. It should be noted that the mutation will be applied to all but the 20 best individuals that we have.</p><pre>def mutacion(individuo, pmut):<br>    individuo_mutado = []<br>    for i in individuo:<br>        prob = random.uniform(0,1)<br>        if prob &lt; pmut:<br>            if i[0] == 0:<br>                new_i = i<br>                new_i[0] += 1<br>                individuo_mutado.append(new_i)<br>            else:<br>                new_i = i<br>                new_i[0] -= 1<br>                individuo_mutado.append(new_i)<br>        else:<br>            individuo_mutado.append(i)<br>    <br>    return individuo_mutado</pre><h4>Replacement</h4><p>In the replacement step we must choose the individuals who will be part of the next generation. The strategy we are going to follow is going to be purely elitist. We will select the k best individuals according to their fitness value.</p><pre>def reemplazamiento_fitness(soluciones, n):<br>    fitness = [funcion_fitness(solucion, distance_matrix) for solucion in soluciones]<br>    soluciones_ordenadas = [x for _, x in sorted(zip(fitness, soluciones), reverse = False)]<br>    return soluciones_ordenadas[:n]</pre><h4>Algorithm code</h4><pre>max_generaciones = 500<br>tamano_poblacion = 100<br>p_cruz = 0.35<br>p_mut = 0.05<br>k_mejores = 20<br>np.random.seed(123)<br>random.seed(123)<br><br>poblacion = [verifica_arregla(individuo, distance_matrix) for individuo in generar_poblacion_inicial(tamano_poblacion)]<br>gen_best = poblacion[0]<br>global_best = gen_best<br><br>gen_best_fitness = funcion_fitness(gen_best, distance_matrix)<br>global_best_fitness = gen_best_fitness<br><br>lista_fitness = [funcion_fitness(individuo, distance_matrix) for individuo in poblacion]<br><br>generacion = 0<br>while generacion &lt; max_generaciones:<br>    <br>    # Seleccion<br>    individuos_seleccionados = seleccion_elitista(poblacion, lista_fitness, k_mejores)<br>    <br>    # Cruzamiento<br>    random.shuffle(individuos_seleccionados)<br>    poblacion_cruzada = poblacion.copy()<br>    for individuo in range(0, len(individuos_seleccionados) - 1, 2):<br>        prob = random.uniform(0, 1)<br>        if prob &lt; p_cruz:<br>            hijo1, hijo2 = cruce_npuntos(individuos_seleccionados[individuo], individuos_seleccionados[individuo + 1], 1)<br>            poblacion_cruzada.append(hijo1)<br>            poblacion_cruzada.append(hijo2)<br>        <br>    poblacion_cruzada_factible = [verifica_arregla(individuo, distance_matrix) for individuo in poblacion_cruzada]<br>    <br>    # Mutacion<br>    poblacion_mutada = [x for _, x in sorted(zip(lista_fitness, poblacion_cruzada_factible), reverse = False)]<br>    poblacion_mutada[k_mejores:] = [mutacion(individuo, p_mut) for individuo in poblacion_mutada[k_mejores:]]<br>    poblacion_mutada_factible = [verifica_arregla(individuo, distance_matrix) for individuo in poblacion_mutada]<br>    <br>    # Reemplazo<br>    poblacion = copy.deepcopy(reemplazamiento_fitness(poblacion_mutada_factible, tamano_poblacion))<br>    lista_fitness = [funcion_fitness(individuo, distance_matrix) for individuo in poblacion]<br>    <br>    gen_best_fitness, gen_best = [[y, x] for y, x in sorted(zip(lista_fitness, poblacion), reverse = False)][0]<br>    <br>    print(&quot;El mejor fitness de la generación &quot;, generacion, &quot; es: &quot;, gen_best_fitness)<br>    print(&quot;El mejor fitness encontrado es: &quot;, global_best_fitness)<br>    <br>    <br>    if gen_best_fitness &lt; global_best_fitness:<br>        print(&quot;Se actualiza&quot;)<br>        global_best = copy.deepcopy(gen_best)<br>        global_best_fitness = gen_best_fitness.copy()<br><br>    generacion += 1</pre><p>After optimizing our parameters this is our best solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*JK4woYKrCvnp4Qcl28inoA.png" /><figcaption>Best solution representation</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716d6fbfb76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[99,46% accuracy on MNIST without CNN]]></title>
            <link>https://aaqumon.medium.com/99-46-accuracy-on-mnist-without-cnn-712042530420?source=rss-880271f569ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/712042530420</guid>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ander]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 11:53:54 GMT</pubDate>
            <atom:updated>2024-02-18T19:06:24.268Z</atom:updated>
            <content:encoded><![CDATA[<h3>Techniques to Improve Our MNIST Accuracy Without Using CNNs (99.46% accuracy)</h3><p>In the pursuit of refining model accuracy on the MNIST dataset, this exploration aims to employ various techniques without resorting to convolutional layers. Multilayer Perceptrons (MLPs) have proven to be formidable in the realm of machine learning, and while convolutional neural networks (CNNs) have gained prominence for image-related tasks, we seek alternative strategies to elevate accuracy on MNIST using the inherent strengths of MLPs.</p><p>Our objective is to shed light on specific techniques that bypass the need for convolutions, providing practitioners with a toolkit to enhance the predictive performance of MLPs on the MNIST dataset. By delving into the intricacies of hyperparameter fine-tuning, exploring unconventional activation functions, and adopting regularization strategies, we aim to present a comprehensive guide for practitioners seeking to boost accuracy without the use of convolutional layers. We will use pytorch.</p><h3><strong>Code for pytorch</strong></h3><p>Necessary libraries</p><pre>import torch<br>import torchvision<br>import pandas as pd<br>import torch.nn as nn<br>from tqdm import tqdm<br>import multiprocessing<br>import torch.optim as optim<br>import torch.nn.functional as  F<br>from torch.utils.data import Dataset<br>from torch.utils.data import DataLoader<br>from torchvision import transforms<br><br>print(&quot;Torch version: &quot;, torch. __version__)</pre><p>To execute the code faster we are going to use GPU. If you dont have one you can use google colab.</p><pre># Set device<br><br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>print(&quot;Device: &quot;, device)</pre><p>Now we will download the MNIST data (train and test)</p><pre># Prepare data<br><br>train_set = torchvision.datasets.MNIST(&#39;.data/&#39;, train=True, download=True)<br>test_set = torchvision.datasets.MNIST(&#39;.data/&#39;, train=False, download=True)<br><br>print(&quot;Train images: &quot;, train_set)<br>print(&quot;Image: &quot;, train_set[0][0])<br>print(&quot;Label: &quot;, train_set[0][1])<br>print(&quot;Label one hot: &quot;, F.one_hot(torch.tensor(train_set[0][1]), num_classes=10))</pre><p>The Python code provided defines a custom MNIST data class dataset for handling MNIST data. It converts PIL images into torch tensors, reshapes them, and encodes the corresponding one-hot labels. A class is initialized with a data set and a partition type (training or testing). Instances of classes (train_dataset and test_dataset) have been created for training and test datasets that provide a convenient interface for loading and processing MNIST datasets in PyTorch.</p><pre># Dataset class<br><br>class MNIST_dataset(Dataset):<br><br>    def __init__(self, data, partition = &quot;train&quot;):<br>        print(&quot;\nLoading MNIST &quot;, partition, &quot; Dataset...&quot;)<br>        self.data = data<br>        self.partition = partition<br>        print(&quot;\tTotal Len.: &quot;, len(self.data), &quot;\n&quot;, 50*&quot;-&quot;)<br><br>    def __len__(self):<br>        return len(self.data)<br><br>    def from_pil_to_tensor(self, image):<br>        return torchvision.transforms.ToTensor()(image)<br><br>    def __getitem__(self, idx):<br>        # Image<br>        image = self.data[idx][0]<br>        # PIL Image to torch tensor<br>        image_tensor = self.from_pil_to_tensor(image)<br>        # care! net expect a 784 size vector and our dataset<br>        # provide 1x28x28 (channels, height, width) -&gt; Reshape!<br>        image_tensor = image_tensor.view(-1)<br><br>        # Label<br>        label = torch.tensor(self.data[idx][1])<br>        label = F.one_hot(label, num_classes=10).float()<br><br>        return {&quot;img&quot;: image_tensor, &quot;label&quot;: label}<br><br>train_dataset = MNIST_dataset(train_set, partition=&quot;train&quot;)<br>test_dataset = MNIST_dataset(test_set, partition=&quot;test&quot;)</pre><p>We now define DataLoader instances using the PyTorchs DataLoader class to facilitate batch processing of the MNIST dataset. It defines a batch size of 100 determines the number of worker processes based on the available CPU cores and sets the data shuffling for the training data loader. The number_workers parameter is set to use all available CPU cores except one. The data loader is ready to train and test neural network models on the MNIST dataset.</p><pre># Dataloader class<br><br>batch_size = 100<br>num_workers = multiprocessing.cpu_count()-1<br>print(&quot;Num workers&quot;, num_workers)<br>train_dataloader = DataLoader(train_dataset, batch_size, shuffle=True, num_workers=num_workers)<br>test_dataloader = DataLoader(test_dataset, batch_size, shuffle=False, num_workers=num_workers)</pre><p><strong>Definition of Net and training</strong></p><p>That will be out initial MLP with 2 hidden layers.</p><pre># Neural network class<br><br>class Net(nn.Module):<br>    def __init__(self, num_classes):<br>        super(Net, self).__init__()<br>        self.linear1 = nn.Linear(784, 1024)<br>        self.relu1 = nn.ReLU()<br>        self.linear2 = nn.Linear(1024, 1024)<br>        self.relu2 = nn.ReLU()<br>        self.linear3 = nn.Linear(1024, 1024)<br>        self.relu3 = nn.ReLU()<br>        self.classifier = nn.Linear(1024, num_classes)<br><br>    def forward(self, x):<br>        out = self.relu1(self.linear1(x))<br>        out = self.relu2(self.linear2(out))<br>        out = self.relu3(self.linear3(out))<br>        out = self.classifier(out)<br>        return out<br><br><br># Instantiating the network and printing its architecture<br>num_classes = 10<br>net = Net(num_classes)<br>print(net)<br><br>def count_parameters(model):<br>    return sum(p.numel() for p in model.parameters() if p.requires_grad)<br>print(&quot;Params: &quot;, count_parameters(net))</pre><pre># Training hyperparameters<br>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.SGD(net.parameters(), lr=0.01, weight_decay=1e-6, momentum=0.9)<br>epochs = 25</pre><pre># Load model in GPU<br>net.to(device)<br><br>print(&quot;\n---- Start Training ----&quot;)<br>best_accuracy = -1<br>best_epoch = 0<br>for epoch in range(epochs):<br>    # TRAIN NETWORK<br>    train_loss, train_correct = 0, 0<br>    net.train()<br>    with tqdm(iter(train_dataloader), desc=&quot;Epoch &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>        for batch in tepoch:<br><br>            # Returned values of Dataset Class<br>            images = batch[&quot;img&quot;].to(device)<br>            labels = batch[&quot;label&quot;].to(device)<br><br>            # zero the parameter gradients<br>            optimizer.zero_grad()<br><br>            # Forward<br>            outputs = net(images)<br>            loss = criterion(outputs, labels)<br><br>            # Calculate gradients<br>            loss.backward()<br><br>            # Update gradients<br>            optimizer.step()<br><br>            # one hot -&gt; labels<br>            labels = torch.argmax(labels, dim=1)<br>            pred = torch.argmax(outputs, dim=1)<br>            train_correct += pred.eq(labels).sum().item()<br><br>            # print statistics<br>            train_loss += loss.item()<br><br>    train_loss /= len(train_dataloader.dataset)<br><br>    # TEST NETWORK<br>    test_loss, test_correct = 0, 0<br>    net.eval()<br>    with torch.no_grad():<br>      with tqdm(iter(test_dataloader), desc=&quot;Test &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>          for batch in tepoch:<br><br>            images = batch[&quot;img&quot;].to(device)<br>            labels = batch[&quot;label&quot;].to(device)<br><br>            # Forward<br>            outputs = net(images)<br>            test_loss += criterion(outputs, labels)<br><br>            # one hot -&gt; labels<br>            labels = torch.argmax(labels, dim=1)<br>            pred = torch.argmax(outputs, dim=1)<br><br>            test_correct += pred.eq(labels).sum().item()<br><br>    test_loss /= len(test_dataloader.dataset)<br>    test_accuracy = 100. * test_correct / len(test_dataloader.dataset)<br><br>    print(&quot;[Epoch {}] Train Loss: {:.6f} - Test Loss: {:.6f} - Train Accuracy: {:.2f}% - Test Accuracy: {:.2f}%&quot;.format(<br>        epoch + 1, train_loss, test_loss, 100. * train_correct / len(train_dataloader.dataset), test_accuracy<br>    ))<br><br>    if test_accuracy &gt; best_accuracy:<br>        best_accuracy = test_accuracy<br>        best_epoch = epoch<br><br>        # Save best weights<br>        torch.save(net.state_dict(), &quot;best_model.pt&quot;)<br><br>print(&quot;\nBEST TEST ACCURACY: &quot;, best_accuracy, &quot; in epoch &quot;, best_epoch)</pre><p>With this net we archieve 98.27% of accuracy on test. We can improve this with different tecniques.</p><h3>Optimize hyperparameters</h3><p>Hyperparameter optimization is a technique for improving the accuracy of machine learning models by adjusting default parameters before training. Key hyperparameters in neural networks include the number of hidden layer neurons per layer activation function and the learning rate. Practitioners systematically look for different values ​​of these parameters such as the number of deep neurons and activation functions for different layers as well as adjust the learning rate. The goal is to determine the best combination that maximizes model performance on a given data set a process called hyperparameter tuning. This approach is important for fine-tuning neural networks that have been applied to tasks such as MNIST digit recognition. We will try these parameters.</p><ul><li><em>Number of hiden layers</em>: 1, 2 or 3</li><li><em>Size of hidden layers</em>: 256, 512 or 1024</li><li><em>Optimizer</em>: Adam, Adagrad or SDG</li><li><em>Activation function</em>: Relu, Tanh or Sigmoid</li><li><em>Learning rate</em>: 0.1, 0.01, 0.02 or 0.001</li></ul><p>With the best parameters we finally obtain 98,5% accuracy. But that is not enough, we can do more things to improve that.</p><h3><strong>Batch Normalization</strong></h3><p>Batch normalization is a technique to improve the stability and convergence speed of neural network training. This involves normalizing the input to each layer of the neural network by scaling and scaling activation. Batch normalization during training calculates the mean and standard deviation of the activations in each mini-batch and then uses these batch-specific statistics to normalize the activations. This normalization helps to overcome problems like intrinsic covariate shift where the distribution of inputs in a layer changes during training and makes it difficult for the model to learn effectively. Group normalization also introduces learned parameters (gamma and beta) that allow the model to adjust to normal values. Overall ensemble normalization contributes to faster and more reliable training by allowing the network to learn better representations and improve generalization performance on unseen data.</p><pre># Add batchnorm<br><br>class Net(nn.Module):<br>    def __init__(self, sizes=[[784, 512], [512, 512], [512, 512], [512, 10]], criterion=None):<br>        super(Net, self).__init__()<br><br>        self.layers = nn.ModuleList()<br><br>        for i in range(len(sizes)-1):<br>            dims = sizes[i]<br>            self.layers.append(nn.Linear(dims[0], dims[1]))<br>            self.layers.append(nn.BatchNorm1d(dims[1]))<br>            self.layers.append(nn.ReLU())<br><br>        dims = sizes[-1]<br>        self.classifier = nn.Linear(dims[0], dims[1])<br><br>        self.criterion = criterion<br><br>    def forward(self, x, y=None):<br>        for layer in self.layers:<br>            x = layer(x)<br>        x = self.classifier(x)<br><br>        if y != None:<br>            loss = self.criterion(x, labels)<br>            return loss, x<br>        return x<br><br># Instantiating the network and printing its architecture<br>num_classes = 10<br>net = Net(sizes=[[784, 512], [512, 512], [512, 512], [512, num_classes]], criterion=criterion)<br>print(net)<br><br>def count_parameters(model):<br>    return sum(p.numel() for p in model.parameters() if p.requires_grad)<br>print(&quot;Params: &quot;, count_parameters(net))</pre><p>With that we obtain 98.64% of accuracy.</p><h3><strong>Learning rate annealing</strong></h3><p>Learning rate annealing is a strategy in which the learning rate is systematically reduced during training. This technique aims to improve model convergence and improve performance by starting with a relatively high learning rate for faster initial progress and gradually reducing it to improve the model as it approaches convergence. Reducing the learning rate helps find a trade-off between fast convergence in the early stages of training and finer adjustments later to contribute to better optimization and better generalization to unseen data.</p><p>In our case we will start with 0.1 of learing rates. At epoch 25 we will decrease it to 0.01 and at epoch 50 we will decrease it again to 0.001.</p><pre># Add LRA<br><br># Training hyperparameters<br>optimizer = optim.SGD(net.parameters(), lr=0.1, weight_decay=1e-6, momentum=0.9)<br><br># Learning Rate Annealing (LRA) scheduling<br># lr = 0.1     if epoch &lt; 25<br># lr = 0.01    if 25 &lt;= epoch &lt; 50<br># lr = 0.001   if epoch &gt;= 50<br>scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[25, 50], gamma=0.1)<br><br>net = net.to(device)<br><br># Start training<br>epochs = 75</pre><h3><strong>Data Augmentation</strong></h3><p>Data augmentation is technique primarily in which the training data set is expanded by applying various transformations to existing images. These changes include zoom rotation and changes to brightness or contrast. By generating different input data variations general models of auction data help adapt to different contexts by reducing overfitting and increasing the ability to identify patterns in real-world situations.</p><p>The defined data transformations are used to expand the training data set:</p><ol><li><strong>Random rotation</strong> <strong>(</strong>up to 10 degrees): Images are randomly rotated up to 10 degrees, which changes the orientation of the numbers.</li><li><strong>Random affine transformation</strong> (up to 20 degrees, random translation,<strong> </strong>random scaling): This transformation includes random rotations (up to 20 degrees), translations (up to 10% both horizontally and vertically), and scaling (between 0.9 and 1.1) . These variations simulate different angles, positions and sizes of the numbers in the images.</li></ol><p>Only the essential transformation of converting images to tensors using transforms.ToTensor() is used on the test dataset, as adding data is usually reserved for training to avoid artificially increasing the diversity of the test set. Together, these transformations help to create a more robust and diverse training dataset, helping the neural network learn invariant features and improve its generalization.</p><pre># Add DA<br><br>train_transform = transforms.Compose([<br>    transforms.RandomRotation(degrees=10),  # Rotación aleatoria hasta 10 grados<br>    transforms.RandomAffine(degrees=20, translate=(0.1, 0.1), scale=(0.9, 1.1)),  # Rotación, traslación y escala aleatorias<br>    transforms.ToTensor(),<br>])<br><br>test_transform = transforms.Compose([<br>    transforms.ToTensor(),<br>])</pre><pre>class MNIST_dataset(Dataset):<br><br>    def __init__(self, partition = &quot;train&quot;, transform=None):<br><br>        print(&quot;\nLoading MNIST &quot;, partition, &quot; Dataset...&quot;)<br>        self.partition = partition<br>        self.transform = transform<br>        if self.partition == &quot;train&quot;:<br>            self.data = torchvision.datasets.MNIST(&#39;.data/&#39;, train=True, download=True)<br>        else:<br>            self.data = torchvision.datasets.MNIST(&#39;.data/&#39;, train=False, download=True)<br>        print(&quot;\tTotal Len.: &quot;, len(self.data), &quot;\n&quot;, 50*&quot;-&quot;)<br><br>    def __len__(self):<br>        return len(self.data)<br><br>    def __getitem__(self, idx):<br><br>        # Image<br>        image = self.data[idx][0]<br>        image = self.transform(image)<br>        # care! net expect a 784 size vector and our dataset<br>        # provide 1x28x28 (channels, height, width) -&gt; Reshape!<br>        image = image.view(-1)<br><br>        # Label<br>        label = torch.tensor(self.data[idx][1])<br>        label = F.one_hot(label, num_classes=10).float()<br><br>        return {&quot;idx&quot;: idx, &quot;img&quot;: image, &quot;label&quot;: label}<br><br>train_dataset = MNIST_dataset(partition=&quot;train&quot;, transform=train_transform)<br>test_dataset = MNIST_dataset(partition=&quot;test&quot;, transform=test_transform)</pre><p>Our best net.</p><pre>batch_size = 100<br>num_workers = multiprocessing.cpu_count()-1<br>print(&quot;Num workers&quot;, num_workers)<br>train_dataloader = DataLoader(train_dataset, batch_size, shuffle=True, num_workers=num_workers)<br>test_dataloader = DataLoader(test_dataset, batch_size, shuffle=False, num_workers=num_workers)</pre><pre>class Net(nn.Module):<br>    def __init__(self, sizes=[[784, 1024], [1024, 1024], [1024, 1024], [1024, 10]], criterion=None):<br>        super(Net, self).__init__()<br><br>        self.layers = nn.ModuleList()<br><br>        for i in range(len(sizes)-1):<br>            dims = sizes[i]<br>            self.layers.append(nn.Linear(dims[0], dims[1]))<br>            self.layers.append(nn.BatchNorm1d(dims[1]))<br>            self.layers.append(nn.ReLU())<br><br>        dims = sizes[-1]<br>        self.classifier = nn.Linear(dims[0], dims[1])<br><br>        self.criterion = criterion<br><br>    def forward(self, x, y=None):<br>        for layer in self.layers:<br>            x = layer(x)<br>        x = self.classifier(x)<br><br>        if y != None:<br>            loss = self.criterion(x, y)<br>            return loss, x<br>        return x<br><br># Training Settings<br>criterion = nn.CrossEntropyLoss()<br><br># Instantiating the network and printing its architecture<br>num_classes = 10<br>net = Net(sizes=[[784, 1024], [1024, 1024], [1024, 1024], [1024, num_classes]], criterion=criterion)<br>print(net)<br><br>def count_parameters(model):<br>    return sum(p.numel() for p in model.parameters() if p.requires_grad)<br>print(&quot;Params: &quot;, count_parameters(net))</pre><pre># Training hyperparameters<br>optimizer = optim.SGD(net.parameters(), lr=0.1, weight_decay=1e-6, momentum=0.9)<br><br># Learning Rate Annealing (LRA) scheduling<br># lr = 0.1     if epoch &lt; 25<br># lr = 0.01    if 25 &lt;= epoch &lt; 50<br># lr = 0.001   if epoch &gt;= 50<br>scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[25, 50], gamma=0.1)<br><br>net = net.to(device)<br><br># Start training<br>epochs = 75</pre><pre># Start training<br>epochs = 75<br><br>print(&quot;\n---- Start Training ----&quot;)<br>best_accuracy = -1<br>best_epoch = 0<br>for epoch in range(epochs):<br><br><br>    # TRAIN NETWORK<br>    train_loss, train_correct = 0, 0<br>    net.train()<br>    with tqdm(iter(train_dataloader), desc=&quot;Epoch &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>        for batch in tepoch:<br><br>          images = batch[&quot;img&quot;].to(device)<br>          labels = batch[&quot;label&quot;].to(device)<br>          ids = batch[&quot;idx&quot;].to(&#39;cpu&#39;).numpy()<br><br>          # zero the parameter gradients<br>          optimizer.zero_grad()<br><br>          #  Forward<br>          loss, outputs = net(images, labels)<br><br>          loss.backward()<br><br>          optimizer.step()<br><br>          # one hot -&gt; labels<br>          labels = torch.argmax(labels, dim=1)<br>          pred = torch.argmax(outputs, dim=1)<br><br>          train_correct += pred.eq(labels).sum().item()<br><br>          # print statistics<br>          train_loss += loss.item()<br><br>        scheduler.step()<br>        print(&quot;\tLR: &quot;, optimizer.param_groups[0][&#39;lr&#39;])<br><br>    train_loss /= len(train_dataloader.dataset)<br><br>    # TEST NETWORK<br>    test_loss, test_correct = 0, 0<br>    net.eval()<br>    with torch.no_grad():<br>      with tqdm(iter(test_dataloader), desc=&quot;Test &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>          for batch in tepoch:<br><br>            images = batch[&quot;img&quot;].to(device)<br>            labels = batch[&quot;label&quot;].to(device)<br>            ids = batch[&quot;idx&quot;].to(&#39;cpu&#39;).numpy()<br><br>            #  Forward<br>            outputs = net(images)<br>            test_loss += criterion(outputs, labels)<br><br>            # one hot -&gt; labels<br>            labels = torch.argmax(labels, dim=1)<br>            pred = torch.argmax(outputs, dim=1)<br><br>            test_correct += pred.eq(labels).sum().item()<br><br>    test_loss /= len(test_dataloader.dataset)<br>    test_accuracy = 100. * test_correct / len(test_dataloader.dataset)<br><br>    print(&quot;[Epoch {}] Train Loss: {:.6f} - Test Loss: {:.6f} - Train Accuracy: {:.2f}% - Test Accuracy: {:.2f}%&quot;.format(<br>        epoch + 1, train_loss, test_loss, 100. * train_correct / len(train_dataloader.dataset), test_accuracy<br>    ))<br><br>    if test_accuracy &gt; best_accuracy:<br>        best_accuracy = test_accuracy<br>        best_epoch = epoch<br><br>        # Save best weights<br>        torch.save(net.state_dict(), &quot;best_model.pt&quot;)<br><br>print(&quot;\nBEST TEST ACCURACY: &quot;, best_accuracy, &quot; in epoch &quot;, best_epoch)<br><br><br># Load best weights<br>net.load_state_dict(torch.load(&quot;best_model.pt&quot;))<br><br>test_loss, test_correct = 0, 0<br>net.eval()<br>with torch.no_grad():<br>    with tqdm(iter(test_dataloader), desc=&quot;Test &quot; + str(epoch), unit=&quot;batch&quot;) as tepoch:<br>        for batch in tepoch:<br><br>            images = batch[&quot;img&quot;].to(device)<br>            labels = batch[&quot;label&quot;].to(device)<br>            ids = batch[&quot;idx&quot;].to(&#39;cpu&#39;).numpy()<br><br>            #  Forward<br>            outputs = net(images)<br>            test_loss += criterion(outputs, labels)<br><br>            # one hot -&gt; labels<br>            labels = torch.argmax(labels, dim=1)<br>            pred = torch.argmax(outputs, dim=1)<br><br>            test_correct += pred.eq(labels).sum().item()<br><br>    test_loss /= len(test_dataloader.dataset)<br>    test_accuracy = 100. * test_correct / len(test_dataloader.dataset)<br>print(&quot;Final best acc: &quot;, test_accuracy)</pre><p>And that is out final results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xw8JPFnD8bEEW-NtcjnvfA.png" /><figcaption>Final net accuracy</figcaption></figure><h3>Conclusion</h3><p>In summary, this work explores strategies to improve the accuracy of multilayer perceptrons (MLPs) on the MNIST dataset without relying on convolutional layers. In addition, the addition of data augmentation techniques such as random transformation, affine transformation, and tensor transformation play an important role in varying the training dataset, which helps to generalize and reduce the addition. Through a systematic approach to parameter optimization and data augmentation, this work aims to provide a comprehensive approach for professionals looking to increase the accuracy of MLP in classification tasks. image, showing how these networks work without layers, adaptability and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=712042530420" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>