Implement Logistic Regression Trained With True SGD (Batch Size 1) From Scratch
Quick Overview
Implement binary logistic regression from scratch in NumPy, trained with true stochastic gradient descent that makes one update per sample. It tests the per-sample log-loss gradient, the order of parameter updates and reproducible shuffling with a single random generator.
Implement Logistic Regression Trained With True SGD (Batch Size 1) From Scratch
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement binary logistic regression trained with true SGD from scratch (no sklearn): exactly one parameter update per individual sample (batch size 1). Return the learned `(w, b)`.
```python
def fit_logistic_sgd(X: np.ndarray, y: np.ndarray, lr: float, n_epochs: int, seed: int) -> tuple[np.ndarray, float]:
```
Follow this protocol exactly so the result is reproducible from `seed`:
- Initialize `w = np.zeros(n_features)` and `b = 0.0`. `X` has no column of ones, so keep a separate scalar bias.
- Create `rng = np.random.default_rng(seed)` once. At the start of each epoch, draw `perm = rng.permutation(n_samples)` from it (no re-seeding) and visit the samples in `perm` order.
- For each sample, compute `p_i = 1/(1+np.exp(-(X[i] @ w + b)))`, then apply `w -= lr * (p_i - y[i]) * X[i]` and `b -= lr * (p_i - y[i])`. Both updates use the `p_i` computed before either update.
- Do not divide by `n_samples`. Run exactly `n_epochs` epochs with a fixed `lr`, no early stopping and no regularization.
- Return `w` as an `np.ndarray` of shape `(n_features,)` and `b` as a float.
As a check: with `X = [[1.0]]`, `y = [1]`, `lr = 1.0`, `n_epochs = 2` and any seed, the function returns `w` close to `[0.768941]` and `b` close to `0.768941`.
```hint Order of operations
Compute each sample's prediction once and keep it. A bias update that uses a prediction recomputed after `w` changed gives a different result from the one specified.
```
```hint Where the generator lives
Think about what happens to the visiting order across epochs if the generator is created inside the epoch loop.
```
### Constraints & Assumptions
- `X` is a numeric array of shape `(n_samples, n_features)` with no intercept column.
- `y` has shape `(n_samples,)` and holds labels 0 or 1.
- `lr` is a fixed positive step size and `n_epochs` is the exact number of passes over the data.
### What a Strong Answer Covers
- The per-sample gradient of the log-loss with respect to the weights and the bias, and why no averaging term appears with a batch size of 1.
- One generator created before the epoch loop, with a fresh permutation drawn from it at the start of every epoch.
- Both parameter updates computed from the same pre-update prediction.
- Return values that match the contract: `w` of shape `(n_features,)` and `b` as a float.
- Time and space complexity of the training loop.
### Follow-up Questions
- Why reuse the same `rng` across epochs instead of re-seeding it at the start of each epoch?
- How would you add L2 regularization to this per-sample update?
- How could you guard against overflow in `np.exp`?
Overview: Implement binary logistic regression from scratch in NumPy, trained with true stochastic gradient descent that makes one update per sample. It tests the per-sample log-loss gradient, the order of parameter updates and reproducible shuffling with a single random generator.
Implement Logistic Regression Trained With True SGD (Batch Size 1) From Scratch
General
Nov 24, 2026
mediumData ScientistOtherMachine Learning
0
0
Implement binary logistic regression trained with true SGD from scratch (no sklearn): exactly one parameter update per individual sample (batch size 1). Return the learned (w, b).
Follow this protocol exactly so the result is reproducible from seed:
Initialize
w = np.zeros(n_features)
and
b = 0.0
.
X
has no column of ones, so keep a separate scalar bias.
Create
rng = np.random.default_rng(seed)
once. At the start of each epoch, draw
perm = rng.permutation(n_samples)
from it (no re-seeding) and visit the samples in
perm
order.
For each sample, compute
p_i = 1/(1+np.exp(-(X[i] @ w + b)))
, then apply
w -= lr * (p_i - y[i]) * X[i]
and
b -= lr * (p_i - y[i])
. Both updates use the
p_i
computed before either update.
Do not divide by
n_samples
. Run exactly
n_epochs
epochs with a fixed
lr
, no early stopping and no regularization.
Return
w
as an
np.ndarray
of shape
(n_features,)
and
b
as a float.
As a check: with X = [[1.0]], y = [1], lr = 1.0, n_epochs = 2 and any seed, the function returns w close to [0.768941] and b close to 0.768941.
Constraints & Assumptions
X
is a numeric array of shape
(n_samples, n_features)
with no intercept column.
y
has shape
(n_samples,)
and holds labels 0 or 1.
lr
is a fixed positive step size and
n_epochs
is the exact number of passes over the data.
What a Strong Answer Covers Guidance
The per-sample gradient of the log-loss with respect to the weights and the bias, and why no averaging term appears with a batch size of 1.
One generator created before the epoch loop, with a fresh permutation drawn from it at the start of every epoch.
Both parameter updates computed from the same pre-update prediction.
Return values that match the contract:
w
of shape
(n_features,)
and
b
as a float.
Time and space complexity of the training loop.
Follow-up Questions Guidance
Why reuse the same
rng
across epochs instead of re-seeding it at the start of each epoch?
How would you add L2 regularization to this per-sample update?