Esempio n. 1
0
    def _pairwise_gradients(self, pxs, nxs, kg_model):
        ep, tp = unzip_e_et(pxs)
        # indices of negative tuples
        en, tn = unzip_e_et(nxs)

        pscores = self._scores(ep, tp, kg_model)
        nscores = self._scores(en, tn, kg_model)

        ind = np.where(nscores + self.margin > pscores)[0]

        # all examples in batch satify margin criterion
        self.nviolations = len(ind)

        if len(ind) == 0:
            return

        ep = list(ep[ind])
        en = list(en[ind])
        tp = list(tp[ind])
        tn = list(tn[ind])

        pg = self.ET[tp] - kg_model.E[ep]
        ng = self.ET[tn] - kg_model.E[en]

        if self.l1:
            pg = np.sign(-pg)
            ng = -np.sign(-ng)
        else:
            raise NotImplementedError()

        # entity type gradients
        ridx, Sm, n = grad_sum_matrix(tp + tn)
        gr = Sm.dot(np.vstack((-pg, -ng))) / n

        return {'ET': (gr, ridx)}
Esempio n. 2
0
    def _pairwise_gradients(self, pxs, nxs):
        # indices of positive examples
        sp, pp, op = unzip_triples(pxs)
        # indices of negative examples
        sn, pn, on = unzip_triples(nxs)

        pscores = self.af.f(self._scores(sp, pp, op))
        nscores = self.af.f(self._scores(sn, pn, on))

        #print("avg = %f/%f, min = %f/%f, max = %f/%f" % (pscores.mean(), nscores.mean(), pscores.min(), nscores.min(), pscores.max(), nscores.max()))

        # find examples that violate margin
        ind = np.where(nscores + self.margin > pscores)[0]
        self.nviolations = len(ind)
        if len(ind) == 0:
            return

        # aux vars
        sp, sn = list(sp[ind]), list(sn[ind])
        op, on = list(op[ind]), list(on[ind])
        pp, pn = list(pp[ind]), list(pn[ind])
        gpscores = -self.af.g_given_f(pscores[ind])[:, np.newaxis]
        gnscores = self.af.g_given_f(nscores[ind])[:, np.newaxis]

        # object role gradients
        ridx, Sm, n = grad_sum_matrix(pp + pn)
        grp = gpscores * ccorr(self.E[sp], self.E[op])
        grn = gnscores * ccorr(self.E[sn], self.E[on])
        #gr = (Sm.dot(np.vstack((grp, grn))) + self.rparam * self.R[ridx]) / n
        gr = Sm.dot(np.vstack((grp, grn))) / n
        gr += self.rparam * self.R[ridx]

        # filler gradients
        eidx, Sm, n = grad_sum_matrix(sp + sn + op + on)
        geip = gpscores * ccorr(self.R[pp], self.E[op])
        gein = gnscores * ccorr(self.R[pn], self.E[on])
        gejp = gpscores * cconv(self.E[sp], self.R[pp])
        gejn = gnscores * cconv(self.E[sn], self.R[pn])
        ge = Sm.dot(np.vstack((geip, gein, gejp, gejn))) / n
        #ge += self.rparam * self.E[eidx]

        return {'E': (ge, eidx), 'R': (gr, ridx)}
Esempio n. 3
0
    def _gradients(self, xys):
        ss, ps, os, ys = unzip_triples(xys, with_ys=True)

        yscores = ys * self._scores(ss, ps, os)
        self.loss = np.sum(np.logaddexp(0, -yscores))
        #preds = af.Sigmoid.f(yscores)
        fs = -(ys * af.Sigmoid.f(-yscores))[:, np.newaxis]
        #self.loss -= np.sum(np.log(preds))

        ridx, Sm, n = grad_sum_matrix(ps)
        gr = Sm.dot(fs * ccorr(self.E[ss], self.E[os])) / n
        gr += self.rparam * self.R[ridx]

        eidx, Sm, n = grad_sum_matrix(list(ss) + list(os))
        ge = Sm.dot(
            np.vstack((fs * ccorr(self.R[ps], self.E[os]),
                       fs * cconv(self.E[ss], self.R[ps])))) / n
        ge += self.rparam * self.E[eidx]

        return {'E': (ge, eidx), 'R': (gr, ridx)}
Esempio n. 4
0
    def _pairwise_gradients(self, pxs, nxs):
        # indices of positive triples
        sp, pp, op = unzip_triples(pxs)
        # indices of negative triples
        sn, pn, on = unzip_triples(nxs)

        pscores = self._scores(sp, pp, op)
        nscores = self._scores(sn, pn, on)
        ind = np.where(nscores + self.margin > pscores)[0]

        # all examples in batch satify margin criterion
        self.nviolations = len(ind)
        if len(ind) == 0:
            return

        sp = list(sp[ind])
        sn = list(sn[ind])
        pp = list(pp[ind])
        pn = list(pn[ind])
        op = list(op[ind])
        on = list(on[ind])

        pg = self.E[op] - self.R[pp] - self.E[sp]
        ng = self.E[on] - self.R[pn] - self.E[sn]

        if self.l1:
            pg = np.sign(-pg)
            ng = -np.sign(-ng)
        else:
            raise NotImplementedError()

        # entity gradients
        eidx, Sm, n = grad_sum_matrix(sp + op + sn + on)
        ge = Sm.dot(np.vstack((pg, -pg, ng, -ng))) / n

        # relation gradients
        ridx, Sm, n = grad_sum_matrix(pp + pn)
        gr = Sm.dot(np.vstack((pg, ng))) / n
        return {'E': (ge, eidx), 'R': (gr, ridx)}
