예제 #1
0
    def mssg(self, from_v, to_w, isMax=False):
        # collect all mssg arriving at v
        mess = []
        neighbors = self.adj[from_v]
        for n in neighbors:
            if n!=to_w:
                pos = self.adj[n].index(from_v)
                msg = self.delta[n][pos]
                mess.append(msg)

        # take the the initial Psi (and log if needed)
        d = copy.copy(self.factors[from_v])
        if isMax==True:
            d.values = np.log(d.values)

        # multiply/sum by incoming messages
        for ms in mess:
            if isMax==True:
                d = FactorOperations.sum(d, ms, False)
            else:
                d = FactorOperations.multiply(d, ms, True)

        # marginalized to setsep vars
        for n in d.variables:
            if n not in (self.box[from_v] & self.box[to_w]):
                if isMax==True:
                    d = FactorOperations.max_marginalize(d, n)
                else:
                    d = FactorOperations.marginalize(d, n)
        return d
예제 #2
0
def MAP_Word(word):
    chars = len(word['gT'])
    vall = [None]*chars
    for i in range(chars):
        vall[i] = Rvar.Rvar(i, 26)
    f = []
    for i in range(chars):
        f.append(singletonFactor(vall[i], word['img'][i]))
    for i in range(chars-1):
        f.append(pairwiseFactor(vall[i], vall[i+1]))
    for i in range(chars-2):
        f.append(tripletFactor(vall[i], vall[i+1], vall[i+2]))

    # choose the top two similar images
    ss = []
    for i in range(chars):
        for j in range(i+1, chars):
            ss.append([vall[i], vall[j], similarity(word['img'][i], word['img'][j])])
    ss = sorted(ss, key = lambda x: x[2])
    top1 = ss.pop()
    print top1
    f.append(image_simil_factor(top1[0], top1[1], top1[2]))
    top2 = ss.pop()
    print top2
    f.append(image_simil_factor(top2[0], top2[1], top2[2]))
    #alist.sort(key=lambda x: x.foo)
    #f1.append(image_simil_factor(vall[i], vall[j], word['img'][i], word['img'][j]))
    print '---', len(f)
    cc = CliqueTree.CliqueTree(f)
    print cc
    cc.calibrate(isMax=True)
    
    # BEWARE I AM assuming that I get exact unambiguous marginals
    # which in the generality of problems does not have to happen
    # that is why the checking at bottom is important
    sol = []
    for vari in vall:
        for beta in cc.beta:
            if vari in beta.variables:
                fu = copy.copy(beta)
                for g in (set(beta.variables) - set([vari])):
                    fu = FactorOperations.max_marginalize(fu, g)
                maxi = np.max(fu.values)
                sol.append(list(fu.values).index(maxi))
                break
    return sol