Repository navigation
Description
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.
-
At the moment any
callbackis ignored and overridden bycallback = lambda x: None. This should only be done if the user does not pass a callback. Example: displayloglikeandnp.abs(score).sum()at each iteration to confirm that the iteration is converging (nope! getting stuck after the second iteration) -
A common problem is overflows in
cdfand underflows inloglike.cdfis 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.
- A)
Let's start withcdf. Take a single row inrow=eXB[rnum]. Because of the column ofnp.ones, we know the denominatorrow.sum()is strictly positive, so we don't need to worry about division by zero. What we do need to worry about is division bynp.inf. If there is exactly onenp.infinrow, then we can assignnp.inf/np.inf = 1. We can avoid cases where there is more than onenp.infinrowby dividingrowby 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.
- B)
loglike,score, andhessian
Let's assume for now that we can rely oncdfto never returnnp.nan. We still have the issue that 0s and 1s in the output fromcdfare 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.
-
Adding
ridge_factorinoptimizer._fit_newtonis not always useful. I'm seeing a case whereHis many orders of magnitude smaller thanridge_factor(sometimes identically zero) and so the increment tonewparamsis on the order of 10^10. The params are still floating off towards infinity, but the values ofloglikeare staying constant after a the first couple of iterations. This might be worth catching inside_fit_newton. -
hessianis 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.
- 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_paramsto fit on the entire dataset.
Activity
jbrockmendel commentedon Jun 24, 2017
Another note on the
ridge_factoradjustment in_fit_newton. In some cases the hessian post-ridge_factor is invertible while the raw hessian is not. Then back inLikelihoodModel.fitit will try to invert the raw hessian and raise anumpy.linalg.linalg.LinAlgError: Singular matrix