Docsity

Generative Multinomial Models: A Comprehensive Guide - Prof. Cumani, Appunti di Machine learning

Toggle sidebar
bg1
Generative Multinomial Models: A Detailed
Introduction
Author
Marc'Antonio Lopez
AI & Data Analytics student at Polytechnic University of Turin
Introduction to Generative Multinomial Models
This overview delves into generative models, specifically focusing on those designed for
multinomial distributions. Generative models function by learning the intrinsic process that
generates the data. In the context of classification, this typically involves modeling the probability of
observing certain features given a specific class ( ).
The multinomial distribution is central to these models, generalizing Bernoulli and binomial
distributions to outcomes falling into multiple discrete categories. Consequently, generative
multinomial models are foundational for handling discrete features—variables that can take values
from a finite set of categories (e.g., 'red', 'green', 'blue') or represent counts (e.g., the number of times
a specific word appears in a document).
Discrete Features and Categorical Variables
Working with Single Categorical Features
Generative multinomial models are particularly well-suited for classification tasks where the input
consists of a single categorical feature. If this feature
x can take
m distinct values (i.e.,
), these models provide a direct way to estimate the probabilities of each feature value
given a class.
Example: Predicting Cat Gender Based on Fur Color
Let's illustrate with an example: predicting a cat's gender (our class) based on its fur color (our single
categorical feature). Possible fur color categories might include:
P(features ∣ class)
x∈
{1, 2, … , m}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Anteprima parziale del testo

Scarica Generative Multinomial Models: A Comprehensive Guide - Prof. Cumani e più Appunti in PDF di Machine learning solo su Docsity!

Generative Multinomial Models: A Detailed

Introduction

Author Marc'Antonio Lopez AI & Data Analytics student at Polytechnic University of Turin

Introduction to Generative Multinomial Models

This overview delves into generative models , specifically focusing on those designed for multinomial distributions. Generative models function by learning the intrinsic process that generates the data. In the context of classification, this typically involves modeling the probability of observing certain features given a specific class ( ).

The multinomial distribution is central to these models, generalizing Bernoulli and binomial distributions to outcomes falling into multiple discrete categories. Consequently, generative multinomial models are foundational for handling discrete features —variables that can take values from a finite set of categories (e.g., 'red', 'green', 'blue') or represent counts (e.g., the number of times a specific word appears in a document).

Discrete Features and Categorical Variables

Working with Single Categorical Features

Generative multinomial models are particularly well-suited for classification tasks where the input consists of a single categorical feature. If this feature x can take m distinct values (i.e., ), these models provide a direct way to estimate the probabilities of each feature value given a class.

Example: Predicting Cat Gender Based on Fur Color

Let's illustrate with an example: predicting a cat's gender (our class) based on its fur color (our single categorical feature). Possible fur color categories might include:

P (features ∣ class)

x ∈

{1, 2, … , m }

To train such a model, we would assemble a dataset,. Each entry in this dataset would consist of an observed cat's fur color ( ) and its corresponding known gender ( ). The model would then learn the patterns of fur colors within each gender.

Independent and Identically Distributed (i.i.d.)

Samples

The i.i.d. Assumption in Machine Learning

A foundational assumption underlying many machine learning models, including generative multinomial models, is that the training samples are independent and identically distributed (i.i.d.). This assumption has two key parts:

Independent: The observation or measurement of one sample (e.g., one cat's fur color and gender) has absolutely no influence on, nor is it influenced by, the observation of any other sample. Each sample is a separate, unrelated event. Identically Distributed: All samples are assumed to be drawn from the exact same underlying probability distribution. This means statistical properties (like the probability of a certain fur color for a given gender) are consistent across all samples.

Goal: Estimating Conditional Probabilities

Given the i.i.d. assumption, our primary objective is therefore to estimate the conditional probability of observing a specific feature value (^) x_t for a new test sample, given that it belongs to a particular class c. This is formally expressed as. For simplicity, we often denote this conditional probability as.

Example: (or ) represents the probability that a randomly selected female cat will have white fur. Parameter Constraint: Crucially, for each class (^) c , the sum of probabilities for all possible feature values must equal one. That is, for a parameter vector , we must have. This ensures that the probabilities for a given class are properly normalized.

{white, black, orange, gray, bi-color, calico, ...}

D = {( x 1 , c 1 ), … , ( x n , c n )}

xi ci

P ( X t = x t ∣ C t = c )

πc , xt

P (white ∣ female) π female, white

π c =( π c ,1 , … , π c , m )

∑ j^ m =1^ π c , j = 1

Fur Color ( ) Gender ( ) black male

orange male black female

orange male

white male white female

white male

white female

black female

calico female

Likelihood Calculation Example

Based on this dataset, the overall likelihood would be computed as the product of the individual conditional probabilities for each of the 10 samples. For example, for the first sample (black fur, male gender), the term included in the product would be. This process would be repeated for all 10 samples, and their product would form the total likelihood.

Log-Likelihood Function

Simplifying Optimization with Log-Likelihood

Maximizing the likelihood function can be computationally challenging due to the product of many small probabilities. To simplify the optimization process, it is standard practice to maximize the log-likelihood instead. This is mathematically equivalent, as the logarithm is a monotonically increasing function. The key benefit is that it transforms products into sums, which are much easier to work with in optimization problems:

xi ci

L (Π)

P (fur color ∣ gender)

P (black ∣ male)

L (Π)

ℓ(Π) = log L (Π)

This sum can be further rearranged by grouping terms that belong to the same class:

This crucial factorization (breaking the sum into independent components for each class) means we can optimize the parameters for each class independently of the parameters for other classes, greatly simplifying the estimation process.

Rewriting the Class-Specific Log-Likelihood

Specifically, for a single class c , the log-likelihood contribution can be rewritten based on counts of feature occurrences within that class:

Here, denotes the count of training samples that belong to class c and exhibit feature value j.

Example Counts from Cat Dataset

To demonstrate, let's derive the counts from our example Cat Gender Dataset:

Feature (Fur Color) Count in Female ( ) Count in Male ( )

black 2 1

orange 0 2

white 2 2

calico 1 0

Total ( ) 5 5

(Note: here represents the total number of samples for that class, not necessarily total word tokens in text classification yet, which will be discussed later).

ℓ(Π) = log π

i =

n c (^) i , xi

ℓ(Π) = log π

c =

k

i such that c (^) i = c

∑ c , xi )

πc

ℓ c ( π c ) = N log π

j =

m c , j c , j

Nc , j

Nc , j

N female, j N male, j

Nc

Nc

Feature (j) MLE ( ) Calculation

black 0.

orange 0. white 0.

calico 0.

Handling Multiple Attributes (The Naive Bayes

Approximation)

The Challenge of Multiple Features (Curse of Dimensionality)

When we move from a single categorical feature to multiple categorical features (e.g., trying to model the joint probability of fur color and eye color given gender, ), we quickly encounter a significant problem known as the curse of dimensionality.

This "curse" arises because the number of possible unique combinations of feature values grows exponentially with the number of features. For example, if fur color has 6 values and eye color has 4 values, there are possible combinations. If we add another feature with 5 values, it jumps to combinations, and so on. This rapid increase leads to:

Severe Data Sparsity: In a finite training dataset, most of these combinations will never be observed, or will appear very rarely. Unreliable Probability Estimates: With insufficient observations for each combination, the probability estimates become highly unreliable and prone to sampling errors.

The Naive Bayes Approximation as a Solution

To circumvent the curse of dimensionality, the Naive Bayes approximation is widely adopted. Its core assumption is a strong simplification: it assumes that features are conditionally independent given the class. This means that if you know the class of an item (e.g., "female cat"), then knowing its fur color provides no additional information about its eye color (beyond what you already know from its class).

π male,^ ML j

P (fur color, eye color ∣ gender)

6 × 4 = 24

24 × 5 = 120

Mathematical Simplification: This powerful (and often unrealistic, but effective) assumption allows the joint conditional probability of observing multiple features to be dramatically simplified into a simple product of individual conditional probabilities for each feature j :

Here:

represents the total number of features (e.g., fur color, eye color, tail length). is the observed value of the j -th feature for the test sample t. is the probability of the (^) j -th feature having value (^) v within class (^) c. This parameter is estimated using MLE, as described earlier, for each feature independently.

Extended Problem: Event Occurrences (e.g., Word

Counts in Text)

Shifting Focus: From Categories to Counts of Events

Beyond dealing with simple categorical values (like 'black' or 'orange'), features can also represent counts of events. This scenario is extremely common in areas like text classification, where the "features" are how many times specific words appear.

The Bag-of-Words (BoW) Approximation

Text classification frequently relies on the Bag-of-Words (BoW) model. This is a powerful approximation that simplifies documents significantly:

Process: It treats a document as an unordered collection (a "bag") of words, completely ignoring word order and grammar. Focus: Instead, it focuses solely on the frequency (count) of each word, typically derived from a predefined vocabulary. Representation: Under the BoW model, a document is represented as a vector

. In this vector, denotes the count of the -th word from the vocabulary within that document, and is the size of the vocabulary.

P ( X t = x t ∣ C t = c ) ≈ P ( X =

j =

D

t , j x^ t ,[ j ] ∣ C^ t = c ) =^ π

j =

D c , j , xt ,[ j ]

D

xt ,[ j ]

πc , j , v

x =

( x [1], … , x [ m ]) x [ j ] j

m

for parameter optimization (ignoring constant multinomial coefficient terms):

