Sunday, September 11, 2011

Laplace mixture, bad code

Hm.  Is this a reasonable implementation of a laplace mixture? The try/except seems to be an ugly way of dealing with the fact that int/float don't return a length, but it gets around testing for what they are...

import numpy as np

def laplace_mix(loc, scale, size, pvals = None):
        dim = len(loc)
        if dim != len(scale):
            raise NameError("Different number of location and scale parameters.")
        dim = 1
        loc = [loc]
        scale = [scale]
    if pvals is None:
        pvals = [ 1/dim for i in range(dim) ]
    args = zip(loc, scale)
    indicate = np.random.multinomial(n=1, pvals=pvals, size=size)
    where = np.where(indicate == 1)[1]
    out = np.zeros(size)
    for i in range(size):
        out[i] = np.random.laplace( loc = loc[where[i]], scale = scale[where[i]], size = 1 )

I'm still curious if there is a way of avoiding the for loop via numpy magic, but this is not a performance bottleneck so...

No comments:

Post a Comment