<?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 Tehreem Ansari on Medium]]></title>
        <description><![CDATA[Stories by Tehreem Ansari on Medium]]></description>
        <link>https://medium.com/@tehreemansari?source=rss-fa5b1249bbc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9Xrc66GIQxJI2Tnani38cw.png</url>
            <title>Stories by Tehreem Ansari on Medium</title>
            <link>https://medium.com/@tehreemansari?source=rss-fa5b1249bbc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 08:13:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tehreemansari/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[Core topics of Deep Learning]]></title>
            <link>https://medium.com/@tehreemansari/core-topics-of-deep-learning-bbd3d2ce6145?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbd3d2ce6145</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 21:58:21 GMT</pubDate>
            <atom:updated>2025-06-23T18:44:53.848Z</atom:updated>
            <content:encoded><![CDATA[<p>(Not including topics like Vanishing gradient, Bias vs Variance etc. These are mostly tabular notes/comparisions for recollection of my thoughts.)</p><p>“Dying ReLU” : The phenomenon where the parameters stop changing due to consistently negative values passed to a ReLU, which result in a zero gradient. To avoid dying relu, use Leaky ReLU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NniDtSnry5BbORrBjf__aQ.png" /><figcaption>relu vs leaky relu</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofdvMMboMk_4X0vZ8w2n6Q.png" /><figcaption>top 10 activation functions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NwVM_1zIVx41qTWWlzKnw.png" /><figcaption>Covariate vs internal covariate shift</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxEsekJgU0GicK8SfaFjKQ.png" /><figcaption>Types of tokenization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2zxoIOYzGusi5nlVYN8og.png" /><figcaption>Tokenization libraries &amp; uses</figcaption></figure><p><a href="https://quickchat.ai/post/tokens-entropy-question">Learn more in this blog</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndC53LVbGh56RR5VF0kZYA.png" /><figcaption>Sequential vs non</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvVXkvKJ9pWiuKuYU5wmsg.png" /><figcaption>T<a href="https://www.geeksforgeeks.org/nlp/word-embeddings-in-nlp/">aken from geeks (here)</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIN42ST9GHLpKuBuxyxfeQ.png" /><figcaption>Positional encoding (taken from <a href="https://community.superdatascience.com/c/llm-gpt/sections/145469/lessons/508206">SDS</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFpozqxrRMjwpN5a8OEJAQ.png" /><figcaption>Tokenization vs embedding</figcaption></figure><p>Checkerboard Artifacts</p><ul><li>Checkerboard artifacts are unwanted grid-like patterns (like a chessboard) that appear in generated images, especially when using transposed convolutions (deconvolutions) in neural networks.</li><li>Most common in image generation tasks (GANs, super-resolution) when upsampling images with certain convolutional layers.</li><li>Why do they happen? Because of uneven overlap or tiling when upsampling, some pixels get more attention than others, creating a checkerboard pattern.</li><li>Example: You see weird square patterns in a generated photo that shouldn’t be there.</li></ul><p>Gradient Artifacts</p><ul><li>Gradient artifacts are unwanted, unnatural changes or stripes in the color or brightness gradient of an image. The transition between colors or brightness isn’t smooth. Can occur during image compression, quantization, or when neural networks don’t learn smooth transitions (for example, in low-bit-depth images or poorly trained models).</li><li>Why do they happen?<br>Loss of information or poor learning causes abrupt changes instead of smooth gradients.</li><li>Example: In a sunset photo, instead of a smooth sky, you see visible bands or steps in color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lir6xVIaiDW-kDwezQKhA.png" /><figcaption>Fix for checkerboard &amp; gradient artifacts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKPV1BwLVzuKDJc38EkjTA.png" /><figcaption>Stochastic vs Deterministic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owPJk0PKJt3z_TZ7amMPMw.png" /><figcaption>Differnt types of distributions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnB3NbiMdb4zJ414EImpFg.png" /><figcaption>Indexing strategy in Vector DBs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHr0BBNegixAfD_d3IIJKw.png" /><figcaption>Different DBs use which Indexing strategy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UINlEeUCMgNznu27_rX5OA.png" /><figcaption>Cost functions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*V31a134quKdhrR2ry3Hz3Q.png" /><figcaption>Formula’s for z (weighted sum)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwnbfWzE3AxDiIOEGzMa2w.png" /><figcaption>Weighted sum for linear vs logistic function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCJV4Q0lqgm0BQ8L8fLppg.png" /><figcaption>Weighted sum vs activation function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjwS_HWfOlYVAu01PuSV1Q.png" /><figcaption>FFNN vs RNN</figcaption></figure><h3>Feedforward Example (Image Classification)</h3><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense<br># Feedforward network for binary classification<br>model = Sequential([<br>    Dense(64, input_shape=(10,), activation=&#39;relu&#39;),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><h3>Recurrent Example (Text Sequence Prediction)</h3><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import SimpleRNN, Dense<br># Recurrent network for sequence data<br>model = Sequential([<br>    SimpleRNN(64, input_shape=(10, 1)),  # 10 time steps, 1 feature per step<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><ul><li>FFNN: Use when your data points are independent (e.g., images, tabular data).</li><li>RNN: Use when your data is a sequence and past information matters (e.g., text, time series).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XP4UR2yfel16GiEHBqrJg.png" /><figcaption>Different types of NN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nc-2ZVziKtfF2WV8AQwK6Q.png" /><figcaption>SVD vs SVM</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkQG2befgVXj7R86Vo8a9w.png" /><figcaption>Encoder vs decoder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhrHEmVRO8DIuk-0J74MQw.png" /><figcaption>Generator vs discriminator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXras-0OPmbUJ1jjgaEasw.png" /><figcaption>Gans vs diffusion models</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPk9Rx6tCxT7F75EZVYf9g.png" /><figcaption>Models/NN where weights can/cannot be 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mm-VmtupXG01O8n4MoSNtA.png" /><figcaption>Rand vs Randn</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rh5w-9W91NuARtwxillyRA.png" /><figcaption>Label encoding vs one hot</figcaption></figure><ul><li>Deep Reinforcement Learning (DRL) is a combination of reinforcement learning and deep learning. It uses deep neural networks to approximate the functions needed for decision-making in reinforcement learning. In simpler terms, DRL helps agents (like robots or AI systems) learn how to make decisions by interacting with their environment and getting feedback (rewards or penalties). It is distinct from supervised learning and unsupervised learning because it focuses on learning through interaction rather than labeled data or clustering patterns.</li></ul><ol><li>Random Projection Trees (RPTrees) are a clever way to organize and search through lots of high-dimensional data (like long lists of numbers, or “vectors”) quickly. Imagine You Have a Big Mess of Dots, Each dot is a data point (like an image, document, or user profile), and each one has lots of numbers describing it (maybe hundreds or thousands!). You want to find which dots are “closest” to a new dot you get (nearest neighbor search).</li><li>Word2Vec: This method uses two techniques, Continuous Bag of Words (CBOW) and Skip-Gram, to generate word vectors. Both methods predict either the target word given its context (CBOW) or the context given the target word (Skip-Gram).</li></ol><p>Example with Gensim:</p><pre>from gensim.models import Word2Vec<br># Load a pre-trained model (you need to download or train one)<br># For demonstration, assume &#39;model&#39; is a pre-trained Word2Vec model<br># Retrieve the vector for &quot;dog&quot;<br>vector = model.wv[&#39;dog&#39;]<br>print(vector)</pre><p>This would output the actual vector for “dog” in the model you’re using.</p><p>— — — — — — — — — — — — —</p><ul><li>GloVe: Global Vectors for Word Representation. This method represents words as vectors based on their co-occurrence patterns in a large corpus of text.</li><li>FastText: An extension of Word2Vec that also considers subword information, which is useful for handling out-of-vocabulary words.</li></ul><p>— — — —</p><p>Covariate Shift</p><ul><li>Covariate shift happens when the distribution of the input data (features) changes between training and testing, but the relationship between features and labels stays the same.</li><li>Your model learns from one type of data, but sees a different type when deployed, so it might perform badly.</li><li>Example: You train a spam detector on emails from 2020, but in 2025, people use new slang or formats. The way emails look (features) has changed, but what counts as spam hasn’t.</li></ul><p>Internal Covariate Shift</p><ul><li>Internal covariate shift happens inside a neural network. It means the distribution of activations (outputs from each layer) keeps changing during training as the weights update.</li><li>It slows down training because each layer has to keep adapting to new input distributions from the previous layer. Example: In a deep neural network, as you train, the output from layer 1 changes, so layer 2 keeps getting different inputs, making learning unstable. Batch normalization was invented to fix this.</li></ul><p>A <strong>transposed convolution</strong> (also called <strong>deconvolution</strong> or <strong>fractionally strided convolution</strong>) is used in neural networks — especially in tasks like image generation or semantic segmentation — to <strong>upsample</strong> a feature map (i.e., increase its spatial dimensions). <strong>Deconvolution</strong> (or <strong>transposed convolution</strong>) is widely used in deep learning for <strong>upsampling</strong>, especially in models like autoencoders, GANs, and segmentation networks (e.g., U-Net).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbd3d2ce6145" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing TensorFlow Crashes on MacBook during ML Model Training]]></title>
            <link>https://medium.com/@tehreemansari/fixing-tensorflow-crashes-on-macbook-during-ml-model-training-40a1c5a9562f?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a1c5a9562f</guid>
            <category><![CDATA[macbook]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 23:03:56 GMT</pubDate>
            <atom:updated>2025-06-09T23:03:56.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Begining year 2025, I purchased a brand new M4 chip macbook thinking I will use it for training my “small ML models”! Boy, did I underestimate how much time I’d end up spending just understanding my Mac’s hardware.</p><p>The first time I encountered the dreaded “<strong>Kernel restarting</strong>” issue, I went full panic mode. I deleted <em>everything</em> — my environment, Anaconda, and even the local trash. And strangely enough, <strong>it didn’t work</strong>. At one point, I seriously thought Apple had “cheated” me and that my GPU wasn’t working at all. The frustrating part? There’s no easy way on macOS to directly check GPU/CPU diagnostics.</p><p>After banging my head for hours, I finally <em>read</em> somewhere (which is now some AI chat) that if the GPU memory is full, the only way to clean it up is to <strong>restart the Mac</strong>. (Honestly, I was this close to formatting the entire system — because I’m impulsive like that.)</p><p>Voilà! After a restart, things started working again. I thought the worst was behind me.</p><p>A few days later, I was building a very similar model. This time, I felt prepared:</p><ul><li>My environments were set up.</li><li>All the required packages were installed.</li><li>My Python version was compatible with TensorFlow.</li><li>I had switched to mamba and completly removed “anaconda” (although you could argue mamba is a part of anaconda, but you know what I mean!).</li><li>And if anything went wrong, I’d just restart. Easy fix, right?</li></ul><p>So I went ahead, did all my preprocessing, and then came the fateful line: model.fit().<br><strong>Boom.</strong> Kernel crash—again.</p><p>No worries, I thought. I confidently restarted my Mac and re-ran the code.</p><p><strong>Guess what?</strong> Same crash.</p><p>At this point, I was confused and mildly existential. Why does nothing ever run smoothly the first time in my dev life?</p><p>So began my hunt for answers. After multiple trial-and-error runs, I finally got the model to train <em>without crashing</em> on my local machine. <strong>Victory!</strong></p><p>But this time, I’m documenting everything — because I never want to go through that chaotic debugging cycle again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kzgk2qSisHpbi0DU.png" /></figure><p>I know, I know… long intro. But whatever — here’s what I learned:</p><h3>🚨 Part 1: Fixing TensorFlow Kernel Crashes on MacBook M1/M2/M3/M4 (Apple Silicon)</h3><h3>💡 The Root Cause</h3><p>The default TensorFlow pip package (or mamba/conda) is not compatible with the M4 chip because it is built for Intel CPUs and expects instruction sets not available on Apple Silicon. It can work sometimes, if you are running an x86_64 (current Intel, 64-bit extension of the x86 instruction set architecture, we also had 32, but its old now) version of Python — often via Rosetta 2 emulation (enables apps built for Intel Macs to run on Macs with Apple silicon) — the default TensorFlow pip package (which is built for Intel) may install and run. Rosetta allows many Intel-based binaries to function on Apple Silicon, albeit (fancy word for “at the cost of”) with performance penalties and sometimes subtle bugs.</p><p>However, when it fails, it’s due to <strong>memory allocation failures</strong> or <strong>segmentation faults</strong>.</p><h3>✅ The Solution: Use tensorflow-macos and tensorflow-metal</h3><h3>🛠️ Step-by-Step Fix</h3><p><strong>Step 1: Create a Clean Environment</strong></p><pre>mamba create -n tf-macos_local_sucks python=3.10 <br>mamba activate tf-macos_local_sucks</pre><p><strong>Step 2: Uninstall Faulty TensorFlow</strong></p><pre>pip uninstall tensorflow  # Run this multiple times if needed (because why not)</pre><p><strong>Step 3: Install Correct Version</strong></p><pre>pip install tensorflow-macos # Beyong 2.15 is supposed to be stable<br>pip install tensorflow-metal</pre><p><strong>Step 4: Verify GPU Access (not on terminal lol, do it in notebook)</strong></p><pre>import tensorflow as tf<br>print(&quot;TensorFlow version:&quot;, tf.__version__)<br>print(&quot;GPUs:&quot;, tf.config.list_physical_devices(&#39;GPU&#39;))</pre><p>You should see:</p><pre>GPUs: [PhysicalDevice(name=&#39;/physical_device:GPU:0&#39;, device_type=&#39;GPU&#39;)]</pre><p><strong>Step 5: Test with Dummy Model</strong></p><pre>import tensorflow as tf <br>import numpy as np<br>X = np.random.rand(100, 32, 32, 3)<br>y = tf.keras.utils.to_categorical(np.random.randint(0, 3, 100), num_classes=3)<br>model = tf.keras.Sequential([<br>    tf.keras.layers.Conv2D(16, 3, activation=&#39;relu&#39;, input_shape=(32, 32, 3)),<br>    tf.keras.layers.MaxPooling2D(),<br>    tf.keras.layers.Flatten(),<br>    tf.keras.layers.Dense(3, activation=&#39;softmax&#39;)<br>])<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(X, y, epochs=1) # this line should run fine</pre><h3>🔧 Part 2: The code part</h3><p>(Will add screenshots and more code if I get the same crashes again.)</p><h3>1. ❌ Using class_weight with One-Hot Labels</h3><ul><li><strong>Code Issue</strong>: model.fit(..., class_weight=...) + one-hot labels</li><li><strong>Why It Crashes</strong>: class_weight expects sparse (integer) labels</li><li><strong>Fix</strong>: Convert labels to sparse or remove class_weight.</li></ul><h3>2. 🔁 Repeating Without Batching</h3><ul><li><strong>Code Issue</strong>: .repeat() without .batch()</li><li><strong>Why It Crashes</strong>: Infinite unbatched data overloads memory</li><li><strong>Fix</strong>: Always batch before repeating</li></ul><pre>dataset = dataset.batch(32).repeat()</pre><h3>3. 🧮 Misusing compute_class_weight on One-Hot Labels</h3><ul><li><strong>Code Issue</strong>: Passing one-hot labels into compute_class_weight()</li><li><strong>Why It Crashes</strong>: One-hot arrays aren’t valid class labels</li><li><strong>Fix</strong>: Convert to integers using np.argmax()</li></ul><pre>y_sparse = np.argmax(y_onehot, axis=1)</pre><h3>4. 📦 Misconfigured .take(1) During Debugging</h3><ul><li><strong>Code Issue</strong>: Using .take(1) after .map(), .prefetch() without checking shape</li><li><strong>Why It Crashes</strong>: Unexpected tensor dimensions</li><li><strong>Fix</strong>: Print shapes to verify early:</li></ul><pre>for x, y in train_ds.take(1):     print(x.shape, y.shape)</pre><h3>5. 🧩 Mismatch in Output Layer vs. Label Dimensions</h3><ul><li><strong>Code Issue</strong>: One-hot labels + sparse loss, or sparse labels + softmax + categorical loss</li><li><strong>Why It Crashes</strong>: Misaligned tensors</li><li><strong>Fix</strong>:</li><li>One-hot → Dense(n_classes) + categorical_crossentropy</li><li>Sparse → Dense(n_classes) + sparse_categorical_crossentropy</li></ul><h3>6. 📉 class_weight with tf.data.Dataset</h3><ul><li><strong>Code Issue</strong>: Using class_weight when labels come from tf.data.Dataset</li><li><strong>Why It Crashes</strong>: class_weight is not supported with dataset generators unless yielding int labels</li><li><strong>Fix</strong>: Either:</li><li>Yield sparse labels</li><li>Switch to oversampling or weighted loss</li></ul><h3>7. 🛜 Prefetch Not Using AUTOTUNE</h3><ul><li><strong>Code Issue</strong>: Using .prefetch(1)</li><li><strong>Why It Crashes</strong>: Static buffer can’t handle async ops efficiently</li></ul><pre>dataset = dataset.prefetch(tf.data.AUTOTUNE)</pre><h3>🧠 Conclusion</h3><p>Use Cloud.</p><p>Use Class_weight carefully.</p><p>Can use “sparse” if dataset is small &amp; compatible.</p><p>Check if dataset is batched/unbatched.</p><p>Accessing len(sample) may cause a crash if sample is a TensorFlow tensor rather than a Python container. Avoid calling len() on TensorFlow tensors or dataset elements (use .shape and .numpy() to inspect)</p><p>Use tf.equal instead of == to compare.</p><p><strong>Using </strong><strong>tf.cond with datasets sometimes causes issues</strong> because it creates conditional branches inside the graph.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a1c5a9562f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Transfer Learning in CNNs work.]]></title>
            <link>https://medium.com/superdatascience/how-transfer-learning-in-cnns-work-47547569cd05?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/47547569cd05</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Tue, 27 May 2025 05:29:25 GMT</pubDate>
            <atom:updated>2025-06-06T05:57:46.171Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transfer Learning: What does it mean?</h3><p><strong>Transfer learning</strong> is when a machine learning model uses what it learned from one task (like recognizing animals in photos) to help solve a new, related task (recognizing crops from photos). Instead of starting from scratch, it builds on what it already knows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCVRbaBNbFxq5p_CcoDwCQ.png" /><figcaption>Basic architecture for any transfer learning model</figcaption></figure><h3>Why do we need it?</h3><ul><li>Training big models from scratch takes a lot of time, data, and computing power. Transfer learning lets you use existing models, hence <strong>Saves Time and Resources</strong>.</li><li>Many real-world problems don’t have huge labeled datasets. Transfer learning lets you <strong>build good models with less data</strong> by reusing what was learned from larger datasets.</li><li>Models often <strong>perform better</strong> when they start with knowledge from a related task, especially when data is limited.</li><li>Since the model already knows a lot, you just need to tweak it for your specific problem, which is <strong>much quicker than full training</strong>.</li></ul><h3>Step-by-Step with MobileNetV2 Example (code is towards the end)</h3><p>This assumes that the dataset of images is already split and other preprocessing like augmentation, class_weight check, imbalance etc are already taken care. <a href="https://www.kaggle.com/datasets/nafishamoin/new-bangladeshi-crop-disease">Dataset used is here</a>.</p><h4>1. Deciding on a model</h4><p>Top 10 models are as below. Have a look and decide which will be useful in your application. The below models are all trained on “ImageNet” dataset which is an image dataset for millions of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjVErBMtBYhnkVDAKlINmw.png" /></figure><h4>Some help in choosing:</h4><ul><li><strong>For mobile/embedded: </strong>Use <strong>MobileNetV2</strong> or <strong>SqueezeNet</strong> (very small and fast).</li><li><strong>For best accuracy with good speed: </strong>Use <strong>EfficientNet</strong> or <strong>ResNet</strong> (top performers, scalable).</li><li><strong>For small datasets or transfer learning: </strong>Use <strong>DenseNet</strong>, <strong>ResNet</strong>, or <strong>VGG</strong> (good feature reuse, easy to fine-tune).</li><li><strong>For educational or simple projects: </strong>Use <strong>AlexNet</strong> or <strong>VGG</strong> (easy to understand and implement).</li><li><strong>For auto-discovered architectures: </strong>Use <strong>NASNet</strong> (if you want to experiment with cutting-edge models).</li><li><strong>For scene or multi-scale recognition: </strong>Use <strong>GoogLeNet/Inception</strong> (handles features at different scales).</li></ul><h4>2. Modify Data as per the Model Requirements</h4><ul><li>Which ever model you choose, ensure to modify the data as per the model (e.g., 224x224x3 for MobileNetV2).</li><li>Normalize or preprocess images as required (e.g., scale pixel values or use a specific preprocessing function). MobileNet needs pixels between 0–1.</li><li>Apply data augmentation (random flips, rotations) to make the model robust and avoid overfitting.</li></ul><h4>3. Training the model</h4><ul><li>Decide if you want to:<br>1. Freeze all base model layers (train only the new head)?<br>2. Unfreeze and fine-tune some or all layers (e.g., last 10, 50, or all).</li><li>Freeze more layers if your dataset is small or similar to ImageNet.</li><li>Fine-tune more layers if your dataset is large or very different from ImageNet.</li></ul><p><strong>First let’s see how the model looks without training:</strong></p><pre>base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,<br>                                               include_top=True,<br>                                               weights=&#39;imagenet&#39;)</pre><p><strong>What does </strong><strong>include_top = True do?</strong></p><ul><li>It means the model includes the final dense classification layer (the “top”) that was trained on ImageNet’s 1000 classes.</li><li>If you set weights=&#39;imagenet&#39;, the final layer is set up to predict ImageNet classes, not your custom classes.</li></ul><p><strong>Is it possible to train model if we do </strong><strong>include_top = True?</strong></p><ul><li>No, not directly for your dataset. If you use include_top=True and weights=&#39;imagenet&#39;, the output layer is fixed for 1000 ImageNet classes, not your dataset’s classes.</li><li>You can technically “train” (fit) the model if you add more layers on top, but with include_top=True and base_model.trainable = False, you can’t adapt it to your own classes or fine-tune it for your data.</li></ul><p><strong>How will the model perform without training on “our” dataset?</strong></p><ul><li>If you call model.evaluate() on your data the accuracy will be meaningless unless your dataset has the same 1000 classes as ImageNet, in the same order.</li><li>If your data is not ImageNet-formatted, the predictions will not match your labels, so accuracy will be very low or random.</li></ul><p><strong>Printing the Last Two Layer Names</strong></p><pre>base_model_layers = len(base_model.layers)<br>print(base_model.layers[base_model_layers - 2].name)<br>print(base_model.layers[base_model_layers - 1].name)</pre><ul><li>The last two layers are the final Dense (classification) layer and the layer right before it (often a Flatten or pooling layer, depending on the architecture).</li></ul><p><strong>My Output (for MobileNetV2):</strong></p><pre>global_average_pooling2d_1<br>predictions</pre><p>The exact names depend on the model, but the last layer (base_model.layers[-1]) will always be the classification Dense layer for 1000 ImageNet classes.</p><p><strong>Checking the Model shape</strong></p><pre>image_batch, label_batch = next(iter(train_dataset))<br>feature_batch = base_model(image_batch)<br>print(feature_batch.shape)</pre><ul><li>feature_batch will be the output of the final Dense layer. <strong>Shape:</strong> (batch_size, 1000)</li><li>Each image gets a vector of 1000 values (one per ImageNet class) and my batch_size was 32.</li></ul><p><strong>My Output (for MobileNetV2):</strong></p><pre>(32, 1000)</pre><ul><li>The model is predicting the probability (or logits) for each of the 1000 ImageNet classes for every image in your batch. These outputs are not meaningful for your own dataset unless it matches ImageNet’s classes and label order.</li></ul><p><strong>Checking the model accuracy without training (which is almost 0)</strong></p><pre>base_model.compile(<br>    optimizer=&#39;adam&#39;,                 # or any optimizer you like<br>    loss=&#39;sparse_categorical_crossentropy&#39;,  # match your label format<br>    metrics=[&#39;accuracy&#39;]<br>)</pre><pre># For validation data<br>val_loss, val_acc = base_model.evaluate(validation_dataset)</pre><pre># For train data<br>train_loss, train_acc = base_model.evaluate(train_dataset)</pre><pre>Output:<br>41/41 ━━━━━━━━━━━━━━━━━━━━ 49s 1s/step - accuracy: 0.0000e+00 - loss: 9.1643<br>326/326 ━━━━━━━━━━━━━━━━━━━━ 345s 1s/step - accuracy: 0.0000e+00 - loss: 9.1999</pre><p><strong>Checking 15 classes of base_model without training to confirm</strong></p><pre>labels_path = tf.keras.utils.get_file(&#39;imagenet_class_index.json&#39;,<br>    &#39;https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json&#39;<br>)<br>with open(labels_path) as f:<br>    class_dict = json.load(f)<br>for i in range(15):<br>    print(f&quot;{i}: {class_dict[str(i)][1]}&quot;)</pre><pre>Output:<br>Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json<br>35363/35363 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step<br>0: tench<br>1: goldfish<br>2: great_white_shark<br>3: tiger_shark<br>4: hammerhead<br>5: electric_ray<br>6: stingray<br>7: cock<br>8: hen<br>9: ostrich<br>10: brambling<br>11: goldfinch<br>12: house_finch<br>13: junco<br>14: indigo_bunting</pre><h4>4. Make the Model Trainable</h4><pre>base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,<br>                                               include_top=False,<br>                                               weights=&#39;imagenet&#39;)<br>base_model.trainable = False</pre><pre># Confirm that the last 2 layers are now different from previous.<br>b_layers = len(base_model.layers)<br>print(base_model.layers[b_layers - 2].name)<br>print(base_model.layers[b_layers - 1].name)</pre><pre>Output:<br>Conv_1_bn<br>out_relu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rouR3nh5U7g2sllGtLqPJg.png" /></figure><h4>Adding our own layers</h4><pre># create the input layer (Same as the imageNetv2 input size)<br>inputs = tf.keras.Input(shape=IMG_SHAPE)</pre><pre># apply data augmentation to the inputs<br>x = data_augmentation(inputs)</pre><pre># add the new Binary classification layers<br># use global avg pooling to summarize the info in each channel<br>x = GlobalAveragePooling2D()(x)</pre><pre>x = Dropout(0.2)(x)</pre><pre>output_tensor = Dense(num_classes, activation=&#39;softmax&#39;)(x)</pre><pre>model = tf.keras.Model(inputs=inputs, outputs=output_tensor)</pre><h4>5. Compile the Model (standard process)</h4><p><strong>Always recompile</strong> the model after changing the trainable property of any layers</p><pre>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&#39;sparse_categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])<br>history = model.fit(<br>    train_dataset,<br>    validation_data<br>    epochs=5<br>)</pre><pre>Output:<br>Epoch 1/5<br>50/50 ━━━━━━━━━━━━━━━━━━━━ 84s 2s/step - accuracy: 0.3960 - loss: 1.8633 - val_accuracy: 0.8156 - val_loss: 0.4961<br>Epoch 2/5<br>50/50 ━━━━━━━━━━━━━━━━━━━━ 75s 1s/step - accuracy: 0.7742 - loss: 0.5904 - val_accuracy: 0.8687 - val_loss: 0.3591<br>Epoch 3/5<br>50/50 ━━━━━━━━━━━━━━━━━━━━ 75s 2s/step - accuracy: 0.8363 - loss: 0.4452 - val_accuracy: 0.8828 - val_loss: 0.3008<br>Epoch 4/5<br>50/50 ━━━━━━━━━━━━━━━━━━━━ 74s 1s/step - accuracy: 0.8352 - loss: 0.4091 - val_accuracy: 0.8906 - val_loss: 0.2748<br>Epoch 5/5<br>50/50 ━━━━━━━━━━━━━━━━━━━━ 74s 1s/step - accuracy: 0.8374 - loss: 0.3763 - val_accuracy: 0.8984 - val_loss: 0.2651</pre><h4>6. Training the Last X Layers of a Pretrained Model</h4><p>If you want to <strong>fine-tune only the last X layers (lets say X = 10) </strong>of your base model (e.g., MobileNetV2), you need to:</p><ol><li>Freeze all layers except the last 10.</li><li>Set the last 10 layers as trainable.</li><li>Recompile the model after making these changes.</li></ol><pre>base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,<br>include_top=False, weights=&#39;imagenet&#39;)<br>  <br># Freeze all layers first<br>base_model.trainable = False<br>  <br># Unfreeze the last 10 layers<br>for layer in base_model.layers[-10:]:<br>   layer.trainable = True<br>  <br># (Re)build your custom head  <br>x = base_model.output<br>x = GlobalAveragePooling2D()(x)<br>x = Dropout(0.2)(x)<br>outputs = Dense(1, activation=&#39;sigmoid&#39;)(x) # For binary classification<br>  <br>model = Model(inputs=base_model.input, outputs=outputs)<br>  <br># Recompile after changing trainable status<br>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><ul><li>This lets you fine-tune only the last 10 layers, which is useful if you want to adapt the model to your data without overfitting or requiring too much data.</li><li>You can change the number of layers to unfreeze by adjusting base_model.layers[-10:] to any number you want. Always check base_model.summary() to see which layers you’re unfreezing!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uc-ialt_pT8lXh5VerO3uQ.png" /></figure><h3>Misc steps</h3><ul><li><strong>Split Data: </strong>Split your data into training, validation, and test sets for unbiased evaluation.</li><li><strong>Monitor Performance: </strong>Track loss and accuracy during training to avoid overfitting and underfitting.</li><li><strong>Fine-tune: </strong>After initial training, unfreeze some base model layers and continue training with a lower learning rate for better adaptation to your data.</li></ul><h4>Datasets Similar to ImageNet</h4><ul><li><strong>COCO (Common Objects in Context): </strong>Over 330,000 images, 80 object categories, used for object detection, segmentation, and captioning.</li><li><strong>Google Open Images: </strong>Over 9 million images with bounding boxes, segmentation masks, and visual relationships, covering hundreds of categories.</li><li><strong>Places2 (365-Standard): </strong>1.8 million images across 365 scene categories, useful for scene recognition.</li><li><strong>Pascal VOC: </strong>20 object classes, 11,530 images, used for object detection and segmentation.</li><li><strong>LSUN: </strong>Millions of labeled images for scene and object categories.</li><li><strong>Stanford Dogs: </strong>20,580 images, 120 dog breeds, built using ImageNet images.</li><li><strong>Fashion-MNIST: </strong>70,000 images of clothing items, used for image classification and benchmarking.</li><li><strong>DeepFashion: </strong>800,000+ clothing images with attributes, used for fashion-related computer vision tasks.</li></ul><h3>When Not to Use Transfer Learning</h3><p>Transfer learning is powerful, but it’s not always the right choice. Here are the main situations where you should <strong>not</strong> use transfer learning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*yyb1sNKREGEUcAnhmpukpg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47547569cd05" width="1" height="1" alt=""><hr><p><a href="https://medium.com/superdatascience/how-transfer-learning-in-cnns-work-47547569cd05">How Transfer Learning in CNNs work.</a> was originally published in <a href="https://medium.com/superdatascience">SuperDataScience</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods to increase the number of images in a dataset]]></title>
            <link>https://medium.com/@tehreemansari/methods-to-increase-the-number-of-images-in-a-dataset-48904a18522b?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/48904a18522b</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Fri, 23 May 2025 17:40:20 GMT</pubDate>
            <atom:updated>2025-05-23T17:40:20.702Z</atom:updated>
            <content:encoded><![CDATA[<p>While working with images, one main issue is shortage of specific classes (bias towards classes). Hence it’s important to increase the number of data for the class which has originally few images.</p><p>I will the before and after images in sometime (need to note down else it will get lost).</p><h3>Core Augmentation Techniques (Input Space)</h3><h3>1. Geometric Transformations</h3><ul><li><strong>Rotation</strong> (RandomRotation(30)): 30° rotations</li><li><strong>Flipping</strong>: Horizontal/vertical mirroring</li><li><strong>Perspective Warp</strong>: Simulate 3D viewpoint changes</li><li><strong>Elastic Deformation</strong>: Stretch images like rubber</li></ul><pre># TensorFlow implementation<br>aug = tf.keras.Sequential([<br>layers.RandomFlip(&quot;horizontal&quot;),<br>layers.RandomRotation(0.2),<br>layers.RandomZoom(0.2)<br>])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*I8IBIRTifHxD1JQPzeQrEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*iD0htX9cegk3FSNnc4UGpg.png" /><figcaption>Notice the “lines” added after transformation.</figcaption></figure><h3>2. Photometric Adjustments</h3><ul><li><strong>Color Jitter</strong>: Random brightness/contrast/hue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhSLFl7MHzcEIAE1bSaGeQ.png" /><figcaption>Colour Jitter</figcaption></figure><ul><li><strong>Channel Shuffling</strong>: Swap RGB channels</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDJsYqz4vtC4OqIv1_2m7Q.png" /><figcaption>Channel Shuffling</figcaption></figure><ul><li><strong>Solarization</strong>: Invert colors above threshold</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tF7iQUMJOTslCilYQUkQlA.png" /><figcaption><strong>Solarization</strong></figcaption></figure><ul><li><strong>CLAHE</strong>: Contrast-limited adaptive histogram equalization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7-MV-px4TG8Hm-5FGW4mg.png" /><figcaption><strong>CLAHE</strong></figcaption></figure><h3>3. Noise Injection</h3><ul><li><strong>Gaussian Noise</strong>: Add pixel-level randomness</li><li><strong>Salt &amp; Pepper</strong>: Black/white pixel dropout</li><li><strong>Speckle Noise</strong>: Multiplicative noise pattern</li></ul><pre># Gaussian noise example<br>def  add_noise(image):<br>noise = tf.random.normal(tf.shape(image), mean=0, stddev=0.1)<br>return image + noise</pre><h3>4. Occlusion Methods</h3><ul><li><strong>Random Erasing</strong>: Delete rectangular regions</li><li><strong>CutOut</strong>: Remove square sections</li><li><strong>GridMask</strong>: Regular pattern masking</li></ul><h3>Advanced Synthesis Techniques</h3><h3>5. Image Mixing</h3><ul><li><strong>MixUp</strong>: Linear image blending</li><li><strong>CutMix</strong>: Patch replacement with label mixing</li><li><strong>Mosaic</strong>: 4-image grid combination</li></ul><h3>6. Feature Space Augmentation</h3><ul><li><strong>Adversarial Examples</strong>: Small perturbed images</li><li><strong>Style Transfer</strong>: Preserve content, change style</li><li><strong>Feature Jittering</strong>: Add noise to latent vectors</li></ul><h3>7. Generative Models</h3><ul><li><strong>GANs</strong>: Generate new images via discriminator</li><li><strong>Diffusion Models</strong>: Iterative denoising process</li><li><strong>VAEs</strong>: Latent space sampling</li></ul><h3>Strategic Sampling Methods</h3><h3>8. Oversampling Techniques</h3><ul><li><strong>SMOTE</strong>: Create synthetic minority samples</li><li><strong>Duplication</strong>: Simple copy-paste</li><li><strong>Borderline-SMOTE</strong>: Focus on class boundary samples</li></ul><h3>9. Domain Adaptation</h3><ul><li><strong>Style Randomization</strong>: Vary textures/backgrounds</li><li><strong>Weather Simulation</strong>: Add rain/snow/fog</li><li><strong>Sensor Noise</strong>: Simulate camera artifacts</li></ul><h3>Specialized Approaches</h3><h3>10. Meta-Learning</h3><ul><li><strong>Neural Augmentation</strong>: Learn augmentation policies</li><li><strong>AutoAugment</strong>: RL-discovered strategies</li></ul><h3>11. Multimodal Fusion</h3><ul><li><strong>Text-to-Image</strong>: Stable Diffusion prompts</li><li><strong>Sketch-to-Photo</strong>: Edge map conversions</li></ul><h3>Gaussian Noise vs Diffusion</h3><p><strong>Gaussian Noise</strong> adds random pixel variations in one step, while <strong>Diffusion Models</strong> use iterative noising/denoising to learn data distributions. They’re fundamentally different:</p><ul><li><strong>Gaussian Noise</strong>: Simple regularization technique</li><li><strong>Diffusion</strong>: Full generative framework requiring:</li></ul><ol><li>Forward noising process</li><li>Neural network denoising training</li><li>Iterative sampling</li></ol><h3>Implementation Checklist</h3><ol><li>Start with basic geometric+photometric transforms</li><li>Add noise/occlusion for robustness</li><li>Use MixUp/CutMix for class imbalance</li><li>Deploy GANs/diffusion for hard cases</li><li>Apply test-time augmentation for consistency</li></ol><pre># Required packages<br>mamba  install  tensorflow  imgaug  opencv-python</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48904a18522b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameter Tuning Strategies Based on Training History]]></title>
            <link>https://medium.com/@tehreemansari/hyperparameter-tuning-strategies-based-on-training-history-2c79b24e8031?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c79b24e8031</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[cnn-model]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Fri, 23 May 2025 17:08:45 GMT</pubDate>
            <atom:updated>2025-05-23T17:08:45.208Z</atom:updated>
            <content:encoded><![CDATA[<p>This is just my notes to try out different techniques for tuning. (I am using <a href="https://www.kaggle.com/datasets/nafishamoin/new-bangladeshi-crop-disease">this crop data</a> and MobileNetV2). I need to add more details and why does it help. For now I’ve just jotted down the techniques.</p><h3>If Loss Plateaus:</h3><ol><li><strong>Learning Rate Scheduling</strong></li></ol><pre>lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(<br>initial_learning_rate=1e-3,<br>decay_steps=1000,<br>decay_rate=0.9)</pre><p><em>Gradually reduce learning rate</em></p><p><strong>2. Increase Batch Size</strong></p><p>batch_size=64 → 128 if GPU memory allows</p><p><strong>3. Optimizer Switching</strong></p><p>From RMSprop to Adam(epsilon=1e-7)</p><h3>If Overfitting (Val Loss ↗):</h3><ol><li><strong>Add Spatial Dropout</strong></li></ol><pre>model.add(layers.SpatialDropout2D(0.5))</pre><p><em>More effective than standard dropout (.Dropout())for CNNs</em></p><p><strong>2. Stronger Data Augmentation</strong></p><p>Add zoom_range=0.3, shear_range=0.2</p><p><strong>3. Label Smoothing</strong></p><pre>loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1)</pre><p><em>Prevents overconfident predictions</em></p><h3>If Underfitting (Train Acc Low):</h3><ol><li><strong>Unfreeze More Layers</strong></li></ol><pre>for layer in base_model.layers[-20:]:<br>layer.trainable = True #transfer learning</pre><p><em>Allow feature adaptation</em></p><p><strong>2. Increase Input Resolution</strong></p><p>input_shape=(300,300,3) instead of input_shape=(224,224,3)</p><p><strong>3. Add Head Complexity</strong></p><pre>x = layers.Dense(256, activation=&#39;relu&#39;)(x)</pre><p><em>Before final softmax layer</em></p><h3>General Improvements:</h3><ol><li><strong>Batch Size Warmup</strong></li></ol><p>Start with batch_size=32, increase to 128 over epochs</p><p><strong>2. Optimizer Param Tuning</strong></p><pre>Adam(beta_1=0.85, beta_2=0.995) (beta params of Adam&#39;s formula)</pre><p><em>Adjust momentum parameters</em></p><p><strong>3. Stochastic Weight Averaging</strong></p><pre>optimizer = tfa.optimizers.SWA(Adam())</pre><p><em>Better generalization</em></p><p><strong>4. Class Weight Balancing</strong></p><pre>class_weights = {0:1, 1:2.5, 2:1.8, 3:3}<br>model.fit(..., class_weight=class_weights)</pre><p><em>For imbalanced crops</em></p><p><strong>5. Gradient Clipping</strong></p><pre>optimizer = Adam(clipvalue=0.5)</pre><p><em>Prevent exploding gradients</em></p><p><strong>6. Hyperparameter Search</strong></p><pre>tuner = BayesianOptimization(<br>build_model,<br>objective=&#39;val_accuracy&#39;,<br>max_trials=20)</pre><p><em>Automated parameter tuning</em></p><h3>Implementation Requirements</h3><p>ie, required packages</p><pre>mamba  install  tf-keras-vis  scikit-learn  matplotlib  pillow</pre><p><strong>Other Notes</strong></p><ul><li>Visualization techniques from <a href="http://neptune.ai/">Neptune.ai</a></li><li>Hyperparameter strategies from Encord &amp; PMC</li><li>MobileNetV2 implementation from Roboflow</li></ul><p>Use these visual diagnostics and tuning strategies iteratively — start with 3–5 most relevant to your observed issues, then expand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c79b24e8031" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A comprehensive guide to visualizing models (using MobileNetV2 example)]]></title>
            <link>https://medium.com/@tehreemansari/a-comprehensive-guide-to-visualizing-models-using-mobilenetv2-example-2e51512e9db7?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e51512e9db7</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[cnn]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Fri, 23 May 2025 16:57:29 GMT</pubDate>
            <atom:updated>2025-05-23T16:57:29.630Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my notes for visualizing my CNN models. It’s a reference doc, I will add the details once I have time.</p><h3>1. Model Architecture Visualization</h3><p><em>Visualize layer connections and output shapes</em></p><pre>from tensorflow.keras.utils import plot_model<br>plot_model(model, show_shapes=True, show_layer_names=True)</pre><h3>2. Activation Heatmaps</h3><p><em>See which image regions activate specific filters</em></p><pre>from tf_keras_vis import ActivationMaximization<br>visualize_activations(model, layer_name=&#39;block_12_expand_relu&#39;)</pre><h3>3. Class-Specific Feature Visualization</h3><p><em>Reveals what visual patterns your model associates with each crop disease</em></p><pre># Generate synthetic patterns that maximally activate output neurons<br>from tf_keras_vis import activation_maximization<br>activations = activation_maximization(model.output[^0][class_idx])</pre><h3>4. Training History Dashboard</h3><p><em>Monitor overfitting/underfitting trends</em></p><pre>import matplotlib.pyplot as plt<br>plt.figure(figsize=(12,4))<br>plt.subplot(1,2,1)<br>plt.plot(history.history[&#39;accuracy&#39;], label=&#39;Train Acc&#39;)<br>plt.subplot(1,2,2)<br>plt.plot(history.history[&#39;loss&#39;], label=&#39;Train Loss&#39;)</pre><h3>5. Confusion Matrix</h3><p><em>Identify class-specific errors</em></p><pre>from sklearn.metrics import ConfusionMatrixDisplay<br>ConfusionMatrixDisplay.from_predictions(y_true, y_pred)</pre><h3>6. ROC Curve Analysis</h3><p><em>Evaluate per-class discrimination ability</em></p><pre>from sklearn.metrics import RocCurveDisplay<br>RocCurveDisplay.from_predictions(y_true, y_pred_prob)</pre><h3>7. Grad-CAM Visualizations</h3><p><em>Highlight decision-making regions in images</em></p><pre>!pip install tf-keras-vis<br>from tf_keras_vis.gradcam import Gradcam<br>cam = Gradcam(model)<br>heatmap = cam(class_idx, seed_input)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*G9UZgkeq8e6MFhW3x1_P0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*o4E5pDVFQyJjI_jfNuup6g.png" /></figure><h3>8. t-SNE Feature Projections</h3><p><em>Visualize cluster separation in latent space</em></p><pre>from sklearn.manifold import TSNE<br>embeddings = feature_extractor.predict(images)<br>tsne = TSNE(n_components=2).fit_transform(embeddings)</pre><h3>9. Layer Activation Distributions</h3><p><em>Histograms of activation values per layer</em></p><pre>layer_outputs = [layer.output for layer in model.layers[:8]]<br>activation_model = Model(inputs=model.input, outputs=layer_outputs)<br>activations = activation_model.predict(img)</pre><h3>10. Kernel Visualization</h3><p><em>Visualize initial convolution filters</em></p><pre>first_layer_weights = model.layers[^2].get_weights()[^0]<br>plt.imshow(first_layer_weights[:,:,:,0].squeeze(), cmap=&#39;viridis&#39;)</pre><h3>11. Attention Map Comparisons</h3><p><em>For models with attention mechanisms</em></p><pre># Compare base MobileNetV2 vs fine-tuned attention<br>attention_model = build_attention_model(base_model)<br>plot_attention_overlay(original_img, attention_map)</pre><h3>12. Error Analysis Grid</h3><p><em>Display images with highest loss values</em></p><pre>plot_top_losses(model, validation_data, n=9)</pre><h3>13. Data Augmentation Preview</h3><p><em>Verify augmentation effectiveness</em></p><pre>augmented = train_datagen.flow_from_directory(...)<br>plot_augmented_samples(augmented, n=9)</pre><h3>14. Saliency Maps</h3><p><em>Pixel-level importance visualization</em></p><pre>from tf_keras_vis.saliency import Saliency<br>saliency = Saliency(model)<br>saliency_map = saliency(class_idx, seed_input)</pre><h3>15. Training-Validation Divergence</h3><p><em>Early stopping indicator</em></p><pre>plt.plot(history.history[&#39;val_loss&#39;], label=&#39;Val Loss&#39;)<br>plt.plot(history.history[&#39;loss&#39;], label=&#39;Train Loss&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e51512e9db7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-step CNN]]></title>
            <link>https://medium.com/superdatascience/step-by-step-cnn-ab5cac62597c?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5cac62597c</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Mon, 19 May 2025 19:45:36 GMT</pubDate>
            <atom:updated>2025-05-20T16:25:05.995Z</atom:updated>
            <content:encoded><![CDATA[<h3>📑 Table of Contents</h3><p><em>Step 1: Define the Problem &amp; Setup</em></p><p><em>Step 2: Organize the Data</em></p><p><em>Step 3: Define the Folders in Code</em></p><p><em>Step 4: Analyze the Data<br> 4.a. Count the Samples / Visualize<br> 4.b. Identify Corrupt Images</em></p><p><em>Step 5: Define the Data Augmentation Pipeline</em></p><p><em>Step 6: Load Data</em></p><p><em>Step 7: Resize the Classes (if needed)</em></p><p><em>Step 8: Build CNN Model (Generic)</em></p><p><em>Step 9: Compile Model</em></p><p><em>Step 10: Set Callbacks</em></p><p><em>Step 11: Train Model</em></p><p><em>Step 12: Plot Training History</em></p><p><em>Step 13: Evaluate Model on Validation Set</em></p><p><em>Step 14: Confusion Matrix</em></p><p><em>Step 15: Save Model</em></p><p>🔑 Key Points Recap</p><ul><li>I am running the code on Google Colab and my data is uploaded in drive.</li><li>In production, CNNs are generally not built from scratch, but it is better to know the basics before using transfer learning.</li><li>The entire code is <a href="https://github.com/TehreemAnsari/CodesForSharing/blob/main/code_for_cnn.ipynb">available here</a>.</li></ul><h3>Step 1: Define the Problem &amp; setup</h3><p>We want to build a CNN model that can classify crop diseases from images using the <a href="https://www.kaggle.com/datasets/nafishamoin/new-bangladeshi-crop-disease">Bangladeshi Crop Disease Dataset.</a></p><p>Install the packages using pip/mamba/conda:</p><pre>mamba install \<br>  python=3.10 \<br>  tensorflow \<br>  matplotlib \<br>  seaborn \<br>  scikit-learn \<br>  pillow \<br>  numpy</pre><ul><li>tensorflow includes keras.</li><li>scikit-learn includes confusion_matrix.</li><li>pillow provides the PIL module.</li><li>ImageDataGenerator, img_to_array, and load_img are all part of tensorflow.keras.preprocessing.image.</li><li>defaultdict and os are part of Python&#39;s standard library and don&#39;t need installation.</li></ul><h3>Step 2: Organize the data</h3><ul><li>The dataset is organized by crop disease classes in folders (e.g., Tomato___Early_blight, Potato___Late_blight, etc.).</li><li>We want to classify images into these disease classes.</li></ul><p>Assume dataset is structured like this:</p><pre>bangladeshi_crop_disease/<br>├── train/<br>│   ├── Rice_Brown_Spot/<br>│   ├── Rice_Blast/<br>│   ├── Potato_Late_Blight/<br>│   └── ... (15 classes)<br>└── val/<br>    ├── Rice_Brown_Spot/<br>    └── ... (same class folders)</pre><h3>Step 3: Define the folders in code</h3><p>All the imports which will be used for below code here:</p><pre># === Standard Library Imports ===<br>import os  # For file and directory operations<br>from collections import defaultdict  # For creating dictionaries with default values<br><br># === Other Library Imports for ML===<br>import numpy as np  # For numerical operations and array handling<br>import matplotlib.pyplot as plt  # For plotting graphs and images<br>import seaborn as sns  # For advanced visualization, e.g., heatmaps<br>from PIL import Image  # For image processing and manipulation<br>from sklearn.metrics import confusion_matrix  # For evaluating classification performance<br><br># === TensorFlow and Keras Imports ===<br>import tensorflow as tf  # Core TensorFlow library<br>from tensorflow.keras import layers, models  # For building neural network layers and models<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img  # For image preprocessing and augmentation</pre><pre># This block because my data is in google drive<br>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)</pre><pre>DATA_DIR = &quot;/content/drive/My Drive/Colab Notebooks/Data&quot;<br>train_dir = os.path.join(DATA_DIR, &#39;train&#39;)<br>val_dir = os.path.join(DATA_DIR, &#39;val&#39;)<br><br><br>print(train_dir)<br>print(val_dir)</pre><h3>Step 4.a: Count the samples/visualize</h3><pre>def count_class_images(directory):<br>    counts = defaultdict(int)<br>    # List all class folders<br>    for class_name in os.listdir(directory):<br>        class_path = os.path.join(directory, class_name)<br>        if os.path.isdir(class_path):<br>            # Count all image files in class folder<br>            counts[class_name] = len([<br>                f for f in os.listdir(class_path)<br>                if f.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;))<br>            ])<br>    return counts<br><br># Get counts<br>class_counts = count_class_images(train_dir)<br><br># Print formatted results<br>print(&quot;Training images per class:&quot;)<br>for class_name, count in sorted(class_counts.items()):<br>    print(f&quot;{class_name}: {count} images&quot;)</pre><h3>Step 4.b: Identify corrupt images</h3><p>In tabular data we identify corrupt data as NULL/NA/undefined etc. For images corrupt images are identified if they are non-image files/images that cannot be opened.</p><pre>#Remove Corrupt Images<br>def remove_corrupt_images(directory):<br>    corrupted_files = []<br>    for dirpath, _, filenames in os.walk(directory):<br>        for filename in filenames:<br>            normalized_name = filename.strip().lower()<br>            if normalized_name.endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;, &#39;.bmp&#39;, &#39;.tiff&#39;, &#39;.gif&#39;)):<br>                file_path = os.path.join(dirpath, filename)<br>                try:<br>                    with Image.open(file_path) as img:<br>                        img.verify()<br>                except Exception as e:<br>                    corrupted_files.append(file_path)<br>                    print(f&quot;Corrupt image found and deleted: {file_path} ({e})&quot;)<br>                    os.remove(file_path)<br>            else:<br>                print(f&quot;Unknown file format ignoring: {filename}&quot;)<br>    print(f&quot;Total corrupt images deleted: {len(corrupted_files)}&quot;)<br><br><br><br>remove_corrupt_images(train_dir)</pre><h3>Step 5: Define the data augmentation pipeline</h3><pre># Define constants<br>IMAGE_SIZE = (224, 224) # Standard size<br>BATCH_SIZE = 32</pre><pre># Normalize and augment training dataset<br>train_datagen = ImageDataGenerator(<br>    rescale=1./255,       # Normalizes the data<br>    rotation_range=15,    # Augmentation via rotation<br>    zoom_range=0.1,       # Augmentation via zoom<br>    horizontal_flip=True  # Augmentation via flipping the image<br>)<br><br># Only normalize the validation dataset<br>val_datagen = ImageDataGenerator(rescale=1./255)</pre><h3>Step 4: Load Data</h3><pre># Path to dataset directory (adjust path)<br>dataset_dir = &quot;data/bangladeshi_crop_disease/&quot;<br>train_dir = os.path.join(DATA_DIR, &#39;train&#39;)<br>val_dir = os.path.join(DATA_DIR, &#39;val&#39;)<br><br>  <br>train_gen = train_datagen.flow_from_directory(<br>    train_dir,<br>    target_size=IMAGE_SIZE,<br>    batch_size=BATCH_SIZE,<br>    class_mode=&#39;sparse&#39;<br>)<br><br>num_classes = train_gen.num_classes<br><br>val_gen = val_datagen.flow_from_directory(<br>    val_dir,<br>    target_size=IMAGE_SIZE,<br>    batch_size=BATCH_SIZE,<br>    class_mode=&#39;sparse&#39;,<br>    shuffle=False<br>)</pre><h3>Step 5: Resize the classes if needed</h3><pre>def augment_images(source_dir, dest_dir, increase_by=3):<br>    &quot;&quot;&quot;<br>    Augments images in source_dir and saves them in dest_dir<br>    so that total images become increase_by times original count.<br>    &quot;&quot;&quot;<br>    datagen = ImageDataGenerator(<br>        rotation_range=30,<br>        width_shift_range=0.1,<br>        height_shift_range=0.1,<br>        shear_range=0.1,<br>        zoom_range=0.1,<br>        horizontal_flip=True,<br>        fill_mode=&#39;nearest&#39;<br>    )<br>    <br>    image_files = [f for f in os.listdir(source_dir) if f.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;))]<br>    n_original = len(image_files)<br>    n_to_generate = n_original * (increase_by - 1)  # how many new images needed<br><br>    print(f&quot;Original images: {n_original}, Will generate: {n_to_generate}&quot;)<br><br>    generated = 0<br>    for img_name in image_files:<br>        if generated &gt;= n_to_generate:<br>            break<br>        img_path = os.path.join(source_dir, img_name)<br>        img = load_img(img_path)<br>        x = img_to_array(img)<br>        x = np.expand_dims(x, 0)<br>        # How many augmentations for this image?<br>        n_aug = (n_to_generate - generated) // (n_original - image_files.index(img_name))<br>        n_aug = max(1, n_aug)<br>        for i, batch in enumerate(datagen.flow(x, batch_size=1, save_to_dir=dest_dir,<br>                                               save_prefix=&#39;aug&#39;, save_format=&#39;jpg&#39;)):<br>            generated += 1<br>            if i+1 &gt;= n_aug or generated &gt;= n_to_generate:<br>                break<br>    print(f&quot;Augmentation complete. Total images in {dest_dir}: {len(os.listdir(dest_dir))}&quot;)<br><br># Example usage for Potato___Healthy<br>source_dir = &#39;/content/drive/My Drive/Colab Notebooks/Data/train/Potato___Healthy&#39;<br>dest_dir = source_dir  # You can use a different folder if you want<br>augment_images(source_dir, dest_dir, increase_by=3)</pre><h3>Step 6: Visualize the classes</h3><pre># Get class names (folder names)<br>class_names = [d for d in os.listdir(train_dir) if os.path.isdir(os.path.join(train_dir, d))]<br><br># Prepare subplots<br>n_classes = len(class_names)<br>plt.figure(figsize=(n_classes * 3, 3))<br><br>for idx, class_name in enumerate(sorted(class_names)):<br>    class_folder = os.path.join(train_dir, class_name)<br>    # Get list of image files in this class<br>    img_files = [f for f in os.listdir(class_folder) if f.lower().endswith((&#39;.jpg&#39;, &#39;.jpeg&#39;, &#39;.png&#39;))]<br>    if not img_files:<br>        continue  # skip if no images<br>    img_path = os.path.join(class_folder, img_files[0])  # Take the first image<br>    img = Image.open(img_path)<br>    plt.subplot(1, n_classes, idx + 1)<br>    plt.imshow(img)<br>    plt.title(class_name)<br>    plt.axis(&#39;off&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><h3>Step 7: Re-read the train dataset (if resize done)</h3><pre>train_gen = train_datagen.flow_from_directory(<br>    train_dir,<br>    target_size=IMAGE_SIZE,<br>    batch_size=BATCH_SIZE,<br>    class_mode=&#39;sparse&#39;<br>)</pre><h3>Step 8: Build CNN Model (Generic)</h3><pre>input_shape = (224, 224, 3)<br><br>model = models.Sequential([<br>    layers.Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=input_shape),<br>    layers.MaxPooling2D((2, 2)),<br>    layers.Conv2D(64, (3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    layers.Conv2D(128, (3, 3), activation=&#39;relu&#39;),<br>    layers.MaxPooling2D((2, 2)),<br>    layers.Flatten(),<br>    layers.Dense(64, activation=&#39;relu&#39;),<br>    layers.Dense(num_classes, activation=&#39;softmax&#39;)<br>])</pre><p>This one is “sequential” as I am not planning to extend it for anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlIYRZ8yAvunGyWEha93pA.png" /></figure><p>Explaination of how the values are calculated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dvaQ8h8UbwkQIMXmSQhCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Xrc66GIQxJI2Tnani38cw.png" /></figure><h3>Step 9: Compile Model</h3><pre>model.compile(<br>optimizer=&#39;adam&#39;,<br>loss=&#39;sparse_categorical_crossentropy&#39;,<br>metrics=[&#39;accuracy&#39;]<br>)<br><br>model.summary()</pre><h3>Step 10: Set Callbacks</h3><pre>callbacks = [<br>tf.keras.callbacks.EarlyStopping(monitor=&#39;val_loss&#39;, patience=3, restore_best_weights=True),<br>tf.keras.callbacks.ModelCheckpoint(&#39;model.keras&#39;, save_best_only=True)  # can be saved via model.save too (see below)<br>]</pre><h3>Step 11: Train Model</h3><pre>history = model.fit(<br>    train_gen,<br>    epochs=10,<br>    validation_data=val_gen,<br>    callbacks=callbacks, #Optional<br>    class_weight=class_weight_dict  #Optional<br>)</pre><h3>Step 12: Plot Training History</h3><pre>plt.plot(history.history[&#39;accuracy&#39;], label=&#39;train acc&#39;)<br>plt.plot(history.history[&#39;val_accuracy&#39;], label=&#39;val acc&#39;)<br>plt.xlabel(&#39;Epoch&#39;)<br>plt.ylabel(&#39;Accuracy&#39;)<br>plt.legend()<br>plt.show()</pre><h3>Step 13: Evaluate Model on Validation Set</h3><pre>val_loss, val_acc = model.evaluate(val_ds)<br>print(f&quot;Validation accuracy: {val_acc:.2f}&quot;)</pre><h3>Step 14: Confusion Matrix (Optional)</h3><pre># Get true labels and predictions<br>y_true = np.concatenate([y for x, y in val_ds], axis=0)<br>y_pred_probs = model.predict(val_ds)<br>y_pred = np.argmax(y_pred_probs, axis=1)<br>  <br>cm = confusion_matrix(y_true, y_pred)<br>  <br>plt.figure(figsize=(12, 10))<br>sns.heatmap(cm, xticklabels=class_names, yticklabels=class_names, annot=True, fmt=&#39;d&#39;)<br>plt.xlabel(&#39;Predicted&#39;)<br>plt.ylabel(&#39;True&#39;)<br>plt.show()</pre><h3>Step 15: Save Model</h3><pre>model.save(&quot;model.keras&quot;) #Optional if not done in callback</pre><h3>Key Points</h3><ul><li><strong>Resize and normalize images</strong> before training.</li><li><strong>Convolution and pooling layers</strong> extract features and reduce data size.</li><li><strong>Flatten and dense layers</strong> perform final classification.</li><li><strong>Augmentation and regularization</strong> help prevent overfitting.</li><li><strong>Evaluate, tune, and retrain.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5cac62597c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/superdatascience/step-by-step-cnn-ab5cac62597c">Step-by-step CNN</a> was originally published in <a href="https://medium.com/superdatascience">SuperDataScience</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the World of Vibe Coding: A Guide to No-Code Platforms]]></title>
            <link>https://medium.com/@tehreemansari/exploring-the-world-of-vibe-coding-a-guide-to-no-code-platforms-0fd1da64f07e?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fd1da64f07e</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[no-code-development]]></category>
            <category><![CDATA[no-code]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 20:30:19 GMT</pubDate>
            <atom:updated>2025-04-04T20:30:19.293Z</atom:updated>
            <content:encoded><![CDATA[<p>There are things we are indifferent to, and then there are things we simply cannot avoid — whether or not we have strong opinions about them. We may not root for or against them; they’re just <em>there</em>, and we adapt. Modern technology has evolved in this way.</p><p>Similarly, <strong>vibe coding</strong> (or <strong>no-code code</strong>) has emerged as a key technology that we cannot escape from. Vibe coding refers to the practice of generating code without actually writing it. Instead, you use natural language prompts to describe your software idea to a large language model (LLM), such as <strong>ChatGPT</strong> or <strong>GitHub Copilot</strong>, which then generates the code for you. It’s an intuitive way of creating software without needing to be a seasoned programmer.</p><p>Let’s explore various platforms in this article that allow you to experience vibe coding firsthand, along with examples of what each tool can do.</p><h3>What is Vibe Coding?</h3><p>It’s coding without actively writing code in the traditional sense. Instead, we use natural language prompts to describe a software idea or problem to a large language model (LLM), which then generates the corresponding code.</p><p>For instance, the prompt that I entered for all the platforms below was:</p><pre>Create a web-based children&#39;s bedtime story generator with an animal focus. <br><br>The app will feature:<br>1. A user-friendly form for inputting story details <br>(child&#39;s name, favorite animal, theme/message)<br>2. Localized story generation based on user input<br>3. Stories that are at least 1,000 words long<br>4. A whimsical, dreamy interface with soft, muted colors and playful animal illustrations<br>5. Include fantasy elements like fairies, dragons, unicorns, etc.&quot;</pre><p>Below, I’ve tested this prompt across several platforms to see how they handle vibe coding and the types of results they produce.</p><h3>1. Replit: Code, Test, and Host in One Place</h3><p><a href="https://replit.com/">Replit</a> is an online platform that allows you to write, run, and host code directly in your browser. It’s perfect for beginners and anyone who wants to quickly test out ideas without needing to install anything on their computer.</p><p>I used Replit to generate a “kids’ bedtime story app” using the prompt mentioned above. You can see the unmodified result here:<br> 🔗 <a href="https://replit.com/@tehreea/WhiskerTales">WhiskerTales on Replit</a></p><p><strong>Pros</strong>:</p><ul><li>Fast, in-browser setup</li><li>Easy to modify and test ideas</li><li>Great for beginners and small projects</li><li>The free version is good for upto 25 prompts</li><li>Can even integrate with LLMs, but will need manual modifications</li></ul><p><strong>Cons</strong>:</p><ul><li>Limited customization options without manual edits</li></ul><p><strong>Updating the result:</strong><br> Replit successfully generated a working prototype. Impressively, when asked to modify the app to use <strong>Flutter</strong> for the UI, it adapted! Note: this works best if the tech stack is compatible and there’s a clear request for the change.</p><h3>2. Hostinger Horizons: A Platform for Fast Prototyping</h3><p><strong>Hostinger Horizons</strong> is an easy-to-use platform for building and hosting apps with minimal setup. It allows you to input natural language prompts to generate projects, making it great for rapid prototyping.</p><p>Here’s how it performed with the same prompt:<br> 🔗 <a href="https://fc93aec7-d1e4-4c0d-b6a5-a51da1e9ad2a.dev2.app-preview.com/">Hostinger Horizons Demo</a></p><p><strong>Pros</strong>:</p><ul><li>Seamless app generation and hosting</li><li>Quick UI outputs</li><li>Great for prototyping without requiring technical knowledge</li></ul><p><strong>Cons</strong>:</p><ul><li>The code generation is not of “top” quality (this is with comparsion with replit)</li><li>It gives only 5 free prompts</li></ul><h3>3. Bubble: Visual Web App Builder</h3><p><a href="https://teh93cat.bubbleapps.io/version-test?debug_mode=true">🔗 Bubble Demo</a></p><p><strong>Bubble</strong> is a visual, drag-and-drop platform similar to Canva but for web apps. It’s ideal for non-coders focused mainly on UI.</p><h4>Pros:</h4><ul><li>Easy-to-use visual builder</li><li>No coding skills required</li></ul><h4>Cons:</h4><ul><li>The generated UI had limited interactivity</li><li>Input form worked, but story generation did not trigger</li><li>The dropdown menu repeated the topic “imagination” five times</li></ul><p><strong>Use Case Example:</strong><br> Great for someone creating an educational platform or a simple app interface, but you’ll need to connect backend workflows or APIs manually.</p><h3>4. Figma</h3><p><strong>Figma</strong> is a design tool, similar to Canva, used for creating website or app layouts via drag-and-drop. However, it does not support natural language prompts or direct code generation.</p><h4>Pros:</h4><ul><li>Fantastic for UI/UX mockups</li></ul><h3>Cons:</h3><ul><li>No prompt-to-code functionality</li><li>Not suitable for vibe coding</li></ul><p><strong>Use Case:</strong><br> Figma is best for designing interfaces that you later hand off to developers or use with code-generation plugins like Anima or Locofy.</p><h3>5. PromptAppGPT</h3><p>I came across <strong>PromptAppGPT</strong> during a Google search, but the experience wasn’t as smooth as expected. The platform provided some initial information about its capabilities, but when I entered the prompt, it failed to generate any code or template.</p><p>Website: <a href="https://promptappgpt.wangzhishi.net/app.htm">PromptAppGPT</a></p><p><strong>Cons</strong>:</p><ul><li>Did not produce functional code</li><li>Likely still under development or inactive</li></ul><h3>6. OpenAI Codex</h3><p><strong>OpenAI Codex</strong>, which once powered GitHub Copilot, has been discontinued in favor of more powerful models like <strong>ChatGPT</strong>. Codex was one of the first widely accessible LLMs capable of generating code from prompts, but it’s no longer available as a separate product. However, you can still achieve similar results using <strong>ChatGPT</strong> or <strong>GPT-4</strong> for code generation tasks.</p><p><strong>Current Alternative</strong>: Use <strong>ChatGPT</strong> (GPT-4) via API or integrated tools like <strong>GitHub Copilot</strong>.</p><h3>7. AugmentCode: Code Extension for IDEs</h3><p><a href="https://augmentcode.com/">AugmentCode</a> is a useful IDE extension for code explanations and debugging. I tested it with the same prompt, and it generated the code for the app, but the process wasn’t as seamless as some of the other platforms.</p><p><strong>Pros</strong>:</p><ul><li>Great for explaining code and identifying bugs/optimizations</li><li>Useful for collaborative debugging and coding</li><li>I’d use it actively when working on professional large scale code</li></ul><p><strong>Cons</strong>:</p><ul><li>Not as intuitive for generating full projects</li><li>Requires manual integration into your existing project</li><li>Similar to <strong>GitHub Copilot</strong>, but slightly less beginner-friendly (while copilot has other integrations with Microsoft365, pages, etc)</li></ul><p><strong>Note</strong>: When I installed the plugin, I got the conflict with Copilot, and also that both shouldn’t be used together (which makes sense as both with “think” different).</p><h3>8. Graphite.dev: Code Review, Not Code Generation</h3><p><a href="https://app.graphite.dev/">Graphite.dev</a> is a tool primarily designed for code review and collaboration, rather than generating code from prompts. It’s best for teams working on professional projects and needing feedback on their code.</p><p><strong>Pros</strong>:</p><ul><li>Excellent for reviewing pull requests</li><li>Helps maintain code quality in collaborative environments</li></ul><p><strong>Cons</strong>:</p><ul><li>Not a code generation tool, so it’s not suited for quick prototyping</li></ul><h3>My favorites</h3><p>Replit for entire project creation from scatch. Graphite.dev for code review, I’d prefer Copilot over AugmentCode.</p><p>These are just a small set of platforms, if there are other great ones, please drop a comment and I’d love to explore them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fd1da64f07e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How High School Math Sneaks Into AI]]></title>
            <link>https://medium.com/@tehreemansari/how-high-school-math-sneaks-into-ai-b2544b40671d?source=rss-fa5b1249bbc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2544b40671d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics-education]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Tehreem Ansari]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 17:20:44 GMT</pubDate>
            <atom:updated>2025-03-21T17:20:44.153Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in high school, my friends and I would always complain, <em>“Why do we need to learn Calculus, Linear Algebra, or Statistics? When are we ever going to use this?”</em> We were <em>so</em> sure we’d never need any of it in real life.</p><p>Yeah… we were wrong.</p><p>Turns out, I’ve had to learn, unlearn, and relearn this stuff <em>so many times</em> that I’ve lost count. Looking back, I wish my 12-year-old self had a clue about how much this math actually shapes the world. So, I figured, why not take a trip down memory lane and pick out some of the most important high school math topics that show up in AI — without getting too lost in the weeds?</p><h3>1. Reducing Errors: Because, we love perfection</h3><p>Prediction is all about <strong>reducing errors</strong> — plain and simple. In fancy terms, this is called <em>loss</em> (for a single data point) or <em>cost</em> (for the whole dataset). But how do we even measure errors? That’s where distance metrics like <strong>Euclidean distance, Hamming distance</strong>, and even <strong>Cosine similarity</strong> (yep, trigonometry sneaks in here) come in.</p><p>Once we figure out the error, we need to <strong>minimize</strong> it. And guess what? That’s just <strong>calculus</strong> in disguise. We use <strong>derivatives</strong> to tweak the model step by step — this is called <strong>Gradient Descent</strong>. And if we flip that idea around and start summing things up instead of taking derivatives? Boom — <strong>integration</strong>. That’s how we measure stuff like <em>AUC (Area Under the Curve)</em> to see how well a model is performing.</p><h3>2. Functions: The Secret Sauce of AI Predictions</h3><p>Wanna keep it simple? Use a <strong>linear function</strong>. Need more flexibility? Try <strong>polynomial, logarithmic, or exponential functions</strong>. And if none of those work, well… time to get creative and come up with your own!</p><p>AI doesn’t just work in two dimensions — some functions live in crazy high-dimensional spaces. Who knows? Your perfect function might be chilling somewhere in an alternate mathematical universe, just waiting to be discovered.</p><h3>3. Statistics: AI’s Fancy Rebrand</h3><p>Let’s be real — Data Science is basically <strong>Statistics</strong> in a cooler outfit. When I was 10, I thought statistics was just about counting people in a census. Turns out, it’s <em>everywhere</em> in AI. From <strong>probability models</strong> to <strong>regression analysis</strong> and <strong>hypothesis testing</strong>, statistics is the engine running behind all the fancy AI algorithms.</p><h3>4. Linear Algebra: The Silent watcher</h3><p>I <em>have</em> to mention <strong>Linear Algebra</strong> because, honestly, AI wouldn’t exist without it. It shows up everywhere:</p><ul><li><strong>Matrices</strong>? They power the <em>bag-of-words</em> model in Natural Language Processing.</li><li><strong>Vectorization</strong>? That’s how we store data in <em>vector databases</em>.</li><li><strong>Matrix multiplication</strong>? It’s what makes neural networks work — they use it to calculate weighted sums.</li></ul><p>And if we’re talking about Linear Algebra, we <em>have</em> to mention <strong>Computer Vision</strong> — it’s basically built on it. If you’ve ever used an AI model that recognizes faces, objects, or even enhances images, thank Linear Algebra for that. My jaws just dropped when I even saw eigenvalues and eigenvalues after 15 years! I had forgotten all about them.</p><p>All that high school math we thought was useless? Yeah… it’s running the AI revolution.</p><p><em>(P.S. If I got anything wrong, feel free to correct me — I’m always up for learning something new!)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2544b40671d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>