Write one fitter for several generalized linear models. The linear predictor is ηn=w⊤xn+on (an optional fixed offset on), and the mean is μn=ℓ−1(ηn) for a link ℓ.
Implement glm_fit(X, y, family, link, trials=None, offset=None, n_iter=100, tol=1e-10):
family: "gaussian" (variance function V(μ)=1), "poisson" (V(μ)=μ) or "binomial". For the binomial, y holds success counts out of trials Nn (default all ones), μn is the success probability, E[yn]=Nnμn and Var[yn]=Nnμn(1−μn).
link: "identity" (μ=η), "log" (μ=eη), "logit" (μ=σ(η)), "probit" (μ=Φ(η), the standard normal CDF) or "cloglog" (μ=1−exp(−eη)).
- Fit by Fisher scoring written as iteratively reweighted least squares. Start from w=0. At each iteration compute η, μ and dμ/dη, then solve the weighted least-squares system X⊤WXwnew=X⊤Wz with
- weights Wn=V(μn)(dμn/dηn)2 for the Gaussian and Poisson families and Wn=μn(1−μn)Nn(dμn/dηn)2 for the binomial;
- working response zn=ηn−on+Nndμn/dηnyn−E[yn] (with Nn=1 outside the binomial).
- Stop when maxd∣wnew−w∣d<
tol or after n_iter iterations. Return w.
Only sensible family/link pairs are tested (identity-Gaussian, log-Poisson, and logit/probit/cloglog-binomial).