Skip to content

Instantly share code, notes, and snippets.

@mlubin
Last active August 29, 2015 14:01
Show Gist options
  • Save mlubin/055690ddf2466e98bba6 to your computer and use it in GitHub Desktop.
Save mlubin/055690ddf2466e98bba6 to your computer and use it in GitHub Desktop.
import Optim
function clogit_ll{R}(coeff::Vector{R}, x1, x2, x3, x4, x5, x6,
y1, y2, y3, y4, y5, y6,
T, nObs, nVar)
llit = zero(R)
for i=1:nObs
for t=1:T
u1 = zero(R); u2 = zero(R); u3 = zero(R); u4 = zero(R); u5 = zero(R); u6 = zero(R)
for k=1:nVar
u1 += x1[i,k,t]*coeff[k]
u2 += x2[i,k,t]*coeff[k]
u3 += x3[i,k,t]*coeff[k]
u4 += x4[i,k,t]*coeff[k]
u5 += x5[i,k,t]*coeff[k]
u6 += x6[i,k,t]*coeff[k]
end
denom = exp(u1)
denom += exp(u2)
denom += exp(u3)
denom += exp(u4)
denom += exp(u5)
denom += exp(u6)
p1 = exp(u1)/denom
p2 = exp(u2)/denom
p3 = exp(u3)/denom
p4 = exp(u4)/denom
p5 = exp(u5)/denom
p6 = exp(u6)/denom
llit += log(p1)*y1[i,t]
llit += log(p2)*y2[i,t]
llit += log(p3)*y3[i,t]
llit += log(p4)*y4[i,t]
llit += log(p5)*y5[i,t]
llit += log(p6)*y6[i,t]
end
end
return -llit
end
const nChoices = 6 # Number of choices
const nVar = 4 # Number of variables describing each choice
const nObs = 2641 # Unique households
const T = 6 # Number of periods
file = open("testdata.csv")
data_raw = readcsv(file)
data = reshape(data_raw, nObs, nChoices*(1+nVar), T)
const y1 = data[:,1,:]
const y2 = data[:,2,:]
const y3 = data[:,3,:]
const y4 = data[:,4,:]
const y5 = data[:,5,:]
const y6 = data[:,6,:]
const X = data[:,7:end,:]
const x1 = X[:,(0*nVar+1):1*nVar,:]
const x2 = X[:,(1*nVar+1):2*nVar,:]
const x3 = X[:,(2*nVar+1):3*nVar,:]
const x4 = X[:,(3*nVar+1):4*nVar,:]
const x5 = X[:,(4*nVar+1):5*nVar,:]
const x6 = X[:,(5*nVar+1):6*nVar,:]
startval = ones(nVar)
res = Optim.optimize(param->clogit_ll(param,x1,x2,x3,x4,x5,x6,
y1,y2,y3,y4,y5,y6,T,nObs,nVar),
startval, method = :l_bfgs,
xtol = 1e-6, ftol = 1e-6, grtol = 1e-6,
show_trace = true, autodiff=true)
tic()
res = Optim.optimize(param->clogit_ll(param,x1,x2,x3,x4,x5,x6,
y1,y2,y3,y4,y5,y6,T,nObs,nVar),
startval, method = :l_bfgs,
xtol = 1e-6, ftol = 1e-6, grtol = 1e-6,
show_trace = true,autodiff=true)
toc()
println(res.minimum)
println(res.f_minimum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment