This lab helps you to estimate the Poisson rate parameter ($\lambda$) using the negative log-likelihood (NLL) framework for a Poisson distribution in PyTorch, and optionally extend the concept to a Poisson regression scenario where $\lambda$ is modeled as a function of input features through a linear model.

In probability theory and statistics, the Poisson distribution is a discrete probability distribution that expresses the probability of a given number of events occurring in a fixed interval of time if these events occur with a known constant mean rate $\lambda$ and independently of the time since the last event.

Theory Recap

The Poisson distribution for a single observation $y \in \{0, 1, 2, \dots\}$ with rate $λ$ is:

$$ p(y \mid \lambda) = \frac{e^{-\lambda} \lambda^{y}}{y!}. $$

For $n$ independent observations $\{y_i\}_{i=1}^n$, the log-likelihood is:

$$ \log \mathcal{L}(\lambda) = \sum_{i=1}^n \log p(y_i \mid \lambda) = \sum_{i=1}^n \left( -\lambda + y_i \log(\lambda) - \log(y_i!) \right). $$

The constant term $\sum \log(y_i!)$ does not depend on $\lambda$, so the negative log-likelihood (ignoring constants) is:

$$ \text{NLL}(\lambda)= \lambda \cdot n - \log(\lambda) \sum_{i=1}^n y_i. $$

To find $\hat{\lambda}_{\text{MLE}}$ analytically, set derivative $\frac{d\text{NLL}(\lambda)}{d\lambda}= 0$, which yields:

$$ \hat{\lambda}{\text{MLE}}= \frac{1}{n} \sum{i=1}^n y_i. $$

Poisson Regression

Rather than a single Poisson rate, suppose each sample $y^{(i)}$ has its own rate $\lambda^{(i)}$ that depends on features $\mathbf{x}^{(i)}$. A common model is:

$$ \lambda^{(i)} = \exp(\mathbf{w}\cdot\mathbf{x}^{(i)}+b). $$

Here, the exponential function ($\exp$) serves as the link function (actually the inversed function $\log$), mapping the linear model output to the parameters of the Poisson distribution. This exponential transformation ensures that the relationship is monotonic and strictly positive.

Then the goal is to minimize the negative log-likelihood:

$$ \arg\min_{\mathbf{w},b} \sum_{i=1}^n \left( \lambda^{(i)} - y^{(i)} \log(\lambda^{(i)}) \right), $$

where $\lambda^{(i)}$ is a function of $\mathbf{w}$ and $\mathbf{x}^{(i)}$.

Code

  1. Generate synthetic features $\mathbf{x}^{(i)}$ and define a “true” parameters $\mathbf{w}, b$ just like logistic regression.

    import torch
    import torch.nn as nn
    import torch.optim as optim
    
    # Synthetic data
    N, D = 3000, 2
    X = torch.randn(N, D)
    true_W = torch.tensor([[0.5], [-1.0]])  # shape (2,1)
    true_b = torch.tensor([0.3])