<?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 Dhananjaikrishnakumar on Medium]]></title>
        <description><![CDATA[Stories by Dhananjaikrishnakumar on Medium]]></description>
        <link>https://medium.com/@dhananjaikrishnakumar?source=rss-5ca723d3eebe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kXZWa6L_az9izbNh</url>
            <title>Stories by Dhananjaikrishnakumar on Medium</title>
            <link>https://medium.com/@dhananjaikrishnakumar?source=rss-5ca723d3eebe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:49:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhananjaikrishnakumar/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[Limitations of Word2vec]]></title>
            <link>https://medium.com/@dhananjaikrishnakumar/limitations-of-word2vec-33db20ac63cc?source=rss-5ca723d3eebe------2</link>
            <guid isPermaLink="false">https://medium.com/p/33db20ac63cc</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[word2vec]]></category>
            <dc:creator><![CDATA[Dhananjaikrishnakumar]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 06:43:36 GMT</pubDate>
            <atom:updated>2025-04-23T06:43:36.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Great question! While <strong>Word2Vec</strong> was a major breakthrough in NLP, it <strong>has several limitations</strong>. Let’s walk through the key problems with intuitive explanations and examples.</p><p><strong>🔴 1. Context-Independent Embeddings</strong></p><p><strong>Problem:</strong></p><p>Each word gets <strong>only one vector</strong>, regardless of context.</p><p><strong>Example:</strong></p><p>• Sentence 1: <em>He went to the </em><strong><em>bank</em></strong><em> to deposit money.</em></p><p>• Sentence 2: <em>She sat on the river </em><strong><em>bank</em></strong><em> and watched the sunset.</em></p><p>👉 Word2Vec gives <strong>“bank”</strong> the <em>same vector</em> in both cases — but clearly the meanings are very different (financial institution vs. riverbank).</p><p><strong>🔴 2. No Understanding of Word Order or Syntax</strong></p><p><strong>Problem:</strong></p><p>Word2Vec uses a window-based approach, treating all context words equally regardless of position.</p><p><strong>Example:</strong></p><p>• <em>Dog bites man</em> vs. <em>Man bites dog</em></p><p>→ Word2Vec can’t distinguish between them — it just sees “dog”, “bites”, “man” in close proximity.</p><p>👉 This causes issues in capturing <strong>meaning from sentence structure</strong>.</p><p><strong>🔴 3. OOV (Out of Vocabulary) Words</strong></p><p><strong>Problem:</strong></p><p>If a word wasn’t in the training corpus, Word2Vec can’t provide an embedding.</p><p><strong>Example:</strong></p><p>• If your model was trained before the term <strong>“COVID”</strong> existed, it won’t recognize or embed it at all.</p><p><strong>🔴 4. Static Vectors Can’t Handle Polysemy</strong></p><p><strong>Problem:</strong></p><p>Words with multiple meanings get a <strong>single averaged embedding</strong>, which may be misleading.</p><p><strong>Example:</strong></p><p>• <em>“Rock”</em> can mean a <strong>stone</strong> or a <strong>music genre</strong>. Word2Vec tries to find a middle ground between both senses, leading to poor representations in both contexts.</p><p><strong>🔴 5. Doesn’t Handle Rare Words Well</strong></p><p><strong>Problem:</strong></p><p>Rare words (low frequency) might get poorly trained vectors.</p><p><strong>Why?</strong></p><p>They appear in fewer contexts → less data to learn meaningful embeddings.</p><p><strong>🔴 6. Window Size Trade-Off</strong></p><p><strong>Problem:</strong></p><p>Small window → captures <strong>syntactic</strong> info but loses <strong>semantic</strong> relationships.</p><p>Large window → captures <strong>semantic</strong> info but blurs syntax.</p><p>Choosing a window size is a trade-off and depends on the task.</p><p><strong>🔴 7. No Built-in Mechanism for Subword Information</strong></p><p><strong>Problem:</strong></p><p>It treats each word as a separate token, missing <strong>morphological</strong> clues.</p><p><strong>Example:</strong></p><p>• “run”, “running”, “runner” → all treated separately, no shared info despite common root.</p><p><strong>🔄 Summary Table</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PrMeEgWGxEOsjo44rAxKg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33db20ac63cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jargons of NLP]]></title>
            <link>https://medium.com/@dhananjaikrishnakumar/jargons-of-nlp-9d88270c879d?source=rss-5ca723d3eebe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d88270c879d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[jargon]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <dc:creator><![CDATA[Dhananjaikrishnakumar]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 07:35:57 GMT</pubDate>
            <atom:updated>2025-04-21T07:35:57.001Z</atom:updated>
            <content:encoded><![CDATA[<p>NLP (and especially LLMs) are <strong>full of jargon</strong> — it’s like learning a new dialect of AI 😄</p><p>Here’s a <strong>smart and memorable way</strong> to tackle this:</p><p><strong>💡 Strategy: “3-Level Memory Hook”</strong></p><p>We’ll use <strong>Associations</strong>, <strong>Analogies</strong>, and <strong>Acronyms</strong> to memorize complex terms.</p><p><strong>📦 1. Group Terms by Theme (Contextual Chunking)</strong></p><p>Instead of memorizing random terms, group them:</p><p><strong>🧠 Language Modeling &amp; Tokenization</strong></p><p>• <strong>Token</strong>: smallest unit (like a word or sub-word)</p><p>• <strong>Vocabulary</strong>: list of all possible tokens</p><p>• <strong>Corpus</strong>: large collection of text</p><p>• <strong>N-gram</strong>: sequence of N tokens</p><p>• <strong>Perplexity</strong>: how “surprised” the model is by the actual next word</p><p>🧠 <strong>Analogy</strong>:</p><p><em>Corpus = the novel</em>, <em>Tokens = words in it</em>, <em>Vocabulary = dictionary</em>, <em>N-gram = phrase</em>, <em>Perplexity = reader’s confusion</em></p><p><strong>🧠 Word Embeddings</strong></p><p>• <strong>Word2Vec</strong>: Predict neighbors (CBOW &amp; Skip-gram)</p><p>• <strong>GloVe</strong>: Counts + matrix factorization</p><p>• <strong>fastText</strong>: Sub-word embeddings</p><p>• <strong>Cosine similarity</strong>: How close words are in meaning</p><p>💡 Mnemonic:</p><p><strong>WGF</strong> → <em>“Words Get Friendly”</em> (Word2Vec, GloVe, fastText) — all build vector friendships.</p><p><strong>🧠 Model Architectures</strong></p><p>• <strong>RNN, LSTM, GRU</strong>: Handle sequences</p><p>• <strong>Transformer</strong>: No recurrence, just attention</p><p>• <strong>Self-Attention</strong>: Each word attends to others in same sentence</p><p>• <strong>Multi-Head Attention</strong>: Look from multiple “perspectives”</p><p>💡 Analogy:</p><p><em>LSTM = note taker with memory</em>,</p><p><em>Transformer = group chat with everyone reading each other’s messages</em></p><p><strong>🧠 Decoding &amp; Generation</strong></p><p>• <strong>Greedy decoding</strong>: pick most probable next word</p><p>• <strong>Beam search</strong>: keep top-k sequences</p><p>• <strong>Top-k sampling</strong>: choose from top k likely tokens</p><p>• <strong>Top-p (nucleus) sampling</strong>: pick from top <em>probability mass</em></p><p>🧠 Acronym Trick: <strong>GBK-P</strong></p><p>Greedy — Beam — Top-<em>k</em> — Top-<em>p</em></p><p>Think of <strong>“Getting Better K-Pop”</strong> as you explore decoding 😄</p><p><strong>🧠 Fine-tuning &amp; Training</strong></p><p>• <strong>ELMo</strong>: Deep contextual embeddings (uses LSTM)</p><p>• <strong>BERT</strong>: Bi-directional encoding</p><p>• <strong>GPT</strong>: Decoder-only, autoregressive</p><p>• <strong>LoRA</strong>: Low-Rank Adapters</p><p>• <strong>Distillation</strong>: Small student learns from big teacher</p><p>💡 Analogy:</p><p><em>ELMo = smart guy who learns context deeply</em>,</p><p><em>BERT = reads both sides</em>,</p><p><em>GPT = writes stories word-by-word</em></p><p><strong>🧠 Ethics &amp; Alignment</strong></p><p>• <strong>Bias</strong>: systemic prejudice in outputs</p><p>• <strong>Toxicity</strong>: harmful/offensive content</p><p>• <strong>RLHF</strong>: Reinforcement Learning from Human Feedback</p><p>💡 Mnemonic: <strong>“Be Real”</strong></p><p>Bias, Ethics, RLHF → Be Real about AI safety</p><p><strong>🧠 2. Use Flashcards (Anki / Google Docs / Sticky Notes)</strong></p><p>Front:</p><p>What is the difference between BERT and GPT?</p><p>Back:</p><p>BERT = encoder, bidirectional, masked LM</p><p>GPT = decoder, left-to-right, autoregressive LM</p><p>Do 10–15 flashcards a day — <strong>spaced repetition is gold</strong>.</p><p><strong>🔁 3. Use &amp; Explain the Terms Often</strong></p><p>• Speak to yourself using them.</p><p>• Teach a friend.</p><p>• Explain via diagrams (great for Transformers or token flow).</p><p>• Create funny stories using them (eg: <em>“GPT is an eager writer who guesses every next word while BERT is a deep thinker who fills in the blanks.”</em>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d88270c879d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Bigram Model with Malayalam- First step towards malayalam GPT]]></title>
            <link>https://medium.com/@dhananjaikrishnakumar/a-bigram-model-with-malayalam-first-step-towards-malayalam-gpt-9d9adaca32e9?source=rss-5ca723d3eebe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9adaca32e9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[malayalam]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[andrej-karpathy]]></category>
            <dc:creator><![CDATA[Dhananjaikrishnakumar]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 12:10:04 GMT</pubDate>
            <atom:updated>2025-01-05T15:16:20.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the next article on building a Malayalam GPT! After publishing the first article, my friend Gishnu joined the effort. Together, we discussed the idea of building a few projects using agents while also completing Andrej Karpathy’s lecture series. Both of us recently finished the second lecture. Inspired by Karpathy’s <em>makemore</em> lecture, which continues from <em>micrograd</em>, we decided to dive deeper.</p><p>Initially, I had planned to directly build a GPT-2 model for Malayalam. However, after discussions with Gishnu, we realized the importance of starting with simpler models for better practice and understanding. This way, we can avoid unnecessary complexity later.</p><p>In Karpathy’s lecture, he builds a model that generates new names using a single-layer neural network. This is a bigram model, meaning it predicts the next letter based only on the current letter. To get started, we used a Malayalam dataset from Hugging Face for our experiments.</p><p><a href="https://huggingface.co/datasets/santhosh/english-malayalam-names">santhosh/english-malayalam-names · Datasets at Hugging Face</a></p><p>The dataset required some cleaning to remove English characters. We used only a portion of the dataset, ensuring that all words containing non-Malayalam characters were excluded.</p><p>In the lecture, Karpathy creates two models: one using a counting method and the other using a single-layer perceptron. While the counting model is simple and effective, it has significant scalability issues. As we increase the number of preceding characters used for prediction, the number of combinations grows exponentially, leading to a combinatorial explosion. For larger values of <em>n</em>, the number of possible outcomes becomes unmanageable.</p><p>Malayalam characters fall within the Unicode range <strong>U+0D00 to U+0D7F</strong>, making it easier to filter the dataset. However, we encountered an additional challenge when visualizing the counts for each character in Malayalam. Unlike English, Matplotlib does not natively display Malayalam characters, which added complexity to our analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypV7AtTWtB0999Q_HyE5DQ.png" /><figcaption>Count of English characters in the dataset</figcaption></figure><p>We first created two dictionaries itos and stoi to refer to the characters with indices and vice versa. We created two torch tensors as inputs and outputs using the cleaned names dataset. The input contains the characters one after the other. For each input character the next character is the output.</p><pre># create the dataset<br>xs, ys = [], []<br>for w in words:<br>  chs = [&#39;.&#39;] + list(w) + [&#39;.&#39;]<br>  for ch1, ch2 in zip(chs, chs[1:]):<br>    ix1 = stoi[ch1]<br>    ix2 = stoi[ch2]<br>    xs.append(ix1)<br>    ys.append(ix2)<br>xs = torch.tensor(xs)<br>ys = torch.tensor(ys)<br>num = xs.nelement()<br>print(&#39;number of examples: &#39;, num)</pre><p>Then we initialised the network with random weights</p><pre># initialize the &#39;network&#39;<br>g = torch.Generator().manual_seed(2147483647)<br>W = torch.randn((len(itos), len(itos)), generator=g, requires_grad=True)</pre><p>For input to the network we have one hot encoded the characters. With the current weight we predict the next character and calcuate the loss. It starts by converting input indices into one-hot vectors, which represent each character uniquely in a vector space. The weight matrix learns to map these vectors to logits (unscaled counts for the next character). These logits are exponentiated to get raw counts, normalized into probabilities, and used to compute the negative log-likelihood loss. A regularization term penalizes large weights to avoid overfitting. During training, the gradients of the loss with respect to weights are computed using backpropagation, and the weights are updated using gradient descent to minimize the loss iteratively.</p><pre>import torch.nn.functional as F<br># gradient descent<br>for k in range(200):<br>  <br>  # forward pass<br>  xenc = F.one_hot(xs, num_classes=len(itos)).float() # input to the network: one-hot encoding<br>  logits = xenc @ W # predict log-counts<br>  counts = logits.exp() # counts, equivalent to N<br>  probs = counts / counts.sum(1, keepdims=True) # probabilities for next character<br>  loss = -probs[torch.arange(num), ys].log().mean() + 0.01*(W**2).mean()<br>  print(loss.item())<br>  <br>  # backward pass<br>  W.grad = None # set to zero the gradient<br>  loss.backward()<br>  <br>  # update<br>  W.data += -50 * W.grad</pre><p>We predicted the some names with the current training. This what it looks like.</p><pre>സ്.<br>ഷ്കുമജ്വ്മഖ്ലദ.<br>രി.<br>സുസാർ.<br>ബഒപ്മായായ.<br>മാവിയില്.<br>ഏദീവാ.<br>സനി.<br>റ്ത്.<br>ഷി.<br>ജോഷ്.<br>അളിന.<br>പൺസ്റശപ്ദ്.<br>വ.<br>ഷ.<br>നീസ്.<br>ജി.<br>ധികബിൻ.<br>ജർ.<br>അനെൻകു.</pre><p>While the output might resemble names of aliens, this is still a small but significant step toward building a more intelligent model. It demonstrates that the bigram model is learning some basic patterns of the Malayalam script.</p><p>Our next steps will include creating a <strong>trigram model</strong> to capture more contextual information and experimenting with a <strong>multilayer perceptron</strong> for training. We’re excited to see how these enhancements improve the quality of the generated names! Stay tuned for updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9adaca32e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Micrograd — Can we build a neural network from scratch? Thanks to Andrej Karapathy]]></title>
            <link>https://medium.com/@dhananjaikrishnakumar/building-micrograd-can-we-build-a-neural-network-from-scratch-thanks-to-andrej-karapathy-a71507a3fe2f?source=rss-5ca723d3eebe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a71507a3fe2f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Dhananjaikrishnakumar]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 09:58:46 GMT</pubDate>
            <atom:updated>2024-12-26T09:58:46.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Micrograd — Can we build a neural network from scratch? Thanks to Andrej Karapathy</h3><p>Recently with ChatGPT we are in a new AI era. I have been looking at people who have been building AI systems and was fascinated by how they would build chatGPT. I came across Andrej Karapathy’s Github profile and started to explore it. He had this neural networks “Hero to Zero” course.</p><p>Just completed watching his first video. In this video he explains how to create a datastructure that can be used to build a neural network. He has this repo called micrograd with just a couple of files which can be used to create neural networks.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVMj-3S1tku0&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVMj-3S1tku0&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FVMj-3S1tku0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bab26b18e53289f68a64c7a42445cb93/href">https://medium.com/media/bab26b18e53289f68a64c7a42445cb93/href</a></iframe><p>A neural network is a network of connected neurons. Each of the neurons get activated if the value passes a certain threshold in the forward pass. We have inputs and target values. We have to teach the neural network to create outputs that are close to the target. Loss functions are used to understand with current weights of the neural network what is the distance between inputs and target.</p><p>After calculating loss we can adjust the weights to reduce the loss. To get the idea of how to adjust the weights we use a concept called back propagation. The loss function is a function of the output layers which is a function of the previous layer. If we know the gradient we can adjust the weights to reduce the loss. To understand backpropagation I would suggest you to watch the video of 3 Blue 1 Brown on back propagation. Actually it would be great if you can watch his entire series on neural nets</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaircAruvnKk%3Flist%3DPLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaircAruvnKk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaircAruvnKk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6c0c64f525af4e58ff01f891bd03ee9/href">https://medium.com/media/f6c0c64f525af4e58ff01f891bd03ee9/href</a></iframe><p>Let me focus on explaining how interesting the data structure of a neural network is. We have four classes in Micrograd that are used to build the neural network. There is a Value class, Neuron class, and Layer class , MLP( Multi Layer Perceptron) class.</p><p><a href="https://github.com/karpathy/micrograd">GitHub - karpathy/micrograd: A tiny scalar-valued autograd engine and a neural net library on top of it with PyTorch-like API</a></p><p>Value class</p><p>It tries to have all the necessary attributes you need to build mathematical expressions needed for a neural network. Each neuron is connected to an input or neurons from previous layer. The connections have weights and neurons have activation functions. The neurons must be sorted topologically to define forward and backward pass. We must store the connections to the neurons from previous layer. All these and much more functionalities are covered by value class.</p><p>Neuron class</p><p>It combines the weights and biases with the activation held by the Value class to create a neuron.</p><p>Layers</p><p>Many Neurons are connected to form a Layer. It has necessary attributes that can be used to create a layer with a given number of inputs and outputs</p><p>MLP</p><p>The inputs and Layers are getting combined here. It also creates a structure to allow pass of information between neurons sequentially during forward and backward pass</p><p>This article just gives a gist of components of the video and micrograd. But creating neural networks from scratch feels awesome. The understanding of how they work make build more fun.</p><p>It took two days for me to watch the video and create it. The main road block that i encountered was installing graphviz. It took away 4–5 hours of my time. But the beauty of the understanding till that point kept me going. Anyone who gets an issue in installing graphviz in Mac can contact me. Unlike just pip install a library, we need to create an executble for graphviz and give the path to our virtual environment.</p><p>“ You don’t really understand it untill you have the capacity to create it “</p><p>Now I will try to finish the exercises given in the video and move to the next video. In month my aim is to finish the course and in the last video Karapathy is Building GPT-2 from scratch. Instead of english to teach GPT in english, I am planning to create a malyalam GPT. Let’s see how that goes. Thanks for reading through, see you later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a71507a3fe2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the need of abstract class?]]></title>
            <link>https://medium.com/@dhananjaikrishnakumar/what-is-the-need-of-abstract-class-3256ce5cdffc?source=rss-5ca723d3eebe------2</link>
            <guid isPermaLink="false">https://medium.com/p/3256ce5cdffc</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[abstract-class]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dhananjaikrishnakumar]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 10:44:54 GMT</pubDate>
            <atom:updated>2024-11-05T10:44:54.281Z</atom:updated>
            <content:encoded><![CDATA[<p>Abstract classes provide a structured blueprint for its subclasses. This is specifically helpful if we want the subclasses to have certain methods to be implemented for sure.</p><p>Here is an example to illustrate the need:</p><p><strong>Without an Abstract Class</strong></p><pre>class PaymentProcessor:<br>    def process_payment(self):<br>        raise NotImplementedError(&quot;Subclasses should implement this!&quot;)<br><br>class CreditCardPayment(PaymentProcessor):<br>    def process_payment(self):<br>        print(&quot;Processing credit card payment.&quot;)<br><br>class PayPalPayment(PaymentProcessor):<br>    # Intentionally omitting process_payment() for illustration<br><br># Attempting to use PayPalPayment<br>payments = [CreditCardPayment(), PayPalPayment()]<br>for payment in payments:<br>    payment.process_payment()  # This will cause a runtime error for PayPalPayment</pre><p><strong>With an Abstract Class</strong></p><pre>from abc import ABC, abstractmethod<br><br>class PaymentProcessor(ABC):<br>    @abstractmethod<br>    def process_payment(self):<br>        pass<br><br>class CreditCardPayment(PaymentProcessor):<br>    def process_payment(self):<br>        print(&quot;Processing credit card payment.&quot;)<br><br>class PayPalPayment(PaymentProcessor):<br>    pass  # Now, this will raise an error immediately<br><br># Attempting to use PayPalPayment will raise an error before runtime<br>payments = [CreditCardPayment(), PayPalPayment()]  # TypeError: Can&#39;t instantiate abstract class PayPalPayment</pre><p>In this case:</p><p>• <strong>PayPalPayment</strong> will raise a TypeError immediately upon definition because it hasn’t implemented the required process_payment() method. This error happens at the time of creating the subclass, not during runtime, making it easier to catch.</p><p>• The abstract class enforces consistency and prevents creating a subclass without the required methods, ensuring that all PaymentProcessor subclasses will behave as expected.</p><p><strong>When Abstract Classes Shine</strong></p><p>Abstract classes are particularly helpful in:</p><p>• <strong>Large Codebases</strong>: Enforces a consistent structure and design.</p><p>• <strong>Team Projects</strong>: Helps ensure that everyone adheres to the required class structure.</p><p>• <strong>Frameworks/Libraries</strong>: Provides a strong contract for developers extending the functionality.</p><p>• <strong>Hierarchical Inheritance</strong>: Where some classes serve as only partially implemented templates for specialized subclasses.</p><p>In short, abstract classes are about <strong>clarity, consistency, and safety</strong> in your design, ensuring all subclasses adhere to a common interface.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3256ce5cdffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>