This can again be factored and optimized independently for each class c :

where the class-specific log-likelihood is:

This means we sum the counts of each word j across all documents belonging to class c , and then multiply by the log probability of that word.

ML Solution for Word Probabilities

Deriving the MLE for Word Counts

Upon close examination, the log-likelihood for a single class (^) c in the context of word counts, , is mathematically identical to the form of the log-likelihood for the single categorical feature case. Here, represents the total count of word (^) j summed across all training documents belonging to class c.

The Maximum Likelihood Estimate (MLE) Formula for Word

Probabilities

Consequently, the Maximum Likelihood Estimate (MLE) for the probability of a specific word j within class c ( ) is precisely:

Where signifies the total count of all words (i.e., the sum of all word tokens) observed across all training documents that belong to class c. This is sometimes called the "total

ℓ(Π) = x [ j ] log π

i =

n

j =

m i c (^) i , j

c =

k c c

ℓ c ( π c )

ℓ c ( π c ) = x [ j ] log π

i s.t. c (^) i = c

j =

m i c , j

ℓ c ( π c ) =∑ j^ m =1^ N c , j log πc , j

Nc , j

πc^ ML, j

π c^ ML, j = N

c

Nc , j

N c =∑ j^ m =1^ Nc , j

word count" or "vocabulary size for class c" in the context of text.

Binary Classification Example: C vs. Python Files

Problem Setup

Let's apply these concepts to a practical binary classification problem: distinguishing between C programming files ( ) and Python programming files ( ) based on the counts of various punctuation symbols found within the files. These punctuation symbol counts will serve as our discrete features.

Log-Likelihood Ratio (LLR) for Classification

For a new, unseen file with observed symbol counts represented by the vector x , we can make a classification decision by comparing the likelihood of x belonging to each class. This is commonly done using the Log-Likelihood Ratio (LLR) :

Substituting the Multinomial PMF (and ignoring the constant multinomial coefficient part that cancels out in the ratio), the LLR simplifies to:

Here, is the count of symbol j in the new file, and and are the MLEs for the probability of symbol j occurring in C and Python files, respectively.

Decision Rule:

If : The numerator (likelihood for class C) is greater than the denominator (likelihood for class Python). Therefore, classify the file as C. If : The likelihood for class Python is greater. Therefore, classify the file as Python. If : The likelihoods are equal. A tie-breaking rule would be needed (e.g., classifying as the more common language a priori).

Example LLR Results

Let's assume we've calculated the values from a training dataset.

h 1 h 0

llr( x ) = log

P ( X = x ∣ C = h 0 )

P ( X = x ∣ C = h 1 )

llr( x ) = x [ j ] log

j =

m

πh^ ML 0 , j

πh^ ML 1 , j

x [ j ] πh^ ML 1 , j^ πh^ ML 0 , j

llr( x ) > 0

llr( x ) < 0

llr( x ) = 0

π ML

Symbols Indicating C Files: The semicolon ( ; ) is a clear indicator of a C file. Its estimated probability ( in C is ) is significantly higher compared to its probability in Python ( ). This makes intuitive sense, as semicolons are widely used for statement termination in C but are optional or less common in Python. Symbols Indicating Python Files: Conversely, the colon ( : ) and the dot (. ) symbols are stronger indicators of Python files. For example, the probability of a colon in Python ( ) is considerably higher than in C ( ). Similarly, the dot has a much higher probability in Python ( ) than in C ( ). This reflects their extensive use in Python for defining blocks (colons) and accessing attributes/methods (dots). Less Useful Symbols: Round brackets ( () ) are comparatively less discriminative. They exhibit similar probabilities ( ) in both C and Python files, suggesting they don't strongly distinguish between the two languages based on their frequency alone.

Test Scripts: Evaluating New Files

To illustrate the classification process with actual counts, here are the punctuation symbol counts for two hypothetical test scripts. is designed to resemble a C file, and is designed to resemble a Python file:

Symbol Test Script Counts (C-like) Test Script Counts (Python-like) {} 2 2

[] 10 18

() 12 16 : 0 3

; 1 0

. 1 1

Total 26 40

(You would use these counts, along with the estimated values from the previous section, to calculate the LLR for each test script and make a classification decision.)

π P y ,:=

0.074 π C ,: =0.

x 1 x 2

x 1 x 2

πc^ ML, j

Practical Considerations: Handling Zero Counts

The Zero Probability Problem

A critical practical challenge arises in multinomial models (especially Naive Bayes) if a particular test feature value (e.g., a specific word or symbol) never appeared in the training data for a specific class. In such a scenario:

Its Maximum Likelihood Estimate (MLE) probability ( ) would be calculated as 0. When calculating the overall likelihood for that class using the product formula ( ), even if only one is non-zero and its corresponding is 0, the entire product will become 0. This would cause the overall likelihood for that class to become 0 and its log-likelihood to become . Consequence: This effectively makes classification for that class impossible, as the model cannot properly evaluate its probability.

