I would like to implement the EM algorithm for parameter estimation of a bivariate poisson model from Karlis 2003. The code is able to run, but I'm not very satisfied with the speed. I would like to ask for some ideas to speed up my code.
fitBivariatePoissonModel[x_?ListQ, init3_: 1, maxIteration_: 300,
prec_: 10^-8] :=
Block[{n = Length[x], s, like, zeroQ, lambda1 = 0., lambda2 = 0.,
lambda3 = init3, var1 = x[[All, 1]], var2 = x[[All, 2]],
difllike = 1000., loglike0 = 1000., i = 0, lbp1, lbp2, x1, x2,
loglike, loglikeli},
s = ConstantArray[0., n];
like = ConstantArray[0., n];
zeroQ = If[MemberQ[#, 0], 1., .0] & /@ x;
lambda1 = Max[0.1, Total[var1]/n*1.0 - lambda3];
lambda2 = Max[0.1, Total[var2]/n*1.0 - lambda3];
loglikeli = Reap[While[difllike > prec && i <= maxIteration,
i++;
lbp1 =
MapThread[
LogLikelihood[
MultivariatePoissonDistribution[
lambda3, {lambda1, lambda2}], {{#1 - 1, #2 - 1}}] &, {var1,
var2}];
lbp2 =
MapThread[
LogLikelihood[
MultivariatePoissonDistribution[
lambda3, {lambda1, lambda2}], {{#1, #2}}] &, {var1,
var2}];
s =
MapThread[
If[MemberQ[{#1, #2}, 0], 0,
Exp[Log[lambda3] +
LogLikelihood[
MultivariatePoissonDistribution[
lambda3, {lambda1, lambda2}], {{#1 - 1, #2 - 1}}] -
LogLikelihood[
MultivariatePoissonDistribution[
lambda3, {lambda1, lambda2}], {{#1, #2}}]]] &, {var1,
var2}];
like = MapThread[If[MemberQ[{#1, #2}, 0],
LogLikelihood[PoissonDistribution[lambda1], {#1}] +
LogLikelihood[PoissonDistribution[lambda2], {#2}] -
lambda3,
LogLikelihood[
MultivariatePoissonDistribution[
lambda3, {lambda1, lambda2}], {{#1, #2}}]] &, {var1,
var2}];
x1 = var1 - s;
x2 = var2 - s;
Sow[loglike = Total[like]];
difllike = Abs[(loglike0 - loglike)/loglike0];
loglike0 = loglike;
lambda1 = Mean[x1];
lambda2 = Mean[x2];
lambda3 = Mean[s]]][[2, 1]];
If[i == maxIteration + 1, Print["Maximum iterations reached"]];
Print[ListLinePlot[loglikeli]];
{lambda1, lambda2, lambda3, loglike0}]
A test evaluation of 100 samples took 30 seconds on my computer. Apparently, for large application, this evaluation speed is quite unsatisfied. Any ideas to accelerate would be appreciated.
l1 = Table[RandomInteger[{0, 10}, 2], {i, 100}];
fitBivariatePoissonModel[l1, 0.01, 500, 10^-8] // AbsoluteTiming
(* {38.5076, {4.84859, 5.34859, 0.00140634, -550.099}} *)
MultivariatePoissonDistribution
already, do you know you can get most of your answer viaEstimatedDistribution[l1, MultivariatePoissonDistribution[\[Mu], {\[Mu]1, \[Mu]2}]]
? $\endgroup$EstimatedDistribution
before. However I tested theEstimatedDistribution
. I found out that for simple cases like in the OPEstimatedDistribution
works quite well. However for complicated cases, e.g. some hierarchical models,MultivariatePoissonDistribution
is too complicated forEstimatedDistribution
and it never comes to a result. I guess the computational burden for MLE is too big. That's probably the reason why the paper proposed the EM algorithm. $\endgroup$