Esempio n. 5
0
    def _gradients(self, xys):
        ss, ps, os, ys = unzip_triples(xys, with_ys=True)

        # define memoized functions to cache expensive dot products
        # helps only if xys have repeated (s,p) or (p,o) pairs
        # this happens with sampling
        @memoized
        def _EW(s, o, p):
            return dot(self.E[s], self.W[p])

        @memoized
        def _WE(s, o, p):
            return dot(self.W[p], self.E[o])

        EW = np.array([_EW(*x) for (x, _) in xys])
        WE = np.array([_WE(*x) for (x, _) in xys])
        yscores = ys * np.sum(self.E[ss] * WE, axis=1)
        self.loss = np.sum(np.logaddexp(0, -yscores))
        fs = -(ys * af.Sigmoid.f(-yscores))[:, np.newaxis]
        #preds = af.Sigmoid.f(scores)
        #fs = -(ys / (1 + np.exp(yscores)))[:, np.newaxis]
        #self.loss -= np.sum(ys * np.log(preds))

        #fs = (scores - ys)[:, np.newaxis]
        #self.loss += np.sum(fs * fs)

        pidx = np.unique(ps)
        gw = np.zeros((len(pidx), self.ncomp, self.ncomp))
        for i in range(len(pidx)):
            p = pidx[i]
            ind = np.where(ps == p)[0]
            if len(ind) == 1:
                gw[i] += fs[ind] * np.outer(self.E[ss[ind]], self.E[os[ind]])
            else:
                gw[i] += dot(self.E[ss[ind]].T,
                             fs[ind] * self.E[os[ind]]) / len(ind)
            gw[i] += self.rparam * self.W[p]

        eidx, Sm, n = grad_sum_matrix(list(ss) + list(os))
        ge = Sm.dot(np.vstack((fs * WE, fs * EW))) / n
        ge += self.rparam * self.E[eidx]

        return {'E': (ge, eidx), 'W': (gw, pidx)}
Esempio n. 6
0
    def _pairwise_gradients(self, pxs, nxs):
        # indices of positive examples
        sp, pp, op = unzip_triples(pxs)
        # indices of negative examples
        sn, pn, on = unzip_triples(nxs)

        pxs, _ = np.array(list(zip(*pxs)))
        nxs, _ = np.array(list(zip(*nxs)))

        # define memoized functions to cache expensive dot products
        # helps only if xys have repeated (s,p) or (p,o) pairs
        # this happens with sampling
        @memoized
        def _EW(s, o, p):
            return dot(self.E[s], self.W[p])

        @memoized
        def _WE(s, o, p):
            return dot(self.W[p], self.E[o])

        WEp = np.array([_WE(*x) for x in pxs])
        WEn = np.array([_WE(*x) for x in nxs])
        pscores = self.af.f(np.sum(self.E[sp] * WEp, axis=1))
        nscores = self.af.f(np.sum(self.E[sn] * WEn, axis=1))

        #print("avg = %f/%f, min = %f/%f, max = %f/%f" % (pscores.mean(), nscores.mean(), pscores.min(), nscores.min(), pscores.max(), nscores.max()))

        # find examples that violate margin
        ind = np.where(nscores + self.margin > pscores)[0]
        self.nviolations = len(ind)
        if len(ind) == 0:
            return

        # aux vars
        gpscores = -self.af.g_given_f(pscores)[:, np.newaxis]
        gnscores = self.af.g_given_f(nscores)[:, np.newaxis]

        pidx = np.unique(list(pp) + list(pn))
        gw = np.zeros((len(pidx), self.ncomp, self.ncomp))
        for pid in range(len(pidx)):
            p = pidx[pid]
            ppidx = np.where(pp == p)
            npidx = np.where(pn == p)
            assert (len(ppidx) == len(npidx))
            if len(ppidx) == 0 and len(npidx) == 0:
                continue
            gw[pid] += dot(self.E[sp[ppidx]].T,
                           gpscores[ppidx] * self.E[op[ppidx]])
            gw[pid] += dot(self.E[sn[npidx]].T,
                           gnscores[npidx] * self.E[on[npidx]])
            gw[pid] += self.rparam * self.W[p]
            gw[pid] /= (len(ppidx) + len(npidx))

        # entity gradients
        sp, sn = list(sp[ind]), list(sn[ind])
        op, on = list(op[ind]), list(on[ind])
        gpscores, gnscores = gpscores[ind], gnscores[ind]
        EWp = np.array([_EW(*x) for x in pxs[ind]])
        EWn = np.array([_EW(*x) for x in nxs[ind]])
        eidx, Sm, n = grad_sum_matrix(sp + sn + op + on)
        ge = (Sm.dot(
            np.vstack(
                (gpscores * WEp[ind], gnscores * WEn[ind], gpscores * EWp,
                 gnscores * EWn))) + self.rparam * self.E[eidx]) / n

        return {'E': (ge, eidx), 'W': (gw, pidx)}