Skip to content

ENH: regression plots for binary endog #6435

Open

Description

@josef-pkt

a quick prototype for a Logit plot observed versus predicted, using lowess as smoother (local averaging)
see #6430 (calibration) #6434 plot elements like add_lowess

fig = plt.Figure(figsize=(8, 6))
ax = fig.add_subplot(1, 1, 1)
ax.plot(fitted[sort_idx], endog[sort_idx], '|')
fig = add_lowess(ax)
#ax.plot(fitted[sort_idx], fitted[sort_idx], color='k', alpha=0.5)
ax.plot([0, 1], [0, 1], color='k', alpha=0.5)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title("Logit - observed versus predicted")
ax.set_xlabel('predicted probability')
ax.set_ylabel('response')
fig

Activity

  1. josef-pkt commented on Jan 18, 2020

    @josef-pkt
    MemberAuthor

    example plot for current version (nobs=500, simulated data, no random seed)

    logit_regplot_500

  2. josef-pkt commented on Jan 18, 2020

    @josef-pkt
    MemberAuthor

    another possibility CUSUM plot version of the above
    However, it's not easy to see smaller misspecification when applied to training sample.
    (idea: instead of binning to get local probabilities, we use the empirical "cdf" but it is a cumulative probability where observations have different expected values)

    simulated example: distortion in misspecified link function linpred = np.exp(linpred + 0.5) - 2 but model assumes Logit

    nobs=200 so we see some deviation from 45 degree line

    logit_regplot_cusum_200

    fig = plt.Figure(figsize=(8, 6))
    ax = fig.add_subplot(1, 1, 1)
    xx = np.cumsum(fitted[sort_idx]) / nobs
    yy = np.cumsum(endog[sort_idx]) / nobs
    ax.plot(xx, yy, '.-')
    fig = add_lowess(ax)
    #ax.plot(fitted[sort_idx], fitted[sort_idx], color='k', alpha=0.5)
    
    ulim = max(xx.max(), yy.max())
    ax.plot([0, ulim], [0, ulim], color='k', alpha=0.5)
    ax.set_xlim(0, ulim)
    ax.set_ylim(0, ulim)
    ax.set_title("Logit - observed versus predicted (CUSUM)")
    ax.set_xlabel('CUSUM predicted probability')
    ax.set_ylabel('CUSUM response')
    fig
    
  3. normanius commented on Jun 19, 2020

    @normanius

    A calibration plot that I found appealing. Just for inspiration.
    The possibility to compute confidence intervals looks also utile.

    Source: Steyerberg, E. W. Clinical prediction models : a practical approach to development, validation, and updating. (2019). Chapter 15 (Evaluation Performance)

    image

  4. josef-pkt commented on Sep 27, 2020

    @josef-pkt
    MemberAuthor

    I'm just trying to figure out similar plots for OrderedModel #7035 and MNLogit, so I can compare predictions of those two.
    One option in the multivariate/multinomial case it to plot separately for each choice dummy.

  5. josef-pkt commented on Sep 29, 2020

    @josef-pkt
    MemberAuthor

    If I iterate lowess in a larger example, e.g. default it=3, then I get a fit to extremes, e.g. many zeros in fitted values. I think robustness or mad kicks in and having only a few local opposite, 0, 1 values are treated as outliers.

    I get better results with it=0, e.g. add_lowess(ax, frac=0.3, it=0) which are closer to 45 degree line

    example for anes96 data using MNLogit while looking at plots for #7035, using separate plots for each endog dummy.

  6. josef-pkt commented on Sep 29, 2020

    @josef-pkt
    MemberAuthor

    another issue training sample versus test sample:

    Most of our regression plots are in-sample, they take a results instance and get the relevant data from those.

    my prototype for the binary reset test uses fitted and observed which can be used also with a test sample.

    def plot_binary(fitted, observed, idx, ax=None):
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
        
        dummies = np.clip(observed[sort_idx[:, idx], idx], 0.01, 0.99)
        ax.plot(fitted[sort_idx[:, idx], idx], dummies, "|")
        ax.set_title("fitted versus observed, choice=%s" % str(i))
    
        fig = add_lowess(ax, frac=0.3, it=0)
        fig = qqline(ax, "45", fmt="k-")
        ax.set_xlim(0, 1)
        ax.set_ylim(0, 1)
        return fig
    
    from statsmodels.graphics import utils
    
    def plot_multinomial_grid(fitted, observed, endog_names=None, grid=None, figsize=None, fig=None):
        import pandas
        fig = utils.create_mpl_fig(fig, figsize=figsize)
    
    
        k_endog = observed.shape[1]
        nrows = (k_endog + 1) // 2
        ncols = 1 if nrows == k_endog else 2
        if grid is not None:
            nrows, ncols = grid
        if ncols > 1:
            title_kwargs = {"fontdict": {"fontsize": 'small'}}
    
        # for indexing purposes
        other_names = [str(i) for i in range(k_endog)] #np.array(results.model.exog_names)
        for i, idx in enumerate(np.arange(k_endog)):
            ax = fig.add_subplot(nrows, ncols, i + 1)
            plot_binary(fitted, observed, i, ax=ax)
            ax.set_title("")
    
        fig.suptitle("Observed versus fitted Plot", fontsize="large")
        fig.tight_layout()
        fig.subplots_adjust(top=.95)
    
        return fig
    

    edit
    this functions are from my dev notebook try_mnlogit_ordered_margin.ipynb

  7. added this to the 0.14 milestone on Sep 8, 2021
  8. modified the milestones: 0.14, 0.15 on Jan 20, 2023
  9. josef-pkt commented on Jan 20, 2023

    @josef-pkt
    MemberAuthor

    related: overlap diagnostic for propensity score

    nonoverlapping observations are close to 0 or 1 boundaries.
    What would be useful is to add the histogram/kde for axes similar to or using seaborn

    bump for 0.15 we can add it to a Binary Diagnostic class similar to the plots for CountDiagnostic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions