Esempio n. 1
0
 def toMode(self,j):
     """Return a mode declaration for the j-th goal of the rule"""
     goal = self.rule.rhs[j]
     def argIOMode(x): 
         return 'i' if x in self.goalDict[j].inputs else 'o'
     def argOnehotMode(x): 
         if (not parser.isVariableAtom(x)) or self.varDict[x].onehot: return '1'
         else: return ''
     return tensorlog.ModeDeclaration(parser.Goal(goal.functor, [argIOMode(x)+argOnehotMode(x) for x in goal.args]))
Esempio n. 2
0
    def toMode(self, j):
        """Return a mode declaration for the j-th goal of the rule"""
        goal = self.goals[j]
        gin = self.goalDict[j]

        def argIOMode(x):
            if x in gin.inputs: return 'i'
            elif x in gin.outputs: return 'o'
            else:
                assert x != 'i' and x != 'o' and x != 'i1' and x != 'i2', 'Illegal to use constants i,o,i1,o1 in a program'
                return x

        return tensorlog.ModeDeclaration(
            parser.Goal(goal.functor, [argIOMode(x) for x in goal.args]))
Esempio n. 3
0
    def propprInferenceCheck(self, weightVec, ruleStrings, modeString,
                             inputSymbol, expectedResultDict):
        print 'testing inference for mode', modeString, 'on input', inputSymbol, 'with proppr rules:'
        rules = parser.RuleCollection()
        for r in ruleStrings:
            rules.add(parser.Parser.parseRule(r))
        prog = tensorlog.ProPPRProgram(db=self.db,
                                       rules=rules,
                                       weights=weightVec)
        mode = tensorlog.ModeDeclaration(modeString)
        fun = prog.compile(mode)

        print 'native computation'
        y1 = self.only(prog.eval(mode, [inputSymbol]))
        self.checkDicts(self.db.rowAsSymbolDict(y1), expectedResultDict)
        print 'theano computation'
        thFun = prog.theanoPredictFunction(mode, ['x'])
        y2 = self.only(thFun(self.db.onehot(inputSymbol)))
        self.checkDicts(self.db.rowAsSymbolDict(y2), expectedResultDict)
Esempio n. 4
0
def fbModes():
    modes = []
    for line in open("test/fb15k-valid.preds"):
        pred = line.strip()
        modes.append(tensorlog.ModeDeclaration("%s(i,o)" % pred))
    return modes
Esempio n. 5
0
#

p = tensorlog.ProPPRProgram.load(
    ["test/textcat.ppr", "test/textcattoy.cfacts"])
p.setWeights(p.db.ones())
p.listing()

#
# load the data
#

xs, ys = loadExamples("test/textcattoy-train.examples", p.db)

#returns inputs and outputs that are used to build the prediction
#function
mode = tensorlog.ModeDeclaration('predict(i,o)')
ins, outs = p.theanoPredictExpr(mode, ['x'])
scorex = outs[0]  #the actual score vector for x

# something simple to try differentiating
toyLoss = B.sp_sum(scorex, sparse_grad=True)
print 'gradToyLoss...'
gradToyLoss = T.grad(toyLoss, p.getParamList())

#
# now define a theano function that computes loss for ONE example
#
y = S.csr_matrix('y')
prob = scorex * (1.0 / B.sp_sum(scorex, sparse_grad=True))  #scale x to 0-1
loss = B.sp_sum(-y * B.structured_log(prob),
                sparse_grad=True)  #cross-entropy loss
Esempio n. 6
0
        print 'compiled to:'
        for op in self.ops:
            print '\t',op

#
# a test driver
#

if __name__ == "__main__":
    if len(sys.argv)<2:
        print 'usage: rule mode'
        sys.exit(-1)

    STRICT = False
    p = parser.Parser()

    ruleString = sys.argv[1]
    rule = p.parseRule(ruleString)

    mode = tensorlog.ModeDeclaration(sys.argv[2])

    rules = parser.RuleCollection()
    rules.add(rule)
    prog = tensorlog.Program(db=None,rules=rules)
    c = OpCompiler(prog,0,rule)
    c.compile(mode)
    c.showRule()
    c.showVars()
    c.showOps()
    print 'incoming',map(str,c.incoming)
Esempio n. 7
0
#python try.py test/fam.cfacts 'p(i,o)' 'p(X,Y):-sister(X,Y) {r1}.' 'p(X,Y):-spouse(X,Y) {r2}.'

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print 'usage factfile mode rule1 ... x1 ... '
    else:
        db = matrixdb.MatrixDB.loadFile(sys.argv[1])
        mode = None
        rules = parser.RuleCollection()
        xs = []
        for a in sys.argv[2:]:
            if a.find(":-") >= 0:
                rules.add(parser.Parser.parseRule(a))
            elif a.find("(") >= 0:
                assert mode == None, 'only one mode allowed'
                mode = tensorlog.ModeDeclaration(a)
            else:
                xs.append(a)
        w = 7 * db.onehot('r1') + 3 * db.onehot('r2')
        p = tensorlog.ProPPRProgram(db=db, rules=rules, weights=w.transpose())
        p.ruleListing(mode)
        f = p.compile(mode)
        p.functionListing()

        for x in xs:
            print 'native result on input "%s":' % x
            result = p.eval(mode, [x])
            for val in result:
                print db.rowAsSymbolDict(val)
            print 'theano result on input "%s":' % x
            f = p.theanoPredictFunction(mode, ['x'])