---
title: Logistic regression with gradient descent
url: https://gurkanozkan.ai/learn/coding/mle-logistic-regression-with-gradient-descent-09/
markdown: https://gurkanozkan.ai/learn/coding/mle-logistic-regression-with-gradient-descent-09.md
kind: coding
difficulty: Medium
topics:
  - NumPy
  - Optimisation
  - From scratch
json: https://gurkanozkan.ai/api/learn/coding/mle-logistic-regression-with-gradient-descent-09.json
robots: noindex
---

# Logistic regression with gradient descent

- (a) `logistic_loss_grad(X, y, w, b)` returns the mean binary cross-entropy loss and its gradients `(loss, grad_w, grad_b)` for `p = σ(Xw + b)`. It must be finite for |Xw + b| up to 1000. - (b) `fit_logistic(X, y, lr, epochs)` runs full-batch gradient descent from `w = 0, b = 0` for exactly `epochs` steps and returns `(w, b)`.

## Signature

```python
def logistic_loss_grad(X, y, w, b) -> tuple[float, np.ndarray, float]: ... def fit_logistic(X, y, lr: float = 0.1, epochs: int = 1000) -> tuple[np.ndarray, float]: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(logistic_loss_grad([[1.0],[2.0]], [0, 1], [0.0], 0.0), (0.693147, [-0.25], 0.0))
True

>>> close(logistic_loss_grad([[1.0, 0.0],[0.0, 1.0]], [1, 1], [0.0, 0.0], 0.0), (0.693147, [-0.25, -0.25], -0.5))
True
```

## Hints

1. Gradient: X^T(p - y)/n for w, mean(p - y) for b.
2. Loss = mean(logaddexp(0, z) - y*z) with z = Xw + b — finite for |z| up to 1000.
3. Full-batch descent from w=0, b=0 for exactly epochs steps, fully vectorised.

## Reference solution

```python
import numpy as np

def _sigmoid(z):
    return np.where(z >= 0, 1 / (1 + np.exp(-np.abs(z))), np.exp(-np.abs(z)) / (1 + np.exp(-np.abs(z))))

def logistic_loss_grad(X, y, w, b):
    X = np.asarray(X, float); y = np.asarray(y, float); w = np.asarray(w, float)
    z = X @ w + b
    # stable BCE: log(1+e^z) - y z
    loss = np.mean(np.logaddexp(0, z) - y * z)
    p = _sigmoid(z)
    gw = X.T @ (p - y) / len(y)
    gb = float(np.mean(p - y))
    return float(loss), gw, gb

def fit_logistic(X, y, lr=0.1, epochs=1000):
    X = np.asarray(X, float)
    w = np.zeros(X.shape[1]); b = 0.0
    for _ in range(epochs):
        _, gw, gb = logistic_loss_grad(X, y, w, b)
        w -= lr * gw; b -= lr * gb
    return w, b
```

## What a strong solution covers

- Correct gradient `Xᵀ(p − y)/n` and `mean(p − y)`.
- Stable loss via `logaddexp(0, z) − y·z`, or clipping.
- Fully vectorised.
- Discusses LR choice, convergence checks, SGD vs full batch, L2 regularisation, and divergence on separable data without regularisation.

## Common mistakes

- sign errors in the gradient
- `log(sigmoid(z))` returning −inf for large negative z.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
