Skip to content

MNLogit Optimizations #3778

Closed
Closed

Description

@jbrockmendel

I've spent most of today trying to estimate a MNLogit model with J=K=14, nobs\approx1.05M. In the process I've jotted down a bunch of notes that I'm dumping here.

  1. At the moment any callback is ignored and overridden by callback = lambda x: None. This should only be done if the user does not pass a callback. Example: display loglike and np.abs(score).sum() at each iteration to confirm that the iteration is converging (nope! getting stuck after the second iteration)

  2. A common problem is overflows in cdf and underflows in loglike. cdf is effectively:

def cdf(self, X):
        eXB = np.column_stack((np.ones(len(X)), np.exp(X)))
        return eXB/eXB.sum(1)[:, None]

If (X > 709.8).any(), we're going to have an overflow (I'm assuming that everything is np.float64). The exact cutoff is np.log(np.finfo(np.float64).max). Even if X is small, we'll also get in loglikeobs wherever X.ptp(1) > 709.8.

AFAICT we can fix cdf on its own and worry about loglike/score/hess separately.

  1. A)
    Let's start with cdf. Take a single row in row=eXB[rnum]. Because of the column of np.ones, we know the denominator row.sum() is strictly positive, so we don't need to worry about division by zero. What we do need to worry about is division by np.inf. If there is exactly one np.inf in row, then we can assign np.inf/np.inf = 1. We can avoid cases where there is more than one np.inf in row by dividing row by its maximum value:
def cdf(self, X):
    XB = np.column_stack(np.zeros(len(X)), X)
    XB -= XB.max(1).reshape(-1, 1)
    eXB = np.exp(XB)
    denom = exB.sum(1)[:, None]
    return eXB / denom

The edge case that I have not considered is where row is finite but big enough that the sum is infinite.

  1. B) loglike, score, and hessian
    Let's assume for now that we can rely on cdf to never return np.nan. We still have the issue that 0s and 1s in the output from cdf are going to cause problems in the optimization.

loglikeobs is roughly:

def loglikeobs(self, params):
    Xb = self.exog.dot(params)
    prob = self.cdf(Xb)
    return self.wendog * np.log(prob)

So any zeros in prob become -np.inf. If we aren't in a terrible part of the parameter space, most of the places where prob == 0 should also have self.wendog == 0. Because the prob==0 is known to be subject to floating point error while wendog is not, we can use the convention 0 * -np.inf == 0 and get rid of many of these problems. In cases where we don't have self.wendog == 0, we might just be out of luck.

For the corresponding problem in score_obs and hessian, I'm playing with the idea of clipping the values of cdf away from zero and 1 so that the optimizer can at least tell what direction they are moving in. Pretty speculative at this point.

  1. Adding ridge_factor in optimizer._fit_newton is not always useful. I'm seeing a case where H is many orders of magnitude smaller than ridge_factor (sometimes identically zero) and so the increment to newparams is on the order of 10^10. The params are still floating off towards infinity, but the values of loglike are staying constant after a the first couple of iterations. This might be worth catching inside _fit_newton.

  2. hessian is pretty expensive, and can be cut almost in half. The status quo:

def hessian(self, params):
        params = params.reshape(self.K, -1, order='F')
        X = self.exog
        pr = self.cdf(np.dot(X,params))
        partials = []
        J = self.wendog.shape[1] - 1
        K = self.exog.shape[1]
        for i in range(J):
            for j in range(J): # this loop assumes we drop the first col.
                if i == j:
                    partials.append(\
                        -np.dot(((pr[:,i+1]*(1-pr[:,j+1]))[:,None]*X).T,X))
                else:
                    partials.append(-np.dot(((pr[:,i+1]*-pr[:,j+1])[:,None]*X).T,X))
        H = np.array(partials)
        # the developer's notes on multinomial should clear this math up
        H = np.transpose(H.reshape(J,J,K,K), (0,2,1,3)).reshape(J*K,J*K)
        return H

Becomes

def hessian(self, params):
        params = params.reshape(self.K, -1, order='F')
        X = self.exog
        pr = self.cdf(np.dot(X, params))
        J = self.wendog.shape[1] - 1
        K = self.exog.shape[1]

        partials = [[None for z in range(J)] for w in range(J)] 
        for i in range(J):
            for j in range(i, J): # this loop assumes we drop the first col.
                if i == j:
                    partial = -np.dot(((pr[: ,i+1]*(1-pr[:,j+1]))[:, None]*X).T, X)
                else:
                    partial = -np.dot(((pr[:, i+1]*-pr[:,j+1])[:, None]*X).T, X)
                partials[i][j] = partial
                partials[j][i] = partial
        
        partials = [part for vec in partials for part in vec]
        H = np.array(partials)
        # the developer's notes on multinomial should clear this math up
        H = np.transpose(H.reshape(J,J,K,K), (0,2,1,3)).reshape(J*K,J*K)
        return H

The calculation of each partial term can be cleaned up a bit, but the main thing is just doing it half as often. In today's use case this cut the runtime on hessian from 23 seconds to 12 seconds.

  1. Next to try: take a random subsample of e.g. 10k observations an fit the model on that, then use the results from that as start_params to fit on the entire dataset.

Activity

  1. jbrockmendel commented on Jun 24, 2017

    @jbrockmendel
    ContributorAuthor

    Another note on the ridge_factor adjustment in _fit_newton. In some cases the hessian post-ridge_factor is invertible while the raw hessian is not. Then back in LikelihoodModel.fit it will try to invert the raw hessian and raise a numpy.linalg.linalg.LinAlgError: Singular matrix

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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions