Average marginal effect vs marginal effect at the means in logistic regression
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement the function below. `X` is an `(n, p)` float array with no intercept column and `y` is a 1-D array of 0/1 integers.
```python
def ame_vs_at_means(X: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
```
Fit the model with
```python
sm.Logit(y, sm.add_constant(X)).fit(method="newton", maxiter=200, tol=1e-10, disp=0)
```
and return the average marginal effect (AME) and the marginal effect at the means (MEM) of each regressor:
- Return a 2-tuple `(ame, mem)` of 1-D float64 arrays.
- `ame` is `res.get_margeff(at="overall", method="dydx").margeff`.
- `mem` is `res.get_margeff(at="mean", method="dydx").margeff`.
- Both have shape `(p,)`. The constant is dropped, so the shape is not `(p+1,)`.
```hint Write the derivative
Write the derivative of the predicted probability with respect to one regressor, then ask at which rows of the sample each of the two quantities evaluates it.
```
```hint Check it by hand
Both results can be rebuilt from `res.params` and the fitted probabilities in a few lines of NumPy, which confirms the library calls did what you expected.
```
### Constraints & Assumptions
- The grader uses a fixed dataset with `n = 80` and `p = 2` that is not perfectly separable, so the maximum likelihood estimate exists and Newton's method converges.
- It asserts that both arrays have shape `(2,)` and compares values with `numpy.testing.assert_allclose(rtol=1e-6)`.
- It also asserts `np.any(np.abs(ame - mem) > 1e-6)`, so returning the same array twice fails.
### What a Strong Answer Covers
- One logit fit with the stated settings and two `get_margeff` calls that differ only in `at`.
- Outputs as 1-D float64 arrays of shape `(p,)` with the constant excluded.
- The logit marginal effect formula and why averaging per-row effects differs from evaluating the effect at the mean row.
- When MEM misleads, such as with binary regressors, and how standard errors for the effects are obtained.
### Follow-up Questions
- Why is AME generally preferred over MEM for reporting?
- How would you attach standard errors to the AME?
- How should the effect of a binary regressor be computed, and what changes in the `get_margeff` call?
- In a plain logit with no interactions, how are the AME and MEM vectors related to each other and to the coefficients?
Overview: Fit a logistic regression in statsmodels and return both the average marginal effect and the marginal effect at the means for each regressor. It tests how the two summaries are computed, why they differ for a nonlinear model, and which one to report.