6/14
Part 3 of 7 · Logistic regressionLearn and do
Newton's method fits it, and each coefficient moves the log odds
Penn State's course notes spell out what that means: the log of the odds, p / (1 − p), is a linear function of the x's. They add that maximizing the likelihood has no closed-form solution, so an iterative method such as reweighted least squares finds it. Newton's method below is that method. Each step uses the curvature and the gradient of the log-likelihood, Xᵀ(y − p). The negative log-likelihood's gradient is the same with the sign flipped, Xᵀ(p − y).
# bought in a sale
sale = (rng.random(n) < 0.3).astype(float)
# how far the size ran from the customer's usual
size_gap = rng.normal(0, 1, n)
chance = 1 / (1 + np.exp(-(-2.2 + 0.7 * sale + 0.9 * size_gap)))
y = (rng.random(n) < chance).astype(float)
def fit_logistic(columns, y, steps=25):
"""Maximum likelihood by Newton's method: the intercept, then one coefficient per column."""
X = np.column_stack([np.ones(len(y))] + list(columns))
w = np.zeros(X.shape[1])
for _ in range(steps):
p = 1 / (1 + np.exp(-(X @ w)))
w += np.linalg.solve(X.T @ (X * (p * (1 - p))[:, None]), X.T @ (y - p))
return w
w = fit_logistic([sale, size_gap], y)
print(f"intercept {w[0]:.2f}, sale {w[1]:.2f}, size gap {w[2]:.2f}")
print(f"e to the sale coefficient: {np.exp(w[1]):.2f}")
The simulation's true sale coefficient is 0.7. What does a sale do to a return?
Pick one to see what it prints.
Pick an answer above to see the rest