Solution: Pseudo-counts (Smoothing)

To mitigate this problem, a common and highly effective solution is to apply smoothing techniques. The most popular method involves adding a small pseudo-count (alpha) to all observed counts, even those initially zero.

The smoothed MLE formula for becomes:

Here:

is the observed count of feature j in class c. is the total count of all features in class c. is the total number of unique features in the vocabulary/feature space. is the pseudo-count. A common choice is , known as Laplace smoothing or "add-one smoothing."

Benefits of Smoothing:

Ensures all feature probabilities are non-zero, preventing the zero probability problem. Provides a more robust and less sensitive estimate, especially for rare features. Mathematical Equivalence: Importantly, applying pseudo-counts is mathematically equivalent to performing Maximum A Posteriori (MAP) estimation with a Dirichlet prior distribution over

πc^ ML, j

∏ πcx ,[ jj ]

x [ j ] πc^ ML, j

πc , j

π c^ smoothed, j =

N c + mα

N c , j + α

Nc , j

Nc

m

Equivalence: Categorical vs. Count-Based Models

Two Equivalent Views of Discrete Data

It is crucial to understand that discrete features, particularly in the context of text or event counts, can be conceptually modeled in two fundamentally equivalent ways:

  1. Categorical Model (Token-based): Viewpoint: In this perspective, each individual discrete observation (or "token," such as a single word in a document) is considered an independent draw from a Categorical (or Multinomial with N=1) distribution. This distribution is parameterized by , which represents the probability of drawing each category within class (^) c. Log-Likelihood: The log-likelihood for this model, considering all individual tokens across all documents in a class, is given by: , where is the total count of category j across all tokens.
  2. Multinomial Model (Document-based): Viewpoint: Alternatively, the entire count vector representing an entity (e.g., a document's word counts, where each document has a fixed total number of words ) is considered a single draw from a Multinomial distribution. This distribution is also defined by the same parameters and the total count. Log-Likelihood: The log-likelihood for this perspective, ignoring the constant multinomial coefficient, is:.

Key Observation on Equivalence:

A critical insight is that the two log-likelihood functions, and , are proportional to each other. They differ only by a constant term independent of the parameters. Consequently, their raw likelihoods are also proportional:.

Significant Implications of this Equivalence:

This mathematical equivalence has profound practical implications for generative multinomial models:

  1. Identical MLE: Both modeling views (categorical/token-based and multinomial/document-based) will yield precisely the same Maximum Likelihood Estimates for the probabilities . This means you can count words per document or words per class and arrive at the same parameter estimates.
  2. Identical Bayesian Posteriors: Similarly, if you were to employ Bayesian methods for parameter estimation, both views would result in identical posterior distributions for the parameters.

πc

ℓ X ( π ) =∑ j^ m =1^ N j log πj Nj

N

πc

N

ℓ Y ( π ) =Constant + ∑ j^ m =1^ N j log πj

ℓ X ( π ) ℓ Y ( π )

L X ( π ) ∝ L Y ( π )

π j^ ML=

N j / N

  1. Identical Classification Inference: Most importantly, the classification decisions made by models built on either view will be identical. This is because any constant factors (like the multinomial coefficient in the document-based PMF) will cancel out when forming Log-Likelihood Ratios (LLRs) or comparing posterior probabilities for classification, thus not affecting the final decision.

Conclusion: Recap and Key Takeaways

Lecture Recap

This lecture provided a detailed introduction to generative multinomial models , outlining their core principles and practical applications:

We began by exploring how to model single categorical features using Maximum Likelihood Estimation (MLE), where parameters (probabilities) are simply calculated as relative frequencies. To tackle the challenge of multiple discrete features , we introduced the powerful Naive Bayes approximation , which assumes conditional independence between features given the class. The concepts were then extended to scenarios involving event occurrences and word counts , demonstrating how the Multinomial distribution is the appropriate choice for modeling these feature types, along with its corresponding MLE derivation. Crucially, we addressed the vital practical issue of zero probabilities (when a feature is unseen in a class's training data) by introducing the effective technique of smoothing (using pseudo- counts). Finally, we formally established the equivalence between token-based (categorical) and count- based (multinomial) models for discrete data, showing that they lead to the same parameter estimates and classification decisions. Overall: These models are highly effective for discrete data classification, finding particular utility in applications such as Natural Language Processing (NLP).

Final Summary: Key Takeaways

To summarize the essential points from this discussion:

Generative models based on categorical and multinomial distributions are fundamental and versatile tools for classifying data that consists of discrete features. These models are well-suited for modeling a diverse range of discrete data types, including straightforward categorical variables like fur colors, count-based features like the occurrences of