<?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 Goktugdagi on Medium]]></title>
        <description><![CDATA[Stories by Goktugdagi on Medium]]></description>
        <link>https://medium.com/@goktugdagi?source=rss-9f7135ed6ee2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KxNdfaAV7RTch4sxj0nG_g.jpeg</url>
            <title>Stories by Goktugdagi on Medium</title>
            <link>https://medium.com/@goktugdagi?source=rss-9f7135ed6ee2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:01:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@goktugdagi/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[LSTM, Transformers, and the Rise of Modern Language Models]]></title>
            <link>https://medium.com/@goktugdagi/lstm-transformers-and-the-rise-of-modern-language-models-2b80a6e88d1c?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b80a6e88d1c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 06:08:07 GMT</pubDate>
            <atom:updated>2025-12-30T06:08:07.031Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous section, we saw how neural networks began to model sequential data, but also why traditional RNNs struggled with long-term dependencies.</p><p>This limitation led to two major breakthroughs in NLP:<br> <strong>LSTM networks</strong>, which improved memory handling, and <strong>Transformers</strong>, which completely redefined how context is learned.</p><p>In this final part, we explore how these architectures gave rise to today’s large language models.</p><h3>LONG SHORT-TERM MEMORY (LSTM)</h3><ul><li>LSTM is a type of RNN.</li><li>It is specifically designed to learn long-term dependencies.</li></ul><p>The Main Purpose of LSTM</p><ul><li>To learn long-term dependencies in time-dependent data</li><li>It was developed to solve the “Vanishing Gradient” problem experienced by traditional RNNs.</li></ul><h4>What is the Improvement of LSTM over RNNs?</h4><p>Problems Experienced in RNNs</p><ul><li>Vanishing Gradient Problem -&gt; In long sequences, gradients gradually decrease and become unlearnable. This is called the “Vanishing Gradient Problem”.</li><li>Inability to Learn Long-Term Dependencies -&gt; Classical RNNs are insufficient in carrying past information forward in long sequences.</li></ul><p>The Solution of LSTM</p><ul><li>Cell State -&gt; Unlike RNNs, Cell State has been added. Cell State is a mechanism that carries information at each step in LSTM. This carries long-term information to future cells.</li><li>Gates -&gt; There are 3 main gates in LSTM. These are: Input, Forget, and Output gates. Through these gates, it is decided which information will be stored, which information will be updated, and which information will be reflected in the output.</li></ul><h4>What is LSTM Architecture, Components, and Operation?</h4><p>LSTM Components</p><ul><li>Cell State -&gt; Acts as long-term memory where information is transferred. It carries information from the past to the future at each step over time.</li><li>Input Gate -&gt; Decides on the addition of new information to the cell state. It determines how much of the input information will be transferred to the cell.</li><li>Forget Gate -&gt; Determines which information from the past will be forgotten or preserved. It is used to delete unnecessary information from the cell state.</li><li>Output Gate -&gt; Determines what will be output based on the current cell state.</li></ul><p>LSTM Applications</p><ul><li>Natural Language Processing (NLP)</li><li>Speech Recognition</li><li>Time Series Forecasting</li><li>Music and Text Generation</li><li>Video Processing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*IPo6pwrqP4duRD_sWhHOdg.png" /></figure><h3>Transformers</h3><ul><li>A revolutionary Deep Learning Model in the field of NLP.</li><li>It gained recognition with the “Attention is All You Need” article published by Google in 2017.</li><li>Using its “attention mechanisms,” it learns the relationship between each element in the input and other elements. This feature provides a significant advantage in understanding the context of long texts.</li><li>It understands context better. It is highly successful in capturing long-distance relationships between words in a sentence.</li><li>While traditional RNN and LSTM models struggle to understand such relationships, “Transformers” is a much more effective method.</li><li>It has parallel processing capabilities. This allows for faster training and inference processes in sequence data.</li><li>It is used in various NLP tasks. It is used in a wide variety of NLP tasks such as language modeling, text classification, language generation, and translation summarization.</li><li>It allows for the reuse of pre-trained models. These models are usually pre-trained on large datasets and fine-tuned for different tasks. This ensures high performance.</li></ul><h3>Transformer Models</h3><h4>BERT</h4><ul><li>BERT is a language model used for language comprehension and text processing tasks.</li><li>BERT attempts to understand context by reading text both from left to right and right to left (it tries to understand context by looking both past and future).</li><li>It is used to understand text. For example, question answering and text classification.</li></ul><p>BERT Architecture</p><ul><li>Transformer Encoder<br>1) BERT uses only the “Encoder” part of the transformer architecture.<br>2) Transformer is a model based on the attention mechanism.</li><li>Two-Stage Training<br>1) Pre-training is done with Masked Language Modeling (MLM) and Next Sentence Prediction (NSP).<br>2) In MLM, the model is expected to predict randomly masked words.<br>3) In NSP, the goal is for the model to understand whether the sentence following a sentence is logically appropriate.</li><li>Fine-Tuning<br>1) Pre-trained models are fine-tuned for various NLP tasks.</li></ul><p>BERT Features</p><ul><li>Bidirectional. That is, it learns the context of each word in a sentence from both the preceding and following words.</li><li>It performs Transfer Learning.</li><li>It uses Transformer Encoder. It only uses the “Encoder” part of the transformer mechanism. BERT is more successful in comprehension and classification tasks.</li></ul><h4>GPT</h4><ul><li>GPT is a language model used for text generation and language modeling.</li><li>GPT reads text only from left to right and looks at the preceding words to predict a word.</li><li>It is used in tasks such as text generation, story writing, and creative content creation.</li></ul><p>GPT Architecture</p><ul><li>It uses the Transformer Decoder part. This structure processes language in the forward direction, i.e., to the left. That is, when predicting a word, it only considers the words preceding that word.</li><li>It has an Autoregressive Approach. When predicting a word, it considers the words it has previously generated. This allows for the generation of logical texts in natural language.</li><li>It has single-stage training. It is trained for language modeling on large datasets.</li><li>It is a unidirectional model.</li><li>It has a Masked Multi-Head Attention mechanism. This allows each token of the model to be processed only based on previous tokens. In other words, it only performs operations with previous tokens.</li><li>It is used to establish contextual relationships. It is used for linear text generation.</li></ul><p>GPT Features</p><ul><li>Unidirectional</li><li>Text Generation</li><li>Transfer Learning</li><li>Very Large Models</li></ul><h4>BERT vs GPT</h4><ul><li>BERT reads text bi-directionally, from left to right and right to left. GPT reads only from left to right.</li><li>BERT is generally used to understand text. GPT is used to generate text.</li><li>BERT is encoder-based. That is, it learns text representation. It is based on GPT Decoder. That is, it is specialized for generating text.</li></ul><h4>LLaMA</h4><ul><li>LLaMA is a family of large language models developed by Meta.</li><li>LLaMA is trained on large datasets and aims to provide similar performance with fewer parameters compared to models like GPT-3 and GPT-4.</li><li>The goal of LLaMA is to make training large language models more accessible to academic researchers and to provide more efficient models.</li></ul><p>LLaMA Architecture</p><ul><li>Transformer-Based</li><li>Lightweight and efficient</li><li>Smaller and faster</li><li>It has a Self-Attention (Multi-Head Self-Attention) layer.</li><li>This layer is responsible for calculating the relationship of each token (word) or sub-word or symbol in the input sequence with all other tokens or words.</li><li>This process allows each token to better learn its context with others.</li><li>It is particularly helpful in language modeling tasks, where children learn the relationship of each word in a sentence to both the words that precede and follow it.</li><li>The goal is to extract contextual information.</li><li>It learns the context of each token in the input sequence based on its relationships with other tokens. This allows the model to better understand each word in relation to the words around it.</li></ul><p>LLaMA Features</p><ul><li>Efficient training</li><li>Researcher-oriented</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*Va2ENUP41JLph6xGpl3yWQ.png" /></figure><p>The evolution from statistical models to neural networks, and ultimately to Transformer-based architectures, represents a fundamental shift in how machines understand language.</p><p>Models such as <strong>LSTM</strong>, <strong>BERT</strong>, <strong>GPT</strong>, and <strong>LLaMA</strong> demonstrate that language understanding is no longer driven by handcrafted features or local patterns, but by <strong>context-aware representations learned at scale</strong>.</p><p>This progression explains why modern language models are capable of reasoning, generation, and transfer learning across a wide range of tasks.</p><p>Understanding this historical evolution is essential — not only to appreciate current Large Language Models, but also to critically evaluate their strengths, limitations, and future directions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b80a6e88d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Word Embeddings to Recurrent Neural Networks]]></title>
            <link>https://medium.com/@goktugdagi/from-word-embeddings-to-recurrent-neural-networks-41fd4de9e3d9?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/41fd4de9e3d9</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 06:28:52 GMT</pubDate>
            <atom:updated>2025-12-26T06:28:52.153Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous part, we examined how classical and probabilistic models represented language using statistical patterns and local dependencies.</p><p>While these approaches were effective for frequency-based analysis, they struggled to capture semantic meaning and contextual relationships between words.</p><p>To address this limitation, NLP shifted toward <strong>vector-based representations and neural models</strong>, enabling machines to learn meaning, similarity, and sequence information directly from data.</p><p>In this section, we explore how word embeddings and recurrent neural networks marked the transition from statistical NLP to deep learning–based language modeling.</p><h3>Deep Learning-Based Language Models</h3><h4>Word Embeddings (Vector Representations of Words)</h4><ul><li>Word Embeddings is a method that represents words with numerical vectors.</li><li>These representations allow for learning semantic relationships between words.</li><li>Words used with the same or similar meanings are close to each other in the vector space.</li></ul><p>Why Should We Represent Words with Vectors?</p><ul><li><strong><em>Capturing Linguistic Meaning -&gt;</em></strong> This concept is used to capture semantic relationships between words. The aim is to capture context, to capture the meaning between words.</li><li><strong><em>Mathematical Operations -&gt;</em></strong> That is, making inferences between words.</li><li><strong><em>Efficient Representation -&gt; </em></strong>Meaningful and compressed representation speeds up operations in large datasets.</li></ul><h4>Word2Vec</h4><p><strong><em>Features and Advantages</em></strong></p><ul><li>Learns semantic affinities based on word neighborhoods.</li><li>It allows you to perform meaningful mathematical operations between words.</li><li>Dataset Used -&gt; Google News Corpus<br>Source -&gt; News Texts<br>Size -&gt; Approximately 100 billion words<br>Scope -&gt; Politics, Economics, Sports, Technology, etc. -&gt; Good for capturing context<br>Words and Word Pairs -&gt; Over 3 million different words and word pairs -&gt; Important for capturing context.</li></ul><p><strong><em>What is Word2Vec?</em></strong></p><ul><li><strong><em>Basic Models: CBOW (Continuous Bag of Words) and Skip-Gram.<br>CBOW -&gt;</em></strong> Attempts to predict the target word by looking at other words in the context.</li><li><strong><em>Skip-Gram Model -&gt;</em></strong> Works in reverse to CBOW. Attempts to predict words in the context using the target word. Works well on larger datasets. Performs particularly well for rare words.</li></ul><h4>FastText</h4><p><strong><em>What is FastText?</em></strong></p><p><em>Features and Advantages</em></p><ul><li>It learns words at the character level as well, making it a stronger model for rare words.</li><li>Dataset Used -&gt; Large datasets such as Wikipedia and Common Crawl.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*LEAvCRatY3TcqtIVr0AyPA.png" /><figcaption>,</figcaption></figure><h4>What are Vector Spaces and Semantic Proximity?</h4><ul><li>The vector representations of words are positioned in the vector space according to their meanings.</li><li>Words with similar meanings (e.g., “cat” and “dog”) are close to each other in the vector space, while words with different meanings (e.g., “cat” and “car”) are far apart.</li><li>The distinction between proximity and distance is made using “Cosine Similarity”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIIszVQD7wxyrks_IQyBFg.png" /></figure><ul><li>Since Cosine Similarity is used, it takes values ​​between -1 and 1.</li><li>Values ​​close to one indicate that words are semantically close. Values ​​close to zero mean that the difference in meaning is significant. A negative one means that the words are opposite to each other.</li></ul><h3>RECURRENT NEURAL NETWORKS (RNN)</h3><p>What are Time Series and Sequence Data?</p><ul><li>A time series refers to observations recorded consecutively over time. Many fields, such as finance, climate, and sensor data, are referred to as time series.</li><li>Sequential data (ordered data) refers to data that is naturally ordered. For example, words in a sentence may follow an ordered structure, or DNA structures may be ordered along a specific base.</li></ul><p>What is Sequential Dependence in Language and Time Series Data?</p><ul><li>Sequential Dependence -&gt; In time series and language data, each element (word or data point) is sequentially dependent on previous data.</li><li>Natural Language Example -&gt; The meaning of a word in a sentence may be related to the preceding words. For example, in the sentence “I am drinking coffee,” the meaning of the word “drinking” is influenced by the words “I” and “coffee.”</li><li>Time Series Example -&gt; What the air temperature will be may depend on the temperature of today and previous days.</li></ul><p>Why are Standard Neural Networks Inadequate for Sequence Data?</p><ul><li>Fixed Input/Output -&gt; Standard Neural Networks expect fixed-size input and output. That is, they must specify input and output sizes. However, sequence data can be of dynamic length, for example, sentences of varying lengths.</li><li>Time Dependence -&gt; Standard Neural Networks are inadequate in learning sequence dependencies because each data point is processed independently.</li><li>Loss of Historical Data -&gt; Standard Neural Networks lose information related to previous inputs, but in sequence data, historical data, such as previous words or sentences, is very important. Therefore, Standard Neural Networks are inadequate for sequence data.</li></ul><p>What is an RNN?</p><ul><li>RNNs are neural networks specifically designed to process sequence data.</li><li>They work by storing information from the previous time step at each time step and updating this information in subsequent steps.</li></ul><p>Basic Features of RNNs</p><ul><li>Time-dimensional repetition</li><li>Suitable for sequence data</li></ul><p>What is RNN Architecture and How Does it Work?</p><ul><li>Network Structure -&gt; RNNs have a hidden layer at every time step. This hidden layer is responsible for carrying the information from previous steps.</li><li>Time-Dimensional Repetition Structure -&gt; At each time step, input is received and processed together with the hidden layer, and output is produced. At the same time, this hidden state is saved for subsequent steps.</li></ul><p>What is the Vanishing Gradient Problem?</p><ul><li>The Vanishing Gradient Problem is a problem that arises during training in RNNs.</li><li>During backpropagation, gradients become very small, making it difficult to learn long-term dependencies.</li></ul><p>Why Does it Occur?</p><ul><li>Chain derivatives are taken at each time step.</li><li>In deep networks, these derivatives can shrink over time and approach almost zero.</li><li>In this case, the impact of information from previous time steps is lost.</li></ul><p>Conclusion</p><ul><li>Learns short-term dependencies, but struggles to learn long-term dependencies.</li></ul><p>Applications of RNN in NLP Fields</p><ul><li>Language Modeling</li><li>Machine Translation</li><li>Sentiment Analysis</li><li>Speech Recognition</li><li>Text Generation</li></ul><p>Recurrent Neural Networks represented a major step forward by introducing memory into language modeling.</p><p>However, as sequences became longer, a fundamental training issue emerged: <strong>vanishing gradients</strong>.</p><p>To truly model long-term dependencies, a more robust memory mechanism was needed — leading to the development of <strong>LSTM networks</strong>, which we will examine next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41fd4de9e3d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Bag of Words to Statistical Language Models]]></title>
            <link>https://medium.com/@goktugdagi/from-bag-of-words-to-statistical-language-models-63eb0a3e900b?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/63eb0a3e900b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 07:10:38 GMT</pubDate>
            <atom:updated>2025-12-24T07:10:38.893Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous part, we focused on how text is cleaned and prepared before any modeling begins.</p><p>Now that the data is ready, we can ask a more fundamental question:<br> <strong>How was language first represented numerically so that machines could process it?</strong></p><p>In this section, we explore the earliest text representation and probabilistic language models that shaped the first era of NLP.</p><h4>Text Representation</h4><ul><li>Text representation is the process of representing text in a numerical or other format.</li><li>In NLP and Machine Learning applications, texts need to be converted into numerical form so that they can be processed by computers.</li><li>Text representation aims to convert various features of text into numerical data.</li></ul><h4>Why Should Text Representation Be Done?</h4><ul><li><strong><em>Computer Understanding</em></strong> -&gt; Since computers cannot understand text, we need to convert texts into numerical data.</li><li><strong><em>Feature Extraction</em></strong> -&gt; Extracting certain features of words and sentences facilitates analysis and modeling.</li><li><strong><em>Model Training</em></strong> -&gt; ML and DL models work with numerical data.</li></ul><h4>Text Representation Methods</h4><ul><li>Bag of Words (BoW)</li><li>TF-IDF (Term Frequency — Inverse Document Frequency)</li><li>N-Gram Models</li><li>Word Embeddings</li><li>Transformers-Based Text Representation</li></ul><h4>What is Bag of Words (BoW)?</h4><ul><li>BoW is a fundamental text representation method used in NLP and text mining.</li><li>BoW converts the words in texts into numerical data and enables text analysis.</li><li>It counts how many times each word appears in the text. In other words, it counts its frequency.</li></ul><h4>How the BoW Method Works</h4><ul><li><strong><em>Word Set Creation</em></strong> -&gt; A word set is created consisting of all the unique words found in the texts. These words are generally called “Vocabulary”.</li><li><strong><em>Word Frequency Calculation</em></strong> -&gt; The frequency of each word in each text is calculated individually. These frequencies indicate how many times the word appears in the text.</li><li><strong><em>Vector Representation</em></strong> -&gt; Each text is represented by a vector containing the frequency of each word in the word set. If a word is not found in the text, its frequency is considered to be zero.</li></ul><p>Example:</p><ul><li>Word Set Creation<br>Text 1: The cat is in the house<br>Text 2: The cat is in the garden<br>Word Set: Cat, house, garden</li><li>Word Frequency Calculation<br>Text 1: Cat: 1, house: 1, garden: 0<br>Text 2: Cat: 1, house: 0, garden: 1</li><li>Text Representation<br>Text 1: [1, 1, 0]<br>Text 2: [1, 0, 1]</li></ul><h4>What is TF-IDF (Term Frequency-Inverse Document Frequency)?</h4><ul><li><strong><em>TF (Term Frequency)</em></strong> -&gt; Means Term Frequency. It measures how often a word appears in a document. It assumes that data that appears more frequently is more important.</li><li><strong><em>IDF (Inverse Document Frequency)</em></strong> -&gt; Means Inverse Document Frequency. It measures the prevalence of a word across all documents. If a word appears in many documents, that word doesn’t provide much information. It is used to determine whether a word is informative or not.</li><li><strong><em>TF-IDF</em></strong> -&gt; A feature extraction method frequently used in text mining and information retrieval.</li><li><strong><em>TF-IDF</em></strong> -&gt; Used to determine how important words are within documents.</li></ul><p>NOTE: In BoW, the frequency of words within documents is examined, while TF-IDF is used to determine how important words are within documents.</p><h4>What are N-Gram Models?</h4><ul><li>It’s a term that specifies the length of a word or character string used in a language model.</li><li>N-Gram models analyze texts by dividing them into parts of “n” words or “n” characters.</li><li>For example: The sentence “This is big data ai book” would be as follows:<br>Uni-Gram -&gt; “This”, “is”, “big”, “data”, “ai”, “book”<br>Bi-Gram -&gt; “This is”, “is big”, “big data”, “data ai”, “ai book”<br>Tri-Gram -&gt; “This is big”, “is big data”, “big data ai”, “data ai book”</li></ul><h4>Areas of Application of N-Gram Models</h4><ul><li>Text modeling</li><li>Text classification</li><li>Text generation</li><li>Text similarity</li></ul><h4>What are Word Embeddings?</h4><ul><li>Word Embedding is a technique used in NLP and Machine Learning.</li><li>It converts words into numerical vectors that meaningfully represent them, usually in a continuous vector space.</li><li>These representations aim to capture semantic and grammatical relationships between words.</li></ul><h4>Word Embedding Features</h4><ul><li><strong><em>Semantic Similarity</em></strong> -&gt; Words with similar meanings receive similar vectors. For example, the words “king” and “queen” can receive similar vectors.</li><li><strong><em>Mathematical Operations</em></strong> -&gt; Word embedding can express the relationship between words using mathematical operations. For example, the calculation “king” — “man” + “woman” = “queen” can be performed.</li><li><strong><em>Comprehensiveness</em></strong> -&gt; It is usually trained based on large datasets. Therefore, it is successful in capturing various relationships in the language.</li></ul><h4>Word Embedding Models</h4><ul><li><strong><em>Word2Vec:</em></strong> Developed by Google, this is a model that converts words into vectors and trains these vectors to capture relationships in the language.</li><li><strong><em>GloVe (Global Vectors for Word Representation): </em></strong>A model developed by Stanford University that calculates word embedding representations by capturing word associations.</li><li><strong><em>FastText:</em></strong> A model developed by Facebook that calculates word embedding representations by taking word sub-units into account.</li></ul><h4>What is Transformers-Based Text Representation?</h4><ul><li>Transformers is an architecture that has brought revolutionary innovations to NLP and other artificial intelligence fields in recent years.</li><li>Using its attention mechanism, it learns the relationships between each sample word in the input and other words.</li><li>Thanks to this feature, Transformers provides a great advantage in understanding the context, especially in long texts.</li></ul><h4>Why Transformers?</h4><ul><li>Better context understanding</li><li>Parallel processing capability</li><li>Parallel processing capability</li><li>Use in various NLP tasks (text classification, translation summarization, etc.)</li><li>Reuse of pre-trained models (Transfer Learning)</li></ul><h3>Most well-known Transformers Models</h3><h4>BERT (Bidirectional Encoder-Representations From Transformers)</h4><ul><li>It is developed to understand the two-way context of texts. That is, when determining the meaning of a word, it considers both the word before and after it.</li><li>BERT is particularly successful in tasks such as text classification, NER, and question answering.</li><li>It is two-way.</li><li>It understands context in depth.</li></ul><h4>GPT (Generative Pre-trained Transformer)</h4><ul><li>It was developed as a language model.</li><li>It is used in various tasks, especially text generation and language creation.</li><li>It is uni-directional.</li><li>It processes texts from left to right.</li><li>It is an autoregressive model. That is, when predicting a word, it relies on the preceding words.</li><li><strong><em>Attention -&gt;</em></strong> allows the model to pay different degrees of attention to specific input pieces.</li><li>It is especially used to understand the relationship of a word to other words.</li><li>For example, in the sentence “The cat is fast,” the word “fast” calculates the attention scores to the word “cat.”</li><li><strong><em>Query and Key Multiplication -&gt;</em></strong> Calculates the relationship score between the word “cat” and the word “fast”.</li><li><strong><em>Attention Score -&gt;</em></strong> Updates the representation of the word “cat” based on this score.</li><li><strong><em>Input Embedding -&gt;</em></strong> A technique used to convert input data into a format that the model can process.</li><li><strong><em>Multi-Head Attention -&gt;</em></strong> A technique where the attention mechanism works with multiple heads. Each head focuses on a different feature of the input sequence. This allows the model to learn richer and more diverse relationships.</li><li><strong><em>Masked Multi-Head Attention -&gt;</em></strong> Prevents the model from seeing future words, meaning the model only makes predictions using past information.</li><li><strong><em>Add and Norm -&gt;</em></strong> A step that adds a shortcut (residual connection) between the output and input and then applies layer normalization.</li><li><strong><em>Feed Forward Network -&gt;</em></strong> A network present in each encoder and decoder layer.</li><li><strong><em>Output Embedding -&gt; </em></strong>This is a technique used to represent the output of a model, and is commonly used in language models.</li></ul><p>Summary of Text Representation Methods in NLP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*Jq1qhvL-p8KIu_RAZHDeJA.png" /></figure><h3>Probabilistic Language Models</h3><ul><li>Probabilistic language models are statistical methods used to understand and model the structure and organization of language.</li><li>Probabilistic language models include:</li></ul><p>1) N-Gram<br>2) Hidden Markov Models (HMM)<br>3) Maximum Entropy Models (MaxEnt)</p><h4>N-Gram Models</h4><ul><li>N-Gram models estimate the probabilities of consecutive word or character groups in a sequence (usually a sentence).</li><li>Here, “n” indicates the number of elements in this group.</li><li>For example, a “unigram” model considers single words, a “bigram” model considers groups of two words, and a “trigram” model considers groups of three words.<br>n=1: This is a sentence -&gt; unigram -&gt; “This”, “is”, “a”, “sentence”.<br>n=2: This is a sentence -&gt; bigram -&gt; “This is”, “is a”, “a sentence”.<br>n=3: This is a sentence -&gt; trigram -&gt; “This is a”, “is a sentence”.</li></ul><h4>Usage</h4><p>N-grams are used to predict the probability with which a word will follow another word in a sentence.</p><p><strong><em>Advantages</em></strong></p><ul><li>Simple and fast.</li><li>Captures local dependencies well.</li></ul><p><strong><em>Disadvantages</em></strong></p><ul><li>Contextual limitations, meaning they cannot capture long-distance dependencies. For example, the bigram model assumes that a word is only dependent on the preceding word.</li><li>Data requirement, i.e., the “n” value, increases as the data requirement increases.</li></ul><h4>Hidden Markov Models (HMM)</h4><ul><li>HMMs are based on the assumption that behind a set of observations (such as words or characters) there is a hidden set of states (e.g., grammatical categories).</li><li>HMMs assume that each state will transition to another state with a certain probability, and each state will produce a specific observation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTtuK50xiMcV9rjJ-1WnHw.png" /></figure><ul><li>Here, the probability of the word “love” following the word “I” is 0.3, which is 30%, or the probability of the word “you” following the word “I” is 0.2, which is 20%.</li></ul><h4>Usage</h4><ul><li>Speech recognition</li><li>Language modeling</li><li>Part of Speech Tagging</li></ul><p><strong><em>Advantages</em></strong></p><ul><li><strong><em>Context Modeling -&gt; </em></strong>Can model the transitions between states and the probabilities of transitioning from a state to an observation. That is, it can construct meaningful sentences.</li><li><em>Efficient Algorithms -&gt;</em> Can run quickly depending on the size of the dataset.</li></ul><p><strong><em>Disadvantages</em></strong></p><ul><li><strong><em>Simplifying Assumption -&gt;</em></strong> HMM assumes that dependencies only come from the previous state.</li><li><strong><em>Training Difficulty -&gt;</em></strong> Does not perform well if there is no data.</li></ul><h4>Maximum Entropy Models (MaxEnt)</h4><ul><li>Maximum Entropy models aim to make as few assumptions as possible when estimating a probability distribution.</li><li>In other words, they aim to estimate probabilities by using the known information to its fullest extent.</li><li>The Maximum Entropy Principle stipulates that when estimating an unknown probability distribution, one should choose the most irregular (highest entropy) distribution possible. This means that no unnecessary assumptions should be made based on the available data.</li><li>Entropy is a measure of the uncertainty of a distribution. Therefore, in Maximum Entropy, it represents the distribution with the least bias.</li></ul><h4>Usage</h4><ul><li>MaxEnt models are used especially in classification tasks.</li><li>For example, they can estimate the probability of a sentence belonging to a particular class (such as positive or negative sentiment).</li></ul><p><strong><em>Advantages</em></strong></p><ul><li>Flexibility</li><li>Good generalization</li></ul><p><strong><em>Disadvantages</em></strong></p><ul><li>Computational cost</li><li>Feature engineering is difficult.</li></ul><p>While these models were powerful for their time, they shared a common limitation:<br> they relied heavily on local statistics and struggled to capture deeper semantic relationships.</p><p>To overcome these limitations, NLP needed a new representation paradigm — one that could learn meaning, not just frequency.</p><p>This shift marked the beginning of <strong>vector-based representations and neural language models</strong>, which we will explore next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63eb0a3e900b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Bag of Words to Language Models: How NLP Really Started]]></title>
            <link>https://medium.com/@goktugdagi/from-bag-of-words-to-language-models-how-nlp-really-started-9a04c5844d1c?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a04c5844d1c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 08:10:23 GMT</pubDate>
            <atom:updated>2025-12-22T08:10:23.046Z</atom:updated>
            <content:encoded><![CDATA[<p>Natural Language Processing (NLP) is a field of artificial intelligence that aims to enable machines to understand, process, and generate human language. While we can now produce very powerful solutions with Transformer-based large language models (LLMs), this point wasn’t reached overnight.</p><p>To truly understand modern NLP, we must first answer this question:</p><ul><li>How did we initially model language problems, and why have these approaches proven inadequate?</li></ul><p>This article examines the classic text representation methods and statistical language models that initiated the evolution of NLP from a simple yet technical perspective.</p><h4>What is Natural Language Processing (NLP)?</h4><ul><li>NLP is a field of artificial intelligence that uses computers to understand, analyze, and generate human language.</li><li>It includes techniques and algorithms for understanding the meaning and context of language.</li><li>The goal of NLP is to transfer knowledge of human language to computers and automatically perform language-based tasks. For example, this can involve performing various analyses on text and speech data, such as determining whether an email is spam or not.</li></ul><h4>Base Tasks</h4><ul><li><strong><em>Text Classification:</em> </strong>The process of separating texts into specific categories. This task allows texts to be assigned to predetermined classes. For example, an email filtering system can classify incoming emails as spam or important.</li><li><strong><em>Sentiment Analysis:</em></strong> The process of identifying emotions and thoughts in texts, i.e., positive, negative, or neutral. This task can be used to understand the overall emotional state of texts.</li><li><strong><em>Named Entity Recognition (NER): </em></strong>NER is used to recognize and classify proper names such as people, places, and organizations in texts.</li><li><strong><em>Part-of-Speech (POS) Labeling: </em></strong>Determines the grammatical roles of words. That is, it attempts to identify whether words in a text are nouns, verbs, or adjectives.</li><li><strong><em>Text Summarization: </em></strong>The process of summarizing long texts to provide concise information. This task is used to summarize the main points or important information of texts.</li><li><strong><em>Machine Translation:</em></strong> The process of translating text from one language to another. This task automatically translates text between different languages.</li><li><strong><em>Chatbots:</em></strong> Artificial intelligence applications that answer questions and perform various tasks by interacting with users in natural language.</li><li><strong><em>Speech Recognition:</em></strong> The process of converting spoken language into text. For example, giving voice commands using Siri or Google Assistant.</li></ul><h4>Application Areas</h4><ul><li><strong><em>Healthcare:<br>1) </em></strong>Patient records and documentation<br>2) Medical content analysis<br>3) Patient communication and support</li><li><strong><em>Customer Relations and Support:<br></em></strong>1) Chatbots and virtual assistants<br>2) Sentiment analysis<br>3) Email and request management</li><li><strong><em>Finance and Banking:<br></em></strong>1) Risk management<br>2) Investment research<br>3) Automated reporting</li><li><strong><em>Education and Academic:<br></em></strong>1) Automated note-taking<br>2) Academic research and literature review<br>3) Learning and training aids</li><li><strong><em>Retail and E-commerce:<br></em></strong>1) Product recommendation systems<br>2) Customer reviews and ratings<br>3) Inventory management</li><li><strong><em>Media and Entertainment:<br></em></strong>1) Automated content generation<br>2) Comprehensive content analysis<br>3) Speech and voice recognition</li><li><strong><em>Human Resources:<br></em></strong>1) Automation of recruitment processes<br>2) Employee satisfaction and feedback analysis<br>3) Performance appraisals</li></ul><h4>Text Preprocessing</h4><ul><li>Text preprocessing is the process of transforming raw text data into a more suitable format for analysis and processing.</li><li>It essentially involves standardizing, cleaning, and structuring text data before moving on to the modeling and analysis phase.</li></ul><h4>Why Should Text Preprocessing Be Done?</h4><ul><li>It improves data quality.</li><li>It improves model performance.</li><li>It manages data dimensionality.</li></ul><h4>Text Preprocessing Steps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcHv0opBwjThp2cvVtS4Ig.png" /></figure><h4>Data Cleaning</h4><ul><li>Veri temizleme, metin verilerini analiz edilebilir hale getirmek için yapılan bir dizi işlemi içerir.</li><li>Errors, redundancies, disorganization, or elements that could negatively impact model performance are removed or corrected.</li></ul><p><strong><em>Data Cleaning Steps:</em></strong></p><ul><li>Removing spaces</li><li>Case conversion</li><li>Removing punctuation marks</li><li>Removing special characters</li><li>Correcting spelling errors</li><li>HTML and URL cleaning</li></ul><h4>Tokenization</h4><ul><li>This is the process of breaking down a text into smaller parts.</li><li>These smaller parts are often called “tokens.”</li><li>Tokens can be words, sentences, or characters.</li><li>It is an important step for text analysis because it is necessary to make raw data meaningful and analyzable.</li></ul><h4>Stemming</h4><ul><li>Stemming is the process of removing suffixes from a word to find its root form (i.e., its basic meaning).</li><li>Stemming does not aim to obtain the meaning of the word completely accurately; rather, it focuses on finding the simplest form of the word.</li><li>For example, “running”, “runner”, “ran”, “runs” -&gt; “run”, “run”, “ran”, “run”</li></ul><h4>Lemmatization</h4><ul><li>Lemmatization is the process of converting words back to their basic lemmas in the dictionary.</li><li>Lemmatization attempts to find a correct root word by considering the meaning and grammatical structure of the word.</li><li>The word obtained after lemmatization is grammatically meaningful and a word that is included in the dictionary.</li><li>For example, “running”, “runner”, “ran”, “runs” -&gt; “run”, “runner”, “run”, “run”</li></ul><h4>Stop Words</h4><ul><li>Stop words are words in texts that generally have little meaning or are not very helpful during text analysis.</li><li>These words are usually conjunctions, prepositions, pronouns, and other words with grammatical functions.</li><li>Removing these words during text processing can improve the accuracy of analyses and help obtain more meaningful results on the text.</li></ul><p>At this point, we have defined what NLP problems look like and how raw text is transformed into a usable format.<br> However, preparing text is only the beginning.</p><p>The next critical question is: <strong>How do we convert text into numbers so that machines can actually learn from it?</strong></p><p>In the next part, we will explore the earliest text representation techniques that laid the foundation of modern NLP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a04c5844d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stacking & Voting: Behind the Scenes of the Most Powerful Ensemble Models]]></title>
            <link>https://medium.com/@goktugdagi/stacking-voting-behind-the-scenes-of-the-most-powerful-ensemble-models-c791a35925ac?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c791a35925ac</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 20:19:47 GMT</pubDate>
            <atom:updated>2025-11-21T20:19:47.490Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most fascinating aspects of machine learning is that we’re not limited to a single model.<br> A decision tree offers interpretability, logistic regression brings stability, and XGBoost aggressively minimizes errors — but none of them are perfect alone.<br>But what if we could <em>combine their strengths</em> into a single, superior learner?<br>That’s when stacking and voting take the stage.<br>This article transforms my handwritten study notes into a structured and deeply technical explanation of how these ensemble methods truly work.</p><h4>What Is Stacking?</h4><ul><li>Stacking is an ensemble method that combines the predictions of “different” machine learning models (submodels) to create a more robust prediction model (metamodel).</li><li>The basic idea is to compensate for the “weaknesses” of individual models and increase generalization ability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S00JiylZV09tHGaZtNWozg.png" /></figure><ul><li>Each Base learner is a different model. That is, it uses different models within itself.</li></ul><h4>Bagging vs. Boosting vs. Stacking</h4><ul><li>The difference between Bagging and Boosting is that the models are run in parallel and then combined into a meta-model.</li><li>Stacking offers the flexibility to combine heterogeneous models (different algorithms).</li><li>In Stacking, a single model makes the final decision by learning the results of the “Meta Learner”. It does this by taking the predictions from previous models, learning from them, and then making a decision accordingly.</li></ul><p><strong><em>Note:</em></strong> Diversity is important when choosing a “base model” in Stacking. We should increase diversity by selecting different models. This is because if similar models make the same mistakes, the advantage of stacking decreases.</p><h4>Stacking General Process</h4><ul><li>Training data is fed to submodels (base learners), each of which generates its own predictions.</li><li>These predictions are used as a new feature set for training the metamodel.</li><li>The metamodel makes the final prediction.</li></ul><p><strong><em>Note:</em></strong> In stacking, the submodels, or base models, provide complexity. In other words, the main power lies in the base models. The metamodel helps reduce the risk of overfitting. The metamodel enables prediction by comparing the results from the base models.</p><h4>Mathematical Foundations of Stacking</h4><p><strong><em>Notation:</em></strong></p><ul><li>Training data:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*sUh80Nt8EwwB13G_ZB6a4A.png" /></figure><p>where xi​ represents the features and yi​ represents the target variable.</p><ul><li>M number of sub-models:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*sCCexW17YtqMTH_ku3rFSA.png" /></figure><p>These are the base learners used in stacking.</p><ul><li>Meta model:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*JUg1krT4lutIFvv3LB1TPg.png" /></figure><p>Here, z is a new feature vector formed by the predictions of the base models.<br> The meta model uses this vector as input to produce the final prediction.</p><h4>Step-by-Step Math</h4><ul><li><strong><em>Submodel predictions:</em></strong> For each hm(x), it produces a prediction for x.</li><li><strong><em>Training the metamodel: </em></strong>The metamodel predicts y using the z vector. For example, for a linear metamodel:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*fU-yfCpW3TrwctjqqN1Y2Q.png" /></figure><p>Where wm are the weights of the submodels and are found through optimization. MSE is typically used for regression, and LogLoss is typically used for classification.</p><ul><li><strong><em>Error minimization:</em></strong> The metamodel is typically trained to minimize a loss function. Cross-Entropy is used for classification, and MSE is used for regression.</li></ul><h4>Stacking Advantages and Disadvantages</h4><p><strong><em>Advantages:</em></strong></p><ul><li>It provides high performance by combining the strengths of different models.</li><li>It can be used flexibly with heterogeneous models.</li><li>It can produce theoretically optimal predictions if the error correlation of submodels is low.</li><li>It can increase generalization ability.</li></ul><p><strong><em>Disadvantages:</em></strong></p><ul><li>Training multiple models and adding a meta-model requires high computational costs.</li><li>The risk of overfitting increases if K-fold cross-validation is not used.</li><li>Model selection and hyperparameter tuning can be complex and time-consuming.</li><li>It is more difficult to implement and interpret than other ensemble methods.</li></ul><p>While stacking leverages a meta-learner to intelligently combine predictions from diverse base models, not every scenario requires such a complex architecture. In many practical cases, we simply need a faster and lighter mechanism that aggregates model decisions without training an additional learner. This is where Voting and Averaging come into play. Unlike stacking, voting does not “learn” how to combine models — rather, it relies on straightforward principles such as majority vote or probability averaging to produce the final prediction. With that, let’s transition from the structured intelligence of stacking to the elegant simplicity of voting.</p><h4>What Is Voting?</h4><ul><li>Voting is one of the fundamental methods of ensemble learning and aims to produce a final prediction by combining the predictions of multiple machine learning models (sub-models).</li><li>This method is used to compensate for the weaknesses of individual models and achieve more robust and generalized predictions through a collective decision-making mechanism.</li><li>It is based on the principle of “wisdom of the crowd.”</li></ul><h4>Its Place in the Ensemble Context</h4><ul><li>Voting differs from methods like Bagging and Boosting in that the model training processes are generally independent of each other, and the aggregation phase relies on a simple aggregation or voting rule.</li><li>It is less complex than Stacking because a direct aggregation rule is used instead of meta-model training.</li><li><strong>Application Areas:</strong><br>Classification: Class prediction using Hard Voting (Majority Voting) or Soft Voting (Probability Averaging)</li><li>Regression: The final prediction is produced by averaging the continuous predictions of submodels.</li></ul><h4>Hard Voting</h4><ul><li>The class prediction (label) of each submodel is considered a “vote,” and the class with the most votes is selected as the final prediction.</li><li>It is based on the “majority” rule.</li><li>It is simple and fast, but it does not take into account the confidence level (probabilities) of the models.</li></ul><h4><em>Soft Voting</em></h4><ul><li>The class probability predictions of each model are averaged, and the class with the highest average probability is selected.</li><li>It takes into account the confidence level (probabilities) of the models.</li><li>Models that can provide probability output are used.</li><li>For example, if the probabilities of three models are (0.9, 0.6, 0.8), the average is (0.9 + 0.6 + 0.8)/3 = 0.77, and this class is selected.</li><li>It is more informative because the probabilities reflect the predictive power of the models.</li></ul><h4>Weighted Averaging</h4><ul><li>The predictions of each model are combined and weighted according to their performance or reliability.</li><li>Weights can be determined by metrics such as the models’ accuracy on the training set.</li></ul><h4>Hard Voting Mathematics</h4><ul><li>If each model hm(x) produces independent predictions from a Bernoulli distribution, the majority vote follows a Binomial distribution.</li><li>Error Probability: For an odd number of models, M, if the probability of a correct prediction is “p”, then the error probability is given by:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*svTYkxkhDdXKF1Lr6qaCnw.png" /></figure><ul><li>The error decreases as the diversity (number of models) increases. (Condorcet’s Jury Theorem)</li><li>The error decreases as M increases.</li></ul><h4>Soft Voting Mathematics</h4><ul><li>When probabilities are averaged, the final prediction is based on an expectation value:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_8JgV-a0GU8d-xu-WmUpA.png" /></figure><ul><li><strong><em>Assumption:</em></strong> If the predictions of the models are independent and not biased, the average error variance decreases.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*SWOjQgegqJH3vmWpVneztw.png" /></figure><ul><li>The variance decreases if the diversity (M) increases.</li></ul><h4>Weighted Average Mathematics</h4><ul><li>If the weights are chosen optimally, the error variance decreases further.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*VUqK5HimmL9nYuhdYKHYWA.png" /></figure><h4>Voting Advantages and Disadvantages</h4><h4>Advantages:</h4><ul><li>Simple and fast to implement.</li><li>Provides generalization by balancing the errors of various models.</li><li>Increases flexibility with weighted averaging.</li><li>Mathematically reduces error variance.</li></ul><h4>Disadvantages:</h4><ul><li>Performance decreases if the dependence (correlation) of models is high.</li><li>Probability output is required for soft voting, but not every model supports this.</li><li>Determining optimal weights requires additional effort.</li><li>Provides limited performance gains compared to more advanced methods such as stacking.</li></ul><p>Despite its simplicity, Voting remains one of the most practical and reliable ensemble techniques. By leveraging the diversity of multiple models, it balances individual weaknesses and produces more stable predictions. Hard Voting brings the power of majority decisions, while Soft Voting provides a probabilistic and more informative alternative.</p><p>Ultimately, Voting stands as a proven, foundational ensemble method — an excellent option when seeking stability, speed, and interpretability without the complexity of more advanced techniques. It deserves a place in every machine learning engineer’s toolkit.</p><p>Throughout this three-part Ensemble Learning series, we explored the fundamental pillars that power modern machine learning:</p><ul><li><strong>Bagging</strong> for reducing variance and improving stability through bootstrap sampling,</li><li><strong>Boosting</strong> for sequential error correction and the mathematical foundations behind XGBoost, LightGBM, and CatBoost,</li><li><strong>Stacking &amp; Voting</strong> for leveraging the collective intelligence of heterogeneous models to achieve top-tier predictive performance.</li></ul><p>While each method excels in different scenarios, they all share one unifying principle:<br> <strong>No single model is as strong as a well-designed ensemble.</strong></p><p>From competition-winning solutions to production-level ML systems, ensemble methods lie at the core of today’s most robust models.</p><p>If you’ve completed this series, you’re not just learning algorithms — you’ve gained an <strong>ensemble mindset</strong>, a way of thinking that allows you to build more resilient models and approach complex problems with greater precision.</p><p>Thank you for following the series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c791a35925ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting: Turning Weak Learners into a Championship Team]]></title>
            <link>https://medium.com/@goktugdagi/boosting-turning-weak-learners-into-a-championship-team-e8b79c39ec97?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b79c39ec97</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 04:38:01 GMT</pubDate>
            <atom:updated>2025-11-17T04:38:01.666Z</atom:updated>
            <content:encoded><![CDATA[<p>Train weak learners sequentially, fix previous errors, and build a powerful ensemble: AdaBoost, Gradient Boosting, XGBoost, LightGBM, CatBoost.</p><p>Imagine preparing for an exam. Your first attempt doesn’t bode well. You identify the topics you made mistakes on and focus solely on those weaker topics on the next attempt. Your score improves. On the next attempt, you target the topics you made the most mistakes on again. Each step corrects the previous one, and your results gradually improve.<br>Boosting is exactly this strategy: a family of methods that train weak learners one by one, sequentially, compensating for previous errors to create a strong ensemble.</p><h4>What is Boosting?</h4><ul><li>Boosting is one of the ensemble learning methods that combines weak learners to create a strong model.</li><li>In Boosting, models are trained sequentially, with each new model attempting to <strong><em>correct the errors of the previous model.</em></strong></li><li>Decision trees are often used in training.</li></ul><h4>Basic Steps of Boosting</h4><ul><li>The first weak model is trained on the entire dataset.</li><li>Subsequent models weight the data points corresponding to the previous model’s mispredictions (errors). In other words, the errors are weighted.</li><li>The new model is trained after weighting the errors.</li><li>The process continues sequentially, and ultimately, the outputs of all models are combined to create a strong model.</li></ul><p>Note: Trying to reduce variance is trying to reduce overfitting.<br>Note: Trying to reduce bias is trying to correct for underfitting.</p><h4>Types of Boosting Methods</h4><ul><li><strong>AdaBoost (Adaptive Boosting):</strong> Each new model places more weight on the <strong><em>“errors”</em></strong> of the previous model. It is a simple and effective boosting method.</li><li><strong>GBM (Gradient Boosting Machine):</strong> A method that minimizes the error differences is used to correct errors. It is widely used in regression and classification problems.</li><li><strong>XGBoost (Extreme Gradient Boosting):</strong> An optimized and accelerated version of GBM. It is very effective on large datasets.</li><li><strong>LightGBM:</strong> It is faster than GBM and performs better with large-scale data.</li><li><strong>CatBoost (Categorical Boosting):</strong> Optimized for working with categorical data and provides high accuracy without requiring hyperparameter adjustments.</li></ul><p>Now let’s explain the boosting methods briefly explained above.</p><h4>What is AdaBoost (Adaptive Boosting)?</h4><ul><li>AdaBoost is an ensemble learning method that combines weak learners into a strong model.</li><li>The goal of AdaBoost is to improve the model’s accuracy by correcting errors.</li><li>It allows for better learning by assigning more weight to incorrectly predicted examples. In other words, the weights of incorrect examples are increased and the weights of correct examples are decreased.</li><li>Decision stump versions of decision trees (depth 1) are often used.</li></ul><h4>How Does AdaBoost Work?</h4><ol><li>Initially, the weights of all samples are equal: <br>First, all data points are assigned equal weights.So initially all examples are equally important.<br>N -&gt; Number of data points<br>wi -&gt; Weight of the ith sample</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*_2oMZGDq8vqHV0Jj8Dz2qw.png" /></figure><p>2. Training the first weak learner:</p><ul><li>It trains a weak learner model (usually a 1-level Decision Tree-Decision Stump).</li><li>This model predicts the dataset, correctly predicting some examples and incorrectly predicting others.</li><li>Points predicted correctly are given a “Low Error Rate,” and points predicted incorrectly are given a “High Error Rate.”</li></ul><p>3. Calculating the model’s error rate:</p><ul><li>The error rate (E) of the weak model is calculated as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*gGsEifF0UtNpo6i5QBxLCA.png" /></figure><ul><li>If the model incorrectly predicts the ith sample, it returns 1, and if it correctly predicts, it returns 0.</li><li>The error rate is calculated by summing the weights of the incorrectly predicted samples.</li></ul><p>4. Determining the model’s strength (Alpha Weight):</p><ul><li>The weight of the model is determined by the error rate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*a6_1ceK0M4G3GjuxRIcmrA.png" /></figure><ul><li>If the error rate is low (E is small), alpha is large. The model is considered more robust.</li><li>If the error rate is high (E is large), alpha is small. The model’s effectiveness decreases.</li><li>If the error rate is 0.5, the model is making random predictions, so alpha approaches zero and its effectiveness decreases.</li></ul><p>5. Increasing the weights of incorrectly predicted examples:</p><ul><li>The weights of the examples that the new model predicted incorrectly are “<strong><em>increased</em></strong>.”</li><li>This way, the next model focuses more on these errors.</li><li>The new weights are updated as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*uT0Gmz2hZcZ9f59nRBqz3g.png" /></figure><ul><li>However, the sum of all weights must still be 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*yNGcAkXiJLLtIM2rbCk9-w.png" /></figure><ul><li>Z -&gt; Normalization factor reduces the total weights to 1.</li><li>The weights of incorrectly predicted examples increase, so the next model assigns more importance to these examples.</li><li>The weights of correctly predicted examples decrease, as they were already well predicted.</li></ul><p>6. The new model is trained, and the process is repeated:</p><ul><li>Steps 2–5 above are repeated.</li><li>Each model attempts to correct the errors of the previous model.</li></ul><p>7. Combining All Models (Weighted Voting):</p><ul><li>All trained weak models are combined into a strong model through weighted fusion.</li><li>The final prediction is calculated by weighting the predictions of all models.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*akMW6-HepZvMSrzp10GsFw.png" /></figure><p>The final prediction is obtained by taking the sign of the weighted sum of the predictions from all weak learners.</p><p>Now that we’ve explored what AdaBoost is and how it works, we’ve established an important foundation: the idea of iteratively correcting mistakes to build a strong predictive model. AdaBoost showed us how weak learners can be boosted by focusing more heavily on misclassified examples, allowing the ensemble to steadily refine itself.</p><p>But the story of boosting doesn’t end there.<br> As machine learning problems grew more complex — ranging from regression tasks to datasets with intricate structures — the limitations of AdaBoost became more noticeable. The need for a more flexible, more general, and more powerful boosting framework started to emerge.</p><p>This is where one of the most influential families of modern machine learning methods enters the stage: <strong>Gradient Boosting Machines (GBM).</strong></p><p>Inspired by the core ideas behind AdaBoost yet built on a much broader foundation, GBM shifts the perspective from simply reweighting errors to <strong>optimizing a loss function through gradient descent</strong>. In other words, instead of just emphasizing misclassified points, GBM learns from the <strong>gradient of the loss itself</strong>, giving it far more flexibility across tasks and data types.</p><p>With that, let’s dive into the next evolution of boosting and uncover the principles behind Gradient Boosting Machines.</p><h4>What is GBM (Gradient Boosting Machine)?</h4><ul><li>Gradient Boosting Machine is a boosting method that creates a strong model by correcting errors.</li><li>Gradient Boosting uses gradient descent to directly learn the errors from the model.</li><li>Gradient Boosting performs better than AdaBoost, especially on large datasets and complex problems.</li></ul><h4>How Does GBM Work?</h4><ol><li>Training the first model:</li></ol><ul><li>A simple model (usually a small decision tree) is trained.</li><li>The model makes predictions, and residual errors are calculated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*9FbXQ051o9d30sengGGUdQ.png" /></figure><ul><li>The calculated error is used to train the next model.</li></ul><p>2. Training the new model that learns errors:</p><ul><li>The second model attempts to predict the errors made by the first model. In other words, a model that predicts errors is trained.</li><li>The new model attempts to reduce errors and makes predictions as follows:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*mRYMsaqS8b3FFaniVAaDdg.png" /></figure><p>v → Learning rate<br> Typically chosen between <strong>0.1 and 0.3</strong>. It controls how much each new weak learner contributes to the overall model. Smaller values result in slower but more stable learning.</p><p>h1(x) →<em>The model that predicts the residual (error)<br></em>It learns the part of the data that the previous model could not explain — essentially the “error pattern” that needs to be corrected.</p><p>3. Calculating the total prediction of the new model:</p><ul><li>The first and second models are combined to produce a new prediction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*hiU-OEhFvH6LAivWyetDfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*CakI9CJygKloloodOrQgEQ.png" /></figure><p>v → Learning rate<br>h(x) → The error model (residual learner)</p><ul><li>This process is repeated with multiple models.</li><li>Each new model attempts to reduce the errors of the previous model.</li></ul><p>4. Using Gradient Descent to Minimize Errors:</p><ul><li>In AdaBoost, errors were corrected by changing the sample weights. GBM uses Gradient Descent to directly minimize errors.</li><li>The goal is to minimize the loss function. MSE is typically used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*pXmC-E0kLjuks1GYwzSQpw.png" /></figure><ul><li>By taking the derivative of this function, we find the fastest way to reduce errors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*G-0bHixBGKUgIBN0HvOuag.png" /></figure><p>It measures <strong>how the loss function L<br></strong>Changes with respect to the <strong>model prediction y^</strong></p><ul><li>Gradient descent updates the model to minimize errors.</li></ul><p>We now have a clear understanding of how traditional Gradient Boosting works. Classic GBM is powerful, but it can be slow, memory-intensive, and sensitive to hyperparameters. As datasets grow and models need to scale efficiently, the need for a more optimized, faster, and more robust form of boosting has become unavoidable.</p><p>This is where XGBoost (Extreme Gradient Boosting) comes into play.</p><p>Let’s take the next step and examine how XGBoost works and why it has become one of the most influential algorithms in modern data science.</p><h4>What is XGBoost(Extreme Gradient Boosting)?</h4><p>XGBoost is an improved and optimized version of GBM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*vaQcGO4a5ifxIKMPyoq-Vg.png" /></figure><h4>How Does XGBoost Work?</h4><ul><li>The basic structure of XGBoost is the same as GBM, but includes some additional optimizations.</li><li>The first model is trained (a simple decision tree).</li><li>Errors are calculated.</li><li>The new model attempts to learn from the errors.</li><li>Each model corrects the errors of the previous model.</li><li>Optimizations are applied to prevent overfitting.</li></ul><ol><li>The general formula of the model is:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*i4OmHCvlHmmCJDLJadIH4g.png" /></figure><ul><li>This equation shows that in XGBoost (and in boosting models in general), the final prediction is obtained by summing the contributions of all individual trees.</li><li>Each new tree attempts to correct the errors of previous trees.</li></ul><p>2. Using the Loss Function:</p><ul><li>The loss function is used to measure the accuracy of predictions.</li><li>Generally, MSE is used for Regression and LogLoss for Classification.</li><li>Gradient Descent is applied to minimize these loss functions.</li></ul><p>3. Minimizing the loss function with Gradient Descent at each step:</p><ul><li>XGBoost minimizes the loss using the first derivative (gradient) and the second derivative (hessian matrix).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*yM4akcTexeqo_6j4zuJ1qg.png" /></figure><ul><li>These derivatives are used to update the data in a way that minimizes the loss as quickly as possible.</li><li>If the derivative is high, the error is large. The update is performed in a large way.</li></ul><p>4. Updating the new model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*ctkNWVJo52Yi0FsxbtGDWQ.png" /></figure><ul><li>The Gradient(g) indicates how “<strong><em>large</em></strong>” the error is.</li><li>The Hessian(h) indicates how much the error has “<strong><em>changed</em></strong>.”</li><li>This allows the new model to better correct for the errors of the previous model.</li></ul><h4>Key Features of XGBoost</h4><ol><li>Regularization (L1 and L2 support)</li></ol><ul><li>L1 (Lasso) and L2 (Ridge) penalties have been added to prevent overfitting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*F2InN0D9oaaNtt_WQgUBvA.png" /></figure><ul><li><strong>L2(Ridge) term:</strong> Shrinks the weights but does <strong>not</strong> force them to zero.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*vO7edhS9kGKrBRGuoyG5cg.png" /></figure><ul><li><strong>L1 (Lasso) term</strong>: Forces small weights to become exactly zero (producing sparse models).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*3PjkAp46fumQZfFwqB4JhQ.png" /></figure><ul><li><strong>L1 → drives small weights to zero (sparsity)</strong></li><li><strong>L2 → reduces weights but keeps them non-zero</strong></li><li>A more regular and better generalizing model is achieved.</li></ul><p>2. Faster execution with parallel computing:</p><ul><li>XGBoost can perform very fast calculations using both the CPU and GPU.</li><li>Recursive calculations are not used; all trees are created in parallel.</li></ul><p>After examining XGBoost and understanding how its optimizations (regularization, parallelization, and efficient tree building) have made it one of the most dominant algorithms in machine learning, it’s natural to ask what’s next. As datasets grew larger and models needed to be trained faster without sacrificing accuracy, the need for a more scalable acceleration method became apparent.</p><p>This paved the way for LightGBM, a gradient acceleration framework designed specifically for speed and efficiency. Unlike XGBoost, which grows trees level by level, LightGBM introduces a new leaf-based (best-first) tree growing strategy combined with advanced techniques such as Gradient-Based Single-Sided Sampling (GOSS) and Exclusive Feature Packing (EFB). These innovations allow LightGBM to train significantly faster, use less memory, and easily handle high-dimensional data.</p><p>Let’s explore how LightGBM pushes the boundaries of gradient boosting even further and why it has become the go-to choice for large-scale, high-performance machine learning tasks.</p><h4>What is LightGBM?</h4><ul><li>LightGBM is a Boosting algorithm similar to XGBoost but much faster.</li><li>It performs particularly well on large datasets and high-dimensional problems.</li><li>While XGBoost uses depth-fixed decision trees, LightGBM uses depth-flexible trees.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*QHjKradopWnqZwWcaTM3dw.png" /></figure><h4>How Does LightGBM Work?</h4><ul><li>The first model is trained (a simple Decision Tree).</li><li>Residuals are calculated.</li><li>The new model attempts to learn the errors.</li><li>New models are added to correct previous errors.</li><li>Trees are trained using LightGBM’s specialized methods.</li></ul><h4>LightGBM’s Difference</h4><ul><li>XGBoost’s tree growth method is Level-wise, meaning it fills each Level. LightGBM, on the other hand, grows all branches simultaneously. Leaf-wise, meaning it allows different branches to grow to different depths without defining Levels, or it allows us to see different Levels of another branch without defining a Level. In other words, one branch can remain at Level 2 while another branch has already reached Level 3.</li><li>It runs slower, but it’s more stable.</li><li>LightGBM’s tree growth method (Leaf-wise) grows only the branch that reduces the error the most.</li><li>It runs faster, but the risk of overfitting may increase.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*XHXAXkx8zf6HYMV8oTxORw.png" /></figure><h4>LightGBM Mathematics</h4><ol><li>Estimated values:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*m3V2eOMuxpTNftl6ZlzLaQ.png" /></figure><p>This formula shows that in boosting models, the final prediction is obtained by summing the outputs of all individual trees.</p><p>2. Loss function and optimization:</p><ul><li>LightGBM uses second derivative (Hessian) information to minimize errors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*VTIusFnxfQ6KF1qehGbbaw.png" /></figure><ul><li>So, the model is updated as follows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*U0rcaX8SrDPGkVJHPHoidA.png" /></figure><p>3. The mathematics of leaf-wise growth:</p><ul><li>LightGBM calculates the error reduction (gain function) to determine which branch to grow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*Jex7Th-pC1Dpt8pmLBEM8Q.png" /></figure><ul><li>G → Gain</li><li>GL, GR → Gradient (1st derivative) values ​​at the left and right nodes</li><li>HL, HR → Hessian (2nd derivative) values ​​at the left and right nodes</li><li>lambda → Regularization coefficient</li><li>The node with the highest Gain value is grown, reducing computational time and making the model run faster.</li></ul><p>After reviewing LightGBM and understanding its leaf-based growth strategy, a challenge remains: effectively processing categorical features. While both XGBoost and LightGBM can work with categorical variables, they typically require manual preprocessing, such as one-hot encoding or label encoding, which can introduce noise, increase dimensionality, and even harm model performance.</p><p>This is where CatBoost comes in as the next evolution of gradient boosting.</p><p>CatBoost is specifically designed to process categorical data locally, using advanced techniques such as sequential target encoding and permutation-oriented splitting to prevent target leakage and preserve generalization. Combined with symmetric tree structures and efficient GPU support, CatBoost offers a powerful, ready-to-use solution for real-world datasets rich in categorical features.</p><p>Let’s move on and examine how CatBoost simplifies preprocessing while maintaining high accuracy and stability across a variety of machine learning problems.</p><h4>What is CatBoost(Categorical Boosting)?</h4><ul><li>CatBoost is a boosting algorithm based on GBM that works particularly well with categorical data.</li><li>It can handle categorical data directly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*CjSgerpNA65faVAvj5NLIA.png" /></figure><h4>CatBoost Highlights</h4><ul><li>Reduces overfitting (using Ordered Boosting).</li><li>Uses categorical data directly.</li><li>Runs very fast with GPU support.</li></ul><h4>CatBoost Mathematics</h4><ol><li>The general formula of the model:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*67z8ThVj3HBGxJiP2XwCYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*YYR25GmXnP6HWcfpWr6Tgw.png" /></figure><ul><li>This formula shows that in boosting models, the final prediction is obtained by summing the outputs of all individual trees.</li></ul><p>2. Using the Loss Function:</p><ul><li>CatBoost uses Gradient Descent to minimize the loss function.</li><li>If there is a <strong><em>classification</em></strong> problem, <strong><em>LogLoss </em></strong>is used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzyrrqITBiuVVov5pNvNJg.png" /></figure><ul><li>If there is a <strong><em>regression </em></strong>problem, <strong><em>MSE </em></strong>is used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*L-I68D7ROWmWnhrfcrVAvg.png" /></figure><p>3. Using Ordered Boosting:</p><ul><li>CatBoost prevents past data from influencing the future with Ordered Boosting.</li><li>In standard Gradient Boosting, the new model is trained using all previous data. CatBoost, on the other hand, divides the data into two groups: past and future, and makes new predictions using only past data. This significantly reduces overfitting.</li></ul><p>4. Transformation of categorical data (Categorical feature encoding):</p><ul><li>CatBoost uses the mean of the target variable instead of one-hot encoding.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*w2osQxXrEXSfOa7FcP3yNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*BjE4GXgB17kdzNB5dIBRKQ.png" /></figure><ul><li>A smoothing factor is added to prevent over-le arning of categories with few examples.</li></ul><h4>Conclusion</h4><p>Now that we’ve explored the evolution of boosting, from AdaBoost’s core idea of ​​reweighting errors to Gradient Boosting’s gradient-based optimization and highly optimized implementations like XGBoost, LightGBM, and CatBoost, we have a much clearer understanding of how these models work and why they are so widely used in modern machine learning.</p><p>Each method introduces new innovations: XGBoost, with its regularization and system-level optimizations, LightGBM with its leaf-based growth and remarkable speed, and CatBoost with its intelligent handling of categorical features. Together, they demonstrate how flexible and powerful boosting algorithms can be across a wide range of real-world tasks.</p><p>With this foundation in place, we can now step back and look at the bigger picture.</p><p>What makes boosting so effective, and where does it struggle?</p><h4>Advantages and Disadvantages of Boosting</h4><p>Advantages:</p><ul><li><strong>Higher Accuracy:</strong> Boosting makes robust predictions by correcting errors.</li><li><strong>Low Error Rate:</strong> Better results are achieved by correcting small errors.</li><li><strong>Flexible and Powerful:</strong> Works well for both classification and regression problems.</li><li><strong>Effective on Large Datasets:</strong> Versions like XGBoost and LightGBM are very fast on large datasets.</li></ul><p>Disadvantages</p><ul><li><strong>Risk of Overfitting:</strong> If too many trees are added, the model may memorize.</li><li><strong>High Computational Cost:</strong> Because models are trained sequentially, this takes longer to run.</li><li><strong>Sensitivity to Data Noise:</strong> Mislabeled data can cause the model to learn incorrectly.</li><li><strong>Hyperparameter Tuning Can Be Difficult:</strong> In methods like Gradient Boosting, selecting the best parameters can be time-consuming.</li></ul><p>That said, we’ve taken a deep dive into the world of boosting, from the error-driven foundations of AdaBoost to the optimization framework of Gradient Boosting, from the engineering efficiencies of XGBoost to the speed of LightGBM and the robust handling of categorical features of CatBoost. Each method builds on the core idea of ​​sequential learning and adds its own innovations to make boosting one of the most effective techniques in modern machine learning.</p><p>In the next article, we’ll continue to expand our ensemble learning journey by examining stacking and voting, two powerful techniques that combine multiple models in completely different ways. Boosting focuses on sequential optimization, stacking leverages meta-learners, and voting blends model predictions to improve stability and accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b79c39ec97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming Variance: How Bagging Builds More Reliable Machine Learning Models]]></title>
            <link>https://medium.com/@goktugdagi/taming-variance-how-bagging-builds-more-reliable-machine-learning-models-e13625b5b095?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e13625b5b095</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 15:21:31 GMT</pubDate>
            <atom:updated>2025-11-12T15:21:31.379Z</atom:updated>
            <content:encoded><![CDATA[<p>(Ensemble Learning Series — Part 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRhEtR9H3-9JH-b0hGWDwg.jpeg" /></figure><p>Imagine you’re feeling unwell and visit a doctor. They give you a diagnosis, but something doesn’t feel right. So you ask for a second opinion… then a third. Each doctor sees the problem differently — and by combining their perspectives, you reach a more reliable conclusion.<br>That’s exactly what <strong>Bagging (Bootstrap Aggregating)</strong> does. Instead of relying on one model’s biased or unstable opinion, it gathers multiple models’ predictions and merges them. The outcome? More stable, more generalizable, and more accurate results.</p><h4>Why “Ensemble” Models Exist?</h4><p>In machine learning, a single model can be wrong: It can overfit the data and fail the test, or it can be limited in capacity and miss important patterns.<br><strong>Ensemble Learning</strong> is the art of combining multiple models to reduce these weaknesses.<br>By letting many learners “vote” together, we gain a model that is more stable, more generalizable, and more accurate.</p><p>The three most common ensemble methods are:<br>- <strong>Bagging (Bootstrap Aggregating)</strong> → reduces <strong>variance<br>- Boosting</strong> → reduces <strong>bias<br>- Stacking</strong> → combines <em>different</em> model types using a meta-learner<br>In this first part of the <em>Ensemble Learning Series</em>, we’ll dive deep into <strong>Bagging</strong>, the foundation of most ensemble techniques.</p><h4><strong>What Is Bagging?</strong></h4><p>Bagging is short for Bootstrap Aggregating. Bagging trains multiple replicas of the same model type independently on different subsets of data generated by bootstrap sampling.<br>Its goal is to reduce model variance, prevent overfitting, and improve overall predictive performance.<br>It is often used in high-variance models such as decision trees. Each model is trained on a randomly selected subset of the training data, and the results are combined.</p><h4><strong>How Bagging Works (Step-by-Step)</strong></h4><p><strong>1. </strong>Bootstrap Sampling<br> — Create <em>B</em> different datasets by randomly sampling (with replacement) from the original data.<br> — Each sample has the same size as the original dataset, but some observations repeat while others are left out.<br>2. Model Training<br> — Train the <em>same</em> model type (e.g., a decision tree) on each of these bootstrapped datasets independently.<br>3. Prediction Aggregation<br> — For regression → take the <strong>average</strong> of predictions.<br> — For classification → use <strong>majority voting</strong>.</p><p>If we have <em>B</em> models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*q5l6QRe7bhp6RArxkfbPNg.png" /></figure><h4><strong>Bias–Variance Trade-off Explained</strong></h4><p>Prediction error can be decomposed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*ezzp-w9chB85NvGZR289EQ.png" /></figure><ul><li><strong>Bias</strong> → How far model predictions are from the true function (systematic error)</li><li><strong>Variance</strong> → How much predictions fluctuate with different training samples</li><li><strong>Noise</strong> → Random, irreducible uncertainty in the data.</li></ul><p><strong>Bagging’s main job:</strong> reduce <strong>variance</strong> without significantly increasing <strong>bias</strong>.</p><h4><strong>Why Variance Shrinks (Mathematical Intuition)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*so3zMTBU9D6r9hgm-ao4yQ.png" /></figure><p>As the correlation between models decreases, the decrease becomes more pronounced. (This is why training and diversifying trees with different data samples is critical.) Therefore, randomization (bootstrap samples, feature subsampling, etc.) is crucial; it helps to uncorrelate models.</p><p>Summary: Bagging creates diversity, allowing model errors to balance each other.</p><h4><strong>Bagging in Regression vs Classification</strong></h4><ul><li><strong><em>Regression:</em></strong> Averaging smooths out noisy predictions, reducing variance approximately by 1/B(better if correlation is low).</li><li><strong><em>Classification:</em></strong> Majority voting ensures that random misclassifications from individual models are overridden by the group.</li></ul><h4>From Bagging to Random Forests</h4><p>Random Forest is a natural extension of Bagging:<br>In addition to diversifying trees with bootstrap, it randomly selects a subset of features at each node. This reduces the similarity of trees (reduces correlation) and further enhances variance reduction.</p><p><strong>Short notes:</strong></p><ul><li>It is based solely on decision trees.</li><li>Suitable for classification and regression.</li><li><strong><em>Advantages:</em></strong> avoiding overfitting, diversity, ease of use, feature importance.</li><li><strong><em>Disadvantages:</em></strong> computational cost, reduced interpretability.</li></ul><h4>Extra Trees: Going One Step Further</h4><p>Extra Trees (Extremely Randomized Trees) are similar to Random Forest, but increase the randomness with two important differences:</p><ul><li>Instead of bootstrap, the tree can be trained with the entire data.</li><li>The split points are chosen completely randomly (in classical trees, they are chosen using criteria such as information gain/Gini).</li><li>Training is fast, correlation between trees becomes lower → generalization increases, overfitting tendency decreases and often speeds up training.</li></ul><h4>When to Use Bagging</h4><ul><li>Your model has high variance (Decision Trees, KNN, etc.)</li><li>The data is noisy or unstable</li><li>If your computational resources allow for parallelization, you can parallelize training</li><li>You are working with imbalanced datasets (Bagging helps by balancing resampling)</li></ul><h4>Advantages</h4><ul><li><strong>Reduces overfitting</strong> — averaging diverse models smooths extreme predictions.</li><li><strong>Increases prediction accuracy</strong> — consensus minimizes outliers.</li><li><strong>Improves generalization </strong>— more diverse data exposure per model.</li><li><strong>Handles imbalanced data</strong> — bootstrapping indirectly balances classes.</li><li><strong>Parallel-friendly</strong> — each model trains independently.</li></ul><h4>Disadvantages</h4><ul><li><strong>High computational cost</strong> — training multiple models is time-consuming.</li><li><strong>Reduced interpretability</strong> — ensemble outputs are more difficult to interpret. This is particularly detrimental to single-model performance (especially in forests).</li><li><strong>Increased storage</strong> — multiple models must be stored simultaneously.</li><li><strong>More difficult for real-time use</strong> — many results must be combined to predict.</li><li><strong>Less effective for linear or low-variance models</strong> — limited potential for improvement.</li></ul><h4>Conclusion</h4><p>Bagging (Bootstrap Aggregating) is one of the simplest yet most powerful ensemble learning techniques.<br>Its main goal is to reduce variance through diversity — all while keeping bias almost unchanged.<br>In essence, Bagging is built on one elegant idea:<br>- “Let multiple weak voices speak together.”<br>This principle later inspired more advanced methods such as Random Forests, Extra Trees, and Boosting algorithms.<br>Bagging works by lowering variance while maintaining bias, effectively reducing overall prediction error.<br>Its impact becomes especially remarkable when combined with unstable, high-variance base learners like Decision Trees.<br>Random Forests take this concept further by adding feature randomness,<br>while Extra Trees introduce completely random split points — both of which enhance diversity and strengthen generalization.<br>In the end, Bagging demonstrates that simplicity, when multiplied through diversity, can become a powerful force in machine learning.</p><h4>Coming Next: “Boosting — Turning Weak Learners into Strong Ones”</h4><p>The next article in this series explores how <strong>Boosting</strong> systematically reduces <strong>bias</strong>, turning simple learners into highly accurate prediction machines.</p><p>This article is based on my detailed handwritten notes from the BTK Academy course “Topluluk Öğrenmesi (Ensemble Learning)” — restructured and expanded for practical understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e13625b5b095" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Association Rule Learning Using Apriori Algorithm]]></title>
            <link>https://medium.com/@goktugdagi/association-rule-2c35d700901?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c35d700901</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 01:59:18 GMT</pubDate>
            <atom:updated>2023-03-23T11:09:07.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, in this article, I will explain Association Rule Learning, one of the recommendation systems, and I will use the Apriori algorithm while explaining it. Finally, I will make an application with Python. Good reading.</p><p>So what are Recommendation Systems?</p><p>They are systems in the form of recommending products or services to users using some techniques.It is used in many infrastructures and applications in many systems, from radio programs to dating applications, from e-commerce sites to social media channels.The main purpose is the possible content, product, service, etc. filtering situations.</p><p>The Recommendation System is divided into sub-headings such as Simple Recommendation System, Association Rule Learning, Content Based Filtering and Collaborative Filtering. In this article, I will explain what Association Rule Learning is.</p><h3>What is Assosiation Rule Learning?</h3><p>It is a rule-based machine learning technique used to find patterns (pattern, relationship, structure) in data.It can also be seen as a basket analysis.Product recommendations are made according to the rules learned through association analysis. It extracts the probabilities of the products that are purchased together very often and provides certain suggestions according to them.</p><h3>What is Apriori Algorithm?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_lKTK54ZiUhUifAkm_huw.png" /></figure><p>It is a basket analysis method.<br>It is used to reveal product associations.<br>There are 3 basic metrics in the Apriori Algorithm. With these 3 basic metrics, it is possible to observe the relationship patterns and structures in the data set. It is possible to evaluate these relations with a statistical criterion.<br>These 3 metrics are:<br>Support, Confidence and Lift</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*9UYM9ITV7gLLOQF-2bydpw.jpeg" /></figure><p><strong>Support(X,Y) </strong>is the probability of X and Y occurring together. That is, the frequency at which X and Y appear together divided by all operations.</p><p><strong>Confidence(X,Y)</strong> is the probability that Y will be sold when X is bought.<br>It is the frequency at which X and Y appear together divided by the frequency of X.<br>It gives information about how the probability of purchasing another product is affected as a result of a purchase in a product. So It is a linked metric.</p><p>When <strong>Lift </strong>X is purchased, the probability of purchasing Y increases as much (Lift).<br>The probability of X and Y appearing together is the Support of X alone (i.e. the probability of X appearing alone) times the Support of Y.</p><p><strong>NOTE:</strong><br>A ratio of Support value to Lift value greater than 1 indicates that the Lift statistic is a measure of dependency.<br>If the Support value between 2 products is high, it is interpreted that these 2 products are seen together with a high probability.</p><h3>How Does Apriori Algorithm Work?</h3><p>The Apriori Algorithm calculates possible product pairs according to a support threshold value to be determined at the beginning of the study and creates the final table by making eliminations according to the support value determined in each iteration.Let’s say the support threshold is 20%.In other words, we say to the algorithm, look at the various product frequencies and possibilities, and if the support value of the product you are looking at is observed less than 20%, it is not important to me, we say to eliminate this product.If there are less than 20% probabilities/supports while performing algorithm iterations, these products are eliminated.</p><p>Now let’s show these things on an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*dA8eobO-AWr1iCIxDj9tgw.png" /></figure><p>Shopping records are given in the table above. There are 5 transactions in these records and the names of the products purchased in these transactions.We set the support value here as 20%.</p><p><strong>Step 1: </strong>Support values of each product should be calculated.</p><p>If we want to calculate the support value for milk, the number of milk in the shopping record divided by the total number of transactions is done.<br>That makes 0.4 out of 2/5.The same process is done for all other products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*NbXAIOLjjcdnNiUlD0ywvg.png" /></figure><p><strong>Step 2: </strong>Elimination is done according to support.In other words, the products that are below the support value (20%) determined at the beginning are eliminated.</p><p>Juice and Cake products are eliminated because their support value is 0.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*0xYsbIXS3TlNFjPYBlFkGg.png" /></figure><p>The remaining products and their frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*thryrsmF-b3l_U1HMPLJdA.png" /></figure><p><strong>Step 3:</strong> Creating new list and support.</p><p>While creating a new list, the binary status of the remaining products is listed. The new product list is as in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*6rLU6Fb0AoBEAm37QU3eSA.png" /></figure><p>Now, the support value is calculated by looking at whether the product pairs in the newly created list are in the shopping record.For example, the number of processes that milk and egg go through togetter divided by the whole process is done.(1/5)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Blkm7GibB5lWMtFiZg3Z4A.png" /></figure><p><strong>NOTE: </strong>When creating the support value of new products, the initial purchase record is checked.</p><p><strong>Step 4:</strong> Elimination is done according to the support value and a new list is created.The product pairs below the determined support value (20%) are eliminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*MZeoDcm5s5K7sopOnI1tsQ.png" /></figure><p>The new list is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*nIpL1ZsblozB9o9XLNeuvw.png" /></figure><p><strong>Step 5: </strong>Step 5: A new list and support value are created.<br>The newly created list is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*v4sTt_4OSBZA3E_7qjpjxQ.png" /></figure><p>Now, the support value is calculated by looking at whether the products in the newly created list are in the shopping record.For example, the number of processes that milk ,tea and egg go through togetter divided by the whole process is done.(1/5)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*dPRU0noiIkGzkjfLhZGITw.png" /></figure><p><strong>Step 6:</strong> Elimination is done according to the support value and a new list is created.The products below the determined support value (20%) are eliminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*hcx5WyGhn7kJaCpOOsn8Qw.png" /></figure><p>The new list is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*T219o1nJQSgF_1J5ol348Q.png" /></figure><p><strong>Step 7:</strong> The final table is created and interpreted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*ogLPkP1_YNv3fjlQlPz13g.png" /></figure><p>Eggs and tea are observed together in 40% of all shopping. In other words, the probability of egg and tea appearing together is 40%. For example, when the products on the shelves are adjusted in a market, the fact that egg and tea products are side by side may cause these products to be sold more.</p><h3>Let’s start example of Association Rule Learning with Python</h3><p><strong>Business Problem</strong></p><p>Suggesting products to users at the basket stage.</p><p><strong>Dataset Story</strong></p><p>The data set named Online Retail 2 includes the sales of a UK-based online sales store between 01/12/2009–09/12/2011.</p><p><strong>Variables</strong></p><p><strong>InvoiceNo : </strong>Invoice Number (If this code starts with C, it means that the transaction has been cancelled.)<br><strong>StockCode :</strong> Product code<br><strong>Description :</strong> Product name<br><strong>Quantity :</strong> Number of products (Indicates how many of the products in the invoices have been sold.)<br><strong>InvoiceDate : </strong>Invoice date<br><strong>UnitPrice :</strong> Invoice price<br><strong>CustomerID : </strong>Unique customer number<br><strong>Country :</strong> Country name</p><p>The roadmap of the project is as follows:<br>1) Data Preprocessing<br>2) Preparing ARL Data Structure(Invoice-Product Matrix)<br>3) Extraction of Association Rules<br>4) Suggesting a Product to Users at the Basket Stage</p><p>Installing the necessary libraries.</p><p>First of all, the “mlxtend” library needs to be installed. For this, the installation process must be done by typing “pip install mlxtend” on the terminal screen.We are doing this setup to use the appriori and association_rules features.</p><pre># !pip install mlxtend<br>import pandas as pd<br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.width&#39;, 500)<br>from mlxtend.frequent_patterns import apriori, association_rules</pre><p><strong>Reading the Data</strong></p><p>You can download the dataset from this address.<br># <a href="https://archive.ics.uci.edu/ml/datasets/Online+Retail+II">https://archive.ics.uci.edu/ml/datasets/Online+Retail+II</a></p><p>We create a variable named df_ and put the data “online_retail_II.xlsx” in it. We create a copy of the “df_” variable so that the master data is not affected by further processing.</p><pre>df_ = pd.read_excel(&quot;online_retail_II.xlsx&quot;, sheet_name=&#39;Year 2010-2011&#39;)<br>df = df_.copy()</pre><p><strong>Data Understanding</strong></p><pre>df.head()</pre><p>Returns the first 5 observations in the dataset. If we want to reach a number of observation values other than the first 5 observations, we need to enter the value we want inside the head() function and run it. (df.head(10))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*mx6fElQMlPpcxWqMG9GEKw.png" /></figure><pre>df.describe().T</pre><p>It gives descriptive analysis of numerical variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*xFdW_eVypav9nyb0ZeKQQg.png" /></figure><p>The minimum values of the Quantity and Price variables are negative. These create a problem. In addition, the maximum values of these variables are very high, which means that they are Outlier values, we need to fix them.</p><pre>df.isnull().sum()</pre><p>It checks whether there are missing values in the variables in the data set, and if there are missing values, it gives how many in each variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*Y3CCY6eNrlewcq4vnbJOZg.png" /></figure><pre>df.shape</pre><p>Returns the size information of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/1*MMIcJ8S7esSNSfeyMMrPBQ.png" /></figure><ol><li><strong>Data Preprocessing</strong></li></ol><p>The process of removing missing observations from the data set.By saying inplace=True, the operation is performed permanently.</p><pre>df.dropna(inplace=True)</pre><p>Subtracting those starting with ‘C’ in the Invoice variable, as the operations starting with ‘C’ indicate the canceled operation.</p><pre>df = df[~df[&quot;Invoice&quot;].str.contains(&#39;C&#39;,na=False)]</pre><p>Choosing values greater than zero to solve the problem in the variables Quantity and Price.</p><pre>df = df[df[&quot;Quantity&quot;] &gt; 0]<br>df = df[df[&quot;Price&quot;] &gt; 0]</pre><p>We define a function to solve the problem of outliers. This function will suppress outliers.</p><pre>def outlier_thresholds(dataframe, variable):<br>    quartile1 = dataframe[variable].quantile(0.01)<br>    quartile3 = dataframe[variable].quantile(0.99)<br>    interquantile_range = quartile3 - quartile1<br>    up_limit = quartile3 + 1.5 * interquantile_range<br>    low_limit = quartile1 - 1.5 * interquantile_range<br>    return low_limit, up_limit<br><br>def replace_with_thresholds(dataframe, variable):<br>    low_limit, up_limit = outlier_thresholds(dataframe, variable)<br>    dataframe.loc[(dataframe[variable] &lt; low_limit), variable] = low_limit<br>    dataframe.loc[(dataframe[variable] &gt; up_limit), variable] = up_limit</pre><p>We apply the created functions to the variables Quantity and Price.</p><pre>replace_with_thresholds(df, &#39;Quantity&#39;)<br>replace_with_thresholds(df, &#39;Price&#39;)</pre><p>We take describe() to check the data.</p><pre>df.describe().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*I5AeeqiIFo5G61FEDMV_4w.png" /></figure><p>As you can see, we got rid of the negative values and outlier problems in the Price and Quantity variables.We also got rid of missing observations in the data.</p><p><strong>2. Preparing ARL Data Structure(Invoice-Product Matrix)</strong></p><p>Here we want Invoice in rows and Products in columns.We will think of the Invoices here as baskets.Products will show whether there is a product in these baskets or not.</p><p>In order not to take a long time, we will select the country of France in the data set and proceed over it.</p><pre>df_fr = df[df[&#39;Country&#39;] == &quot;France&quot;]</pre><p>According to the Invoice and StockCode variables, we received the groupby operation and we performed the “sum” operation in Quantity. The purpose of this is to see the invoice, product and how many of each product has been received.</p><pre>df_fr.groupby([&#39;Invoice&#39;, &#39;StockCode&#39;]).agg({&quot;Quantity&quot;: &quot;sum&quot;}).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*KZ5GVcp_O6q2SJiLc3moYg.png" /></figure><p>This is not exactly the output we wanted. We want to see one invoice in the rows and we want to see the products in the columns.We can use unstack() or pivot() functions for this.</p><pre>df_fr.groupby([&#39;Invoice&#39;, &#39;StockCode&#39;]).agg({&quot;Quantity&quot;: &quot;sum&quot;}).unstack().iloc[0:5,0:5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Ay-X2SNLElhtQPRpqZbW1A.png" /></figure><p>The output obtained as a result of the transaction became singular according to InvoceID. StockCode came in the columns. In the row and column intersections, the empty places were “NAN”, if there was a purchase, their totals were displayed. But here is something we don’t want. We want 0 to come to the empty places, namely “NAN”, and we want to get 1 to the filled places.</p><p>Filling “NAN” with zeros.</p><pre>df_fr.groupby([&quot;Invoice&quot;,&quot;StockCode&quot;]).agg({&quot;Quantity&quot;: &quot;sum&quot;}).unstack().fillna(0).iloc[0:5,0:5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*vjhdCamcps66hFsYdcJqPw.png" /></figure><p>The next operation is a fetch operation to the filled places.</p><pre>df_fr.groupby([&quot;Invoice&quot;, &quot;StockCode&quot;]).agg({&quot;Quantity&quot;:&quot;sum&quot;}).unstack().fillna(0).applymap(lambda x: 1 if x &gt; 0 else 0 ).iloc[0:5,0:5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*kL_iLDbBsOX-acBx_WzkEw.png" /></figure><p><strong>NOTE:</strong><br>Applymap() işlevi, veri kümesindeki tüm gözlemler arasında gezinmemizi sağlar.</p><p>Let’s throw the above operations into a dataframe.</p><pre>fr_inv_pro_df = df_fr.groupby([&quot;Invoice&quot;, &quot;StockCode&quot;]).agg({&quot;Quantity&quot;:&quot;sum&quot;}).unstack().fillna(0).applymap(lambda x: 1 if x &gt; 0 else 0 )</pre><p>Let’s look at the first 5 observations of the newly created dataframe.</p><pre>fr_inv_pro_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*f-oyrTlVgZPwa5Iwi0EQew.png" /></figure><p>Girilen StockCode’un adına ulaşmak için bir fonksiyon yazalım.</p><pre>def check_id(dataframe, stock_code):<br>    product_name = dataframe[dataframe[&quot;StockCode&quot;] == stock_code][[&quot;Description&quot;]].values[0].tolist()<br>    print(product_name)</pre><p>Let’s say we want to access the name of the product with the stock code 10002 in df_fr.</p><pre>check_id(df_fr, 10002)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*FWfc4H3dIJZ8TqjFy-LVFQ.png" /></figure><p><strong>3. Extraction of Association Rules</strong></p><p>Our aim is to find the “Support” values, ie probabilities, of all possible product associations with the Apriori Algorithm method.</p><pre>frequent_itemset = apriori(fr_inv_pro_df, min_support=0.01, use_colnames=True)</pre><p>We defined a variable named frequent_itemset and used the apriori() function. Using this function, the probabilities of possible pairs of items are found.<br>min_support : Minimum Support Threshold Value<br>use_colnames : If we want to use the names of the variables in the used dataset, we need to set it to “True”.</p><p>Sorting the created “frequent_itemset” variable from largest to smallest according to the support value.</p><pre>frequent_itemset.sort_values(&quot;support&quot;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*mDeA5NvqZDAfMX8WY9Gi8A.png" /></figure><p>Now let’s deduce the association rules.</p><pre>rules = association_rules(frequent_itemsets,<br>                          metric=&quot;support&quot;,<br>                          min_threshold=0.01)</pre><p>Let’s look at the general view of the table that consists of saying “rules”.</p><pre>rules</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfuloIlOdQ77ofgmG2MOqg.png" /></figure><p><strong>antecedents :</strong> means previous product<br><strong>consequents :</strong> means second product<br><strong>anteceden support :</strong> The probability of observing the first product alone<br><strong>consequent support :</strong> The probability of the second product being observed alone<br><strong>support :</strong> The probability of observing the first and second product together<br><strong>confidence :</strong> The probability of getting product Y when product X is bought<br><strong>lift : </strong>When product X is purchased, the probability of purchasing product Y increases as much as lift.<br><strong>leverage :</strong> It means leverage. This value is similar to “lift”, but “leverage” tends to give priority to values with higher “support”. That’s why it has bias.</p><p><strong>conviction : </strong>The expected value of product X without product Y is its frequency. The reverse is also true.</p><p><strong>4. Suggesting a Product to Users at the Basket Stage</strong></p><p>For example, let’s say a user adds a product with a product id of 22492 to its cart.</p><pre>product_id = 22492<br>check_id(df, product_id)</pre><p>Let’s see what the product with the product id is 22492.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*G8vRBBb7YV81Diz-8pYvYQ.png" /></figure><p>We sorted the “rules” variable according to the “lift” from largest to smallest and looked at the top 5 observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wj_48LLasDLJA-5RzXQmIw.png" /></figure><p>We will navigate in the “antecedents” variable in this table, and we will catch the products we have caught here in the “consequents” variable in the same index. We will have recommended this product that we caught.</p><pre>recommendation_list = []<br>for i, product in enumerate(sorted_rules[&quot;antecedents&quot;]):<br>    for j in list(product):<br>        if j == product_id:<br>            recommendation_list.append(list(sorted_rules.iloc[i][&quot;consequents&quot;])[0])</pre><p>Requesting 1 product recommendation according to the product added to the cart.</p><pre>check_id(df_fr,recommendation_list[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*OksmtCeGEFXqCepkPwipmA.png" /></figure><p>Requesting 2 product recommendation according to the product added to the cart.</p><pre>recommendation_list[0:2]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*fSrv3GxcdsvYx2Bq7qXYow.png" /></figure><p>In summary, in this article, I tried to explain what the Association Rule Learning are, what they do, and I made an application with Python. I hope it was useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c35d700901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Do It Without A/B Testing]]></title>
            <link>https://medium.com/@goktugdagi/dont-do-it-without-a-b-testing-7602eac0b1aa?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7602eac0b1aa</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 06:55:14 GMT</pubDate>
            <atom:updated>2022-12-06T06:55:14.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2RolI2ZvuwwCQN2UyHTKQ.png" /></figure><p>Hello everyone, today in this article I will explain what A/B Testing, one of the Hypothesis Tests, is, why it should be done and where it is used, and then I will make a small application with Python.</p><h4>What is Hypothesis ?</h4><p>Statistical methods used to test a belief or an argument. In this article, we will focus on Group Comparisons. So what are Group Comparisons? The main purpose is to try to show whether possible differences arose by chance.</p><p>For example, has the average daily time spent by users in the application increased after the interface change in the mobile application? A hypothesis is established that there is no difference between the average time spent by the users in the application before the interface change, that is, in group A and after the interface change, that is, in group B. This is then tested. Let’s say the time spent in A Group is 55 minutes and the time spent in Group B is 58 minutes. Here, it cannot be stated that group B increased the time spent in application. This is because processing was done on a sample, and this may have happened by chance. It is necessary to show statistically whether the difference here occurred by chance. We use AB Testing for this.</p><h4>What is A/B Testing ?</h4><ul><li>It is one of the most used methods in the field of Data Science.</li><li>When AB Testing is mentioned, the average of the two groups is compared or the ratios of the two groups are compared.</li><li>AB(Independent 2-Sample T-Test) Testing is used when it is desired to make a comparison between the averages of two groups.</li><li>Statements A and B represent the control group and the experimental group.</li></ul><h4>A/B Testing Applications</h4><p>A/B Testing is generally used to test the innovations made in mobile or web applications or the features that are desired to be tested, or it is used in scenarios such as testing whether there is a difference in revenues as a result of some machine learning algorithms developed.</p><h4>Hypothesis of A/B Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*OOpv3TNdQw6Wjh3MALrv-g.png" /></figure><p>H0 is the null hypothesis. The situation we will test is the H0 hypothesis. That is, there is no difference between the two groups. In other words, the mean of the two groups is equal. The H0 hypothesis is tested and we evaluate whether there is a statistical difference between the two groups according to whether or not to reject the H0 hypothesis.</p><p>There are some test statistics to compare the two groups, but we will not use them, we will only examine them for general information. These test statistics are:</p><p>If the sample numbers are the same and the variances are homogeneous:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*u4otkK2sfbBx_I_3hAg69w.png" /></figure><p>If the number of samples is different and the variances are homogeneous:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*i1VSS7QkD1X80nYncMDDAg.png" /></figure><p>If the sample numbers are different and the variances are not homogeneous:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*zM56pVxE2CkYzmft_gL1VQ.png" /></figure><p>Instead of using the formulas shown above, operations are performed on the value of “<strong>p-value</strong>(p&lt;0.05)”. If the “p-value” is less than 0.05, it is concluded that the corresponding H0 hypothesis is “<strong>rejected</strong>”.</p><h4>Assumptions of A/B Testing</h4><ul><li>Normality Assumption</li><li>Variance Homogeneity Assumption</li></ul><p>For the Normality Assumption, the two groups must be “<strong>normally distributed</strong>” separately.</p><p>For the Variance Homogeneity Assumption, it is the condition of whether the distributions of the two groups are similar to each other.</p><h4>Steps to A/B Testing</h4><ol><li>Set up Hypotheses(At the beginning of the study, relevant hypotheses should be established for what is to be tested.)</li><li>Assumption Control</li></ol><ul><li>Normality Assumption</li><li>Variance Homogeneity Assumption</li></ul><p>3. Application of Hypotheses</p><ul><li>If the assumptions are met, Independent 2-Sample T-Test is performed. (Parametric test)(t-test)</li><li>If the assumptions do not provide, the “Mannwhitneyu” Test is performed. (Non-Parametric test)(mannwithneyu test)</li></ul><p>4. Results are interpreted according to the “p-value” value.</p><p><strong>NOTE: </strong>If the Normality Assumption is not met, the 2nd Hypothesis (Non-Parametric Test) is used. If the Variance Homogeneity Assumption is not met, the 1st Hypothesis (Parametric Test) is used.</p><p><strong>NOTE: </strong>Before examining the Assumption of Normality, it may be helpful to perform outlier analysis and correction.</p><h4>Let’s start example of A/B Testing with Python</h4><p><strong>Business Problem</strong></p><p>A company recently introduced what’s called “maximum bidding”. Introduced a new type of bidding, “average bidding,” as an alternative to the bidding type. One of their customers has decided to test this new feature and wants to do an A/B Test to see if average bidding converts more than maximum bidding.</p><p><strong>Dataset Story</strong></p><p>In this data set, which includes the website information of a company, there is information such as the number of advertisements that users see and click, as well as earnings information from here. There are two separate data sets, the control and test groups. “Maximum Bidding” was applied to the control group and “Average Bidding” was applied to the test group.</p><p><strong>Variables</strong></p><pre>Impression: Number of Advertise Views<br>Click: Clicks on Displayed Advertise<br>Purchase: Number of Products Purchased After Advertises Clicked<br>Earning: Earnings After Purchased Products</pre><p>Installing the necessary libraries.</p><p>First of all, the “statsmodels” library needs to be installed. For this, the installation process must be done by typing “pip install statsmodels” on the terminal screen.</p><pre>import itertools<br>import pandas as pd<br>import matplotlib.pyplot as plt<br># !pip install statsmodels<br>import statsmodels.stats.api as sms<br>from scipy.stats import ttest_1samp, shapiro, levene, ttest_ind, mannwhitneyu, pearsonr, spearmanr, kendalltau, f_oneway, kruskal<br>from statsmodels.stats.proportion import proportions_ztest<br><br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&quot;display.width&quot;, 500)<br>pd.set_option(&#39;display.max_rows&#39;, 10)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.5f&#39; % x)</pre><p><strong>Reading the Data</strong></p><p>We create two variables called control_df and test_df and we assign the control and test group data in the “data.xlsx” data into these variables.</p><pre>control_df = pd.read_excel(&quot;ab_testing.xlsx&quot;, sheet_name=&quot;Control Group&quot;)<br>test_df = pd.read_excel(&quot;ab_testing.xlsx&quot;, sheet_name=&quot;Test Group&quot;)</pre><p><strong>Data Understanding</strong></p><pre>print(&quot;control_df shape :&quot;, control_df.shape)<br>print(&quot;test_df shape :&quot;, test_df.shape)</pre><p>Returns the size information of the data sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*-SYhdRtw2aWTi26bNI8ZfQ.png" /></figure><pre>control_df.info()<br>test_df.info()</pre><p>It gives information about the variables in the data sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*9bthV17rcIoVzuqxR2eimg.png" /></figure><pre>control_df.describe().T<br>test_df.describe().T</pre><p>It gives descriptive analysis of numerical variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*HwFXvq81eaMMq3KzbzFhdA.png" /></figure><p><strong>Data Preparation</strong></p><p>Let’s start with the establishment of hypotheses first.</p><h4>Set up Hypotheses</h4><pre># H0 : M1 == M2 (There is no statistically significant difference between the average of &quot;Average Bidding&quot; and &quot;Maximum Bidding&quot;.)</pre><pre># H1 : M1 != M2 (There is a statistically significant difference between the average of &quot;Average Bidding&quot; and &quot;Maximum Bidding&quot;.)</pre><p>Let’s analyze the “purchase” averages for the control and test group.</p><pre>control_df.groupby(&quot;Purchase&quot;).agg({&quot;Earning&quot;: &quot;mean&quot;}).head()<br>test_df.groupby(&quot;Purchase&quot;).agg({&quot;Earning&quot;: &quot;mean&quot;}).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*wGoBYveid65sT-spaDFR7Q.png" /></figure><h4>Performing Hypothesis Testing</h4><p>Let’s start by doing the Assumption tests first. These were the Normality Assumption and the Variance Homogeneity Assumption.</p><p>Normality Assumption:<br> H0: Normal Distribution assumption is provided.<br> H1: Normal Distribution assumption is not provided.</p><p># p &lt; 0.05 H0 REJECTED , p &gt; 0.05 H0 CANNOT BE REJECTED</p><p>It uses the “shapiro()” test in “scipy.stats” to make the Normality Assumption. This test needs to be applied separately in two separate data sets.</p><pre>control_stat, control_pvalue = shapiro(control_df[&quot;Purchase&quot;])<br>print(&quot;Control Stat = %.5f, Control p-value = %.5f&quot; % (control_stat, control_pvalue))<br><br>test_stat, test_pvalue = shapiro(test_df[&quot;Purchase&quot;])<br>print(&quot;Test Stat = %.5f, Test p-value = %.5f&quot; % (test_stat, test_pvalue))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*i2XA0OLVNuBiak-2dEuibw.png" /></figure><p>Extracted Comment:<br># “H0 CANNOT BE REJECTED” because the p-values of both the Control and Test group are greater than 0.05.<br># H0: Normal Distribution Assumption is provided.</p><p>Variance Homogeneity:<br> H0: Variances are homogeneous.<br> H1: Variances are not homogeneous.</p><p>p &lt; 0.05 H0 REJECTED , p &gt; 0.05 H0 CANNOT BE REJECTED</p><p>It uses the “levene()” test in “scipy.stats” to make the Variance Homogeneity Assumption.</p><pre>stat, pvalue = levene(control_df[&quot;Purchase&quot;],<br>                      test_df[&quot;Purchase&quot;])<br>print(&quot;Stat = %.5f, p-value = %.5f&quot; % (stat, pvalue))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*ejFPTLpa4Zq9NqiNH2BGaQ.png" /></figure><p>Extracted Comment:<br># H0 CANNOT BE REJECTED because p value is greater than 0.05. So Variances are Homogeneous.</p><h4>Application of Hypotheses</h4><p>Parametric Test (ttest_ind()) is performed because Normality Assumption and Variance Homogeneity Assumptions are provided.</p><h4>NOTE:</h4><ol><li>To use the hypothesis test, the ttest_ind() method is used.</li><li>It is a parametric test.</li><li>You can use the ttest_ind() method if the Assumption of Normality is met.</li><li>You can use the ttest_ind() method if the Normality Assumption and Variance Homogeneity Assumption are met.</li><li>You can use the ttest_ind() method if the Assumption of Normality is met but the Assumption of Variance Homogeneity is not met, but the variable “equal_var” must be set to “False”.</li></ol><pre>hypothesis_stat, hypothesis_pvalue =  ttest_ind(control_df[&quot;Purchase&quot;],<br>          test_df[&quot;Purchase&quot;],<br>          equal_var=True)<br>print(&quot;Hypothesis Stat = %.4f, Hypothesis_pvalue = %.4f&quot; % (hypothesis_stat, hypothesis_pvalue))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*CRJlkfAfeHxoLlEDlXXbQg.png" /></figure><p>Extracted Comment:<br># H0 CANNOT BE REJECTED because p value is greater than 0.05.<br># In other words, there is no statistically significant difference between the “average bidding” and the “maximum bidding” average.</p><p>Let’s advise the customer according to the test results obtained.</p><p>It has been observed that “average bidding” has no statistically significant difference compared to “maximum bidding”. So there is no difference between the old product and the new product. You can continue with the old system.</p><p>Let’s assume that the Normality Assumption is not met and let’s see how it turns out.</p><p>Since the Assumption of Normality is not provided, the non-parametric test “mannwithneyu()” in “scipy.stats” is used.</p><pre>hypothesis_stat, hypothesis_pvalue =          mannwhitneyu(control_df[&quot;Purchase&quot;],<br>             test_df[&quot;Purchase&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*vGhn1j1kCph3TqvgcRQ63w.png" /></figure><p>Extracted Comment:<br># H0 CANNOT BE REJECTED because p value is greater than 0.05.<br># In other words, there is no statistically significant difference between the “average bidding” and the “maximum bidding” average.</p><p>In summary, in this article, I explained what A/B Testing, which is one of the Hypothesis Tests, is, why it should be done and where it is used, and then I made a small application with Python. I hope it was useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7602eac0b1aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Life Time Value Prediction by Using BG-NBD and Gamma-Gamma Submodels and Applied Example…]]></title>
            <link>https://medium.com/@goktugdagi/customer-life-time-value-prediction-by-using-bg-nbd-and-gamma-gamma-submodels-and-applied-example-2951beef5224?source=rss-9f7135ed6ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2951beef5224</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[customer-lifetime-value]]></category>
            <dc:creator><![CDATA[Goktugdagi]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 06:27:57 GMT</pubDate>
            <atom:updated>2022-11-22T06:27:57.102Z</atom:updated>
            <content:encoded><![CDATA[<h3>Customer Life Time Value Prediction by Using BG-NBD and Gamma-Gamma Submodels and Applied Example in Python</h3><p>Hello everyone, in this article I will explain what BG-NBD Model and Gamma Gamma Submodel are and we will learn how to calculate Customer Lifetime Value Prediction using these statistical models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYVqXIKukdjF1SdT0PV8_g.jpeg" /></figure><p><strong>What is Customer Lifetime Value Prediction ?</strong></p><p>It is a probabilistic estimate of lifetime value with time projection. In other words, it allows us to make data-based predictions about the future.</p><p>It is desired to model the number of transactions and purchasing behaviors of the whole audience with a probability distribution. Then, it is aimed to estimate the expected number of transactions and expected average profit for each person by using the behavior patterns modeled with this probability distribution in a conditional way, that is, shaping them individually.</p><p><strong>Formula of Customer Lifetime Value Prediction</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GfSMU0sTahM5wBQvHT9fQ.png" /></figure><p><strong>What can we do using BG-NBD Model and Gamma Gamma Submodel?</strong></p><ol><li>Forecasting which customers will purchase in the next period.</li><li>Forecast of the customer with the most purchases in the coming period.</li><li>Forecast of the most profitable customer for the next period.</li></ol><p>The BG-NBD Model models the distribution of each customer’s “<strong><em>purchasing behavior</em></strong>” and predicts the expected number of transactions for each customer.</p><p>The Gamma-Gamma Submodel models the expected average profit distribution and predicts the expected “<strong><em>average profit</em></strong>” for each customer.</p><h4>What is BG-NBD Model ?</h4><p>Beta Geometric / Negative Binomial Distribution known as BG-NBD Model. Also known as “Buy Till You Die”. It gives conditionally expected number of transactions in the next time period. This model can answer the following questions:</p><ul><li>How many transactions will be next week ?</li><li>How many transactions will be in the next 6 months ?</li><li>Which customers will do the most purchases in the next 1 month ?</li></ul><p>The BG-NBD Model models the Expected Number of Transaction process as 2 probabilistic models. These :</p><ol><li>Transaction Process (Buy)</li><li>Dropout Process (Till You Die)</li></ol><p><strong>Transaction Process (Buy)</strong></p><ol><li>It is used for the purchasing process.</li><li>As long as the customer is alive, the number of transactions to be performed by a customer in a certain period of time is distributed with the transaction rate parameter “<strong>poison</strong>”.</li><li>As long as the customer is alive, it continues to make random purchases around its transaction rate.</li><li>Transaction rates vary according to each customer and are distributed with “<strong>gamma distribution</strong>” for the whole mass.(r,α)</li></ol><p><strong>NOTE:</strong> Inferences and probabilistic estimations can be made over a population whose distribution is known. If the general distribution of the audience is known, it can be estimated how many purchases that individual can make when it is reduced to the specifics of an individual by conditioning it.</p><p><strong>Dropout Process (Till You Die)</strong></p><ul><li>It means dropping purchasing.</li><li>Each customers has a dropout rate with probability “<strong>p</strong>”.</li><li>A customer drops with a certain probability after making a purchase.</li><li>Dropout rates vary for each client and are distributed with a “<strong>beta distribution</strong>” for the entire mass.(a,b)</li></ul><p><strong>BG-NBD Formula</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmYF0cY8usnbDq5Cgr5OWA.png" /></figure><p>I’ll explain the parameters left side of equality.</p><ul><li>E refers to the expected value</li><li>Y(t) refers to the expected number of transactions for each customer.</li><li>| refers to that this probability is conditional</li><li>x refers to frequency for each customer who purchased at least 2 times.</li><li>tx represents the Recency value. It refers to the difference between a customer’s last purchase and their first purchase, and is considered weekly.</li><li>T is the time since the customer’s first purchase. That is, it refers to the age of the customer. It can also be thought of as “Tenure”. It is considered weekly.</li><li>r,α comes from the gamma distribution (Buy Process). <strong>Transaction rate of the mass.</strong></li><li>a,b comes from the beta distribution (Till You Die Process). <strong>The dropout rate of the mass.</strong></li></ul><p><strong>NOTE:</strong> It gives the BG-NBD Model Purchase Frequency(Expected Number of Transaction).</p><h4>What is Gamma Gamma Submodel ?</h4><p>It is used to estimate how much profit each customer can generate on average per transaction. It gives us the expected average profit for each customer after modelling the average profit for the mass.</p><ol><li>The monetary value of a customer’s transactions is randomly distributed around the average of the transaction values.</li><li>The average transaction value may change between users over time, but not for a single user.</li><li>The average transaction value is distributed among all customers with a “<strong>gamma distribution</strong>”.</li></ol><p><strong>Gamma Gamma Submodel Formula</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERgwQVrKQDl34Oq0STzTSA.png" /></figure><ul><li>E refers to the expected value</li><li>M refers to the expected value of transactions (expected average profit)</li><li>x refers to the frequency for each customer. That is the number of repeat sales. It refers to the state of having made a transaction at least 2 times.</li><li>mx refers to the monetary for each customer. That is, the observed transaction values. (Total Price / Total Transaction)</li><li>p,q,γ comes from parameters of the gamma distribution.</li></ul><h3>Let’s start example of CLTV Prediction with Python</h3><p><strong>Business Problem</strong></p><p>Roadmap for marketing activities of an e-commerce company<br>wants to determine. It wants to estimate the potential value that existing customers will provide to the company in the future so that the company can make a medium-long-term plan.</p><p><strong>Dataset Story</strong></p><p>The dataset consists of the information obtained from the past shopping behaviors of customers who made their purchases from the e-commerce company as OmniChannel (both online and offline shopping) in the years 2020–2021.</p><p><strong>Variables</strong></p><p><strong>master_id:</strong> Unique client number<br><strong>order_channel:</strong> Which channel of the shopping platform is used (Android, ios, Desktop, Mobile)<br><strong>last_order_channel: </strong>The channel where the last purchase was made<br><strong>first_order_date:</strong> The date of the first purchase made by the customer<br><strong>last_order_date:</strong> The date of the customer’s last purchase<br><strong>last_order_date_online:</strong> The date of the last purchase made by the customer on the online platform<br><strong>last_order_date_offline:</strong> The date of the last purchase made by the customer on the offline platform<br><strong>order_num_total_ever_online:</strong> The total number of purchases made by the customer on the online platform<br><strong>order_num_total_ever_offline:</strong> Total number of purchases made by the customer offline<br><strong>customer_value_total_ever_offline:</strong> The total price paid by the customer for offline purchases<br><strong>customer_value_total_ever_online:</strong> The total price paid by the customer for their online shopping<br><strong>interested_in_categories_12:</strong> List of categories the customer has purchased from in the last 12 months</p><p>Installing the necessary libraries.</p><p>First of all, the “lifetimes” library needs to be installed. For this, the installation process must be done by typing “pip install lifetimes” on the terminal screen.We are doing this setup to use the BetaGeoFitter and GammaGammaFitter features.</p><pre>#pip install lifetimes<br>import pandas as pd<br>import datetime as dt<br>import matplotlib.pyplot as plt<br>from lifetimes import BetaGeoFitter<br>from lifetimes import GammaGammaFitter<br>from lifetimes.plotting import plot_period_transactions<br>from sklearn.preprocessing import MinMaxScaler<br>pd.set_option(&quot;display.max_columns&quot;, None)<br>pd.set_option(&quot;display.width&quot;, 500)<br>pd.set_option(&quot;display.float_format&quot;, lambda x: &quot;% .4f&quot; % x)</pre><p><strong>Reading the Data</strong></p><p>We create a variable named data and put the data “data.csv” in it. We create a copy of the “data” variable so that the master data is not affected by further processing.</p><pre>data= pd.read_csv(&quot;data.csv&quot;)<br>df = data.copy()</pre><p><strong>Data Understanding</strong></p><pre>df.shape</pre><p>Returns the size information of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*VtPixljOKuhonpbmQXf_jA.png" /></figure><pre>df.head()</pre><p>Returns the first 5 observations in the dataset. If we want to reach a number of observation values other than the first 5 observations, we need to enter the value we want inside the head() function and run it. (df.head(10))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*1B32sVLbeHe0jT_dmaTyBQ.png" /></figure><pre>df.tail()</pre><p>Returns the last 5 observations in the dataset. If we want to reach a number of observation values other than the last 5 observations, we need to enter the value we want inside the tail() function and run it. (df.tail(10))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*aj4QlUYMIIMhfqGJ9pz-Yw.png" /></figure><pre>df.info()</pre><p>It gives information about the variables in the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*baSlCOoYCPlxyOh0KcQbmA.png" /></figure><pre>df.describe().T</pre><p>It gives descriptive analysis of numerical variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*78Q2ECvO3y118a_T7BxfVg.png" /></figure><p><strong>Data Preparation</strong></p><p>Let’s write a function to suppress outliers in the dataset.</p><pre>def outlier_thresholds(dataframe, variable):<br>    quartile1 = dataframe[variable].quantile(0.01)<br>    quartile3 = dataframe[variable].quantile(0.99)<br>    interquantile_range = quartile3 - quartile1<br>    low_limit = quartile1 - 1.5 * interquantile_range<br>    up_limit = quartile3 + 1.5 * interquantile_range<br>    return low_limit, up_limit<br><br>def replace_with_thresholds(dataframe, variable):<br>    low_limit, up_limit = outlier_thresholds(dataframe, variable)<br>    dataframe.loc[(dataframe[variable] &lt; low_limit), variable] = round(low_limit, 0)<br>    dataframe.loc[(dataframe[variable] &gt; up_limit), variable] = round(up_limit, 0)</pre><p>Let’s suppress any outliers in the variables “order_num_total_ever_online”, “order_num_total_ever_offline”, “customer_value_total_ever_offline”, “customer_value_total_ever_online”.</p><pre>replace_with_thresholds(df, &quot;order_num_total_ever_online&quot;)<br>replace_with_thresholds(df,&quot;order_num_total_ever_offline&quot;)<br>replace_with_thresholds(df, &quot;customer_value_total_ever_offline&quot;)<br>replace_with_thresholds(df, &quot;customer_value_total_ever_online&quot;)<br>df.describe().T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*7QUYAGV-2E8HEWg9jEbOOQ.png" /></figure><p>The mean, std and max values of the suppressed variables changed.</p><p>Omnichannel means that customers shop from both online and offline platforms. New variables were created for the total number of purchases and spending of each customer.</p><pre>df[&quot;omnichannel_total_order&quot;] = (df[&quot;order_num_total_ever_online&quot;] + df[&quot;order_num_total_ever_offline&quot;]).astype(&quot;int64&quot;)<br>df[&quot;omnichannel_total_value&quot;] = (df[&quot;customer_value_total_ever_online&quot;] + df[&quot;customer_value_total_ever_offline&quot;]).astype(&quot;int64&quot;)<br></pre><p>Converted the type of variables that express “date” to date.</p><pre>date = [date for date in df.columns if &quot;date&quot; in date]<br>df[date] = df[date].astype(&#39;datetime64[ns]&#39;)<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*65mFFOxujXNN3UWN-Rx9GQ.png" /></figure><p><strong>Creating the CLTV Data Structure</strong></p><p>We need the analysis date to calculate the recency and T values. Since the data set is old, we add 2 days to the last shopping date and accept it as the analysis date.</p><pre>today_date = df[&quot;last_order_date&quot;].max() + dt.timedelta(2)</pre><p>We are creating a new cltv dataframe with customer_id, recency_cltv_weekly, T_weekly, frequency and monetary_cltv_avg values.</p><pre># Create cltv DataFrame<br>cltv = pd.DataFrame()<br><br>cltv[&quot;customer_id&quot;] = df[&quot;master_id&quot;]</pre><pre>cltv[&quot;recency_cltv_weekly&quot;] = (df[&quot;last_order_date&quot;] -df[&quot;first_order_date&quot;]).dt.days</pre><pre>cltv[&quot;T_weekly&quot;] = (today_date - df[&quot;first_order_date&quot;]).dt.days<br>df[&quot;omnichannel_total_order&quot;].min()</pre><pre>cltv[&quot;frequency&quot;] = df[&quot;omnichannel_total_order&quot;]</pre><pre>cltv = cltv[cltv[&quot;frequency&quot;] &gt; 1]</pre><pre>cltv[&quot;monetary_cltv_avg&quot;] = df[&quot;omnichannel_total_value&quot;] / cltv[&quot;frequency&quot;]</pre><pre># We convert the variable recency_cltv_weekly to weekly.<br>cltv[&quot;recency_cltv_weekly&quot;] = cltv[&quot;recency_cltv_weekly&quot;] / 7</pre><pre># We convert the variable T_weekly to weekly.<br>cltv[&quot;T_weekly&quot;] = cltv[&quot;T_weekly&quot;] / 7 </pre><p><strong>NOTE:</strong> We need to convert recency_cltv_weekly, T_weekly variables to day type and then we need to express them weekly.</p><p><strong>Establishment of BG-NBD Model</strong></p><p>I’ll use BetaGeoFitter from lifetimes package. I’ll create an instance and will fit it by using frequency, recency and T values.</p><p>The fit() function is used to fit the BG_NBD Model. We need to give “frequency”, “recency” and “T” variables as arguments to fit() function.</p><pre>bgf = BetaGeoFitter(penalizer_coef=0.001)<br>bgf.fit(cltv[&quot;frequency&quot;],<br>        cltv[&quot;recency_cltv_weekly&quot;],<br>        cltv[&quot;T_weekly&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*z0iNYqZYX10JT7Hn7Ne02g.png" /></figure><p>BG-NBD Model was established above. Now let’s estimate the expected purchases from customers in 3 and 6 months and add exp_sales_3_month and exp_sales_6_month to the cltv dataframe.</p><p>The predict() function takes the “time”, “frequency”, “recency”, and “T” arguments.</p><pre>cltv[&quot;exp_sales_3_month&quot;] = bgf.predict(12, # week<br>                                        cltv[&quot;frequency&quot;],<br>                                        cltv[&quot;recency_cltv_weekly&quot;],<br>                                        cltv[&quot;T_weekly&quot;])</pre><pre>cltv[&quot;exp_sales_6_month&quot;] = bgf.predict(24, # week<br>                                        cltv[&quot;frequency&quot;],<br>                                        cltv[&quot;recency_cltv_weekly&quot;],<br>                                        cltv[&quot;T_weekly&quot;])<br>cltv.head()</pre><p><strong>NOTE: </strong>The predict() function accepts the desired time as weekly. For example, if we want to make a 3-month observation, we need to write 12 in the “time” argument. Since 1 month consists of 4 weeks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJYDDj8H9t9YdMYBGKc-7A.png" /></figure><p><strong>Establishment of Gamma Gamma Submodel</strong></p><pre>ggf = GammaGammaFitter(penalizer_coef=0.01)<br>ggf.fit(cltv[&quot;frequency&quot;],<br>        cltv[&quot;monetary_cltv_avg&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*JL3iJ9MZf-cijwz8W9yK2g.png" /></figure><p>Gamma Gamma Submodel fit() function is used to fit. We need to give “frequency” and “monetary” variables as arguments to fit() function.</p><p>Gamma Gamma Submodel was established above. Let’s estimate the average value of the customers and add it to the cltv dataframe as exp_average_value.</p><pre>cltv[&quot;exp_average_value&quot;] = ggf.conditional_expected_average_profit(cltv[&quot;frequency&quot;],<br>                                                                    cltv[&quot;monetary_cltv_avg&quot;])<br>cltv.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBeSXdYTpyitiTfJXVpMJQ.png" /></figure><p><strong>Predicting CLTV by Using BG-NBD Model and Gamma-Gamma Submodels</strong></p><p>The customer_life_value() function is used to calculate CLTV Prediction. The arguments of this function are “transaction prediction model”, “frequency”, “recency”, “T”, “monetary”, “time”, “freq”, “discount_rate”. The thing to note here is that the “time” argument is taken as “monthly” here. The “discount_rate” argument is the argument where the discount rate is entered, taking into account the possibility of discounting the product in the future.</p><p>Let’s calculate 6 months CLTV and add it to the DataFrame with the name cltv. Then, sorting was done according to the “cltv” variable, from largest to smallest.</p><pre>cltv[&quot;cltv&quot;] = ggf.customer_lifetime_value(bgf,<br>cltv[&quot;frequency&quot;],                                               cltv[&quot;recency_cltv_weekly&quot;],<br>cltv[&quot;T_weekly&quot;],                                           cltv[&quot;monetary_cltv_avg&quot;],<br>time=6, # month<br>freq=&quot;W&quot;,<br>discount_rate=0.01)</pre><pre>cltv.sort_values(by=&quot;cltv&quot;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkoVuBvsroirpvtPMnUhKg.png" /></figure><p><strong>Creating Segments by CLTV Value</strong></p><p>Let’s segment according to the 6-month cltv variable. It is then segmented using the qcut() function. It is divided into 4 segments.</p><pre>cltv[&quot;segment&quot;] = pd.qcut(cltv[&quot;cltv&quot;], q=4, labels=[&quot;D&quot;, &quot;C&quot;, &quot;B&quot;, &quot;A&quot;])<br>cltv.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6y0-JrWD9T2AX8QXwELag.png" /></figure><p>The interpretation to be drawn from this can predict how much profit the segmented customers will bring in the next 6 months, and a roadmap can be drawn to develop strategies specific to customers.</p><p>In summary, in this article, I tried to explain what the BG-NBD Model and the Gamma-Gamma Sub-Model are, what they do, and I made an application with Python. I hope it was useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2951beef5224" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>