示例#1
0
def read_data(path, data_type, args):
    X = []
    y = []
    if data_type == 'deepwalk':
        word_vector = KeyedVectors.load_word2vec_format(path, binary=False)
        for word in word_vector.vocab:
            vector = word_vector[word]
            X.append(vector)
            y.append(int(word))
    if data_type == "transe":
        from models.transe import TransE as Model
        model = Model.load_model(path)
        ent_vocab = Vocab.load(args.ent)
        rel_vocab = Vocab.load(args.rel)

        valid_rels = np.random.randint(0, len(rel_vocab), args.n_cls)

        with open(args.kb) as f:
            for line in f:
                sub, rel, obj = line.strip().split('\t')
                sub_emb = model.pick_ent(ent_vocab[sub])
                obj_emb = model.pick_ent(ent_vocab[obj])
                rel_id = rel_vocab[rel]
                if (args.n_cls >= len(rel_vocab)) or (rel_id in valid_rels):
                    X.append(sub_emb - obj_emb)
                    y.append(rel_id)
    else:
        word_vector = KeyedVectors.load_word2vec_format(path, binary=False)
        ent_vocab = Vocab.load(args.ent)
        rel_vocab = Vocab.load(args.rel)

        def pick_emb(eid):
            if str(eid) in word_vector:
                return word_vector[str(eid)]
            else:
                return np.array([0.0 for i in range(len(word_vector[0]))])

        with open(args.kb) as f:
            for line in f:
                sub, rel, obj = line.strip().split('\t')
                sub_emb = pick_emb(ent_vocab[sub])
                obj_emb = pick_emb(ent_vocab[obj])
                rel_id = rel_vocab[rel]
                valid_rels = np.random.randint(0, len(rel_vocab), args.n_cls)
                if (args.n_cls >= len(rel_vocab)) or (rel_id in valid_rels):
                    X.append(sub_emb - obj_emb)
                    y.append(rel_id)

    return np.array(X), np.array(y)
示例#2
0
def test(args):
    ent_vocab = Vocab.load(args.ent)
    rel_vocab = Vocab.load(args.rel)

    # preparing data
    if args.task == 'kbc':
        test_dat = TripletDataset.load(args.data, ent_vocab, rel_vocab)
    elif args.task == 'tc':
        test_dat = LabeledTripletDataset.load(args.data, ent_vocab, rel_vocab)
    else:
        raise ValueError('Invalid task: {}'.format(args.task))

    print('loading model...')
    if args.method == 'transe':
        from models.transe import TransE as Model
    elif args.method == 'complex':
        from models.complex import ComplEx as Model
    elif args.method == 'analogy':
        from models.analogy import ANALOGY as Model
    else:
        raise NotImplementedError

    if args.filtered:
        print('loading whole graph...')
        from utils.graph import TensorTypeGraph
        graphall = TensorTypeGraph.load_from_raw(args.graphall, ent_vocab,
                                                 rel_vocab)
        # graphall = TensorTypeGraph.load(args.graphall)
    else:
        graphall = None

    model = Model.load_model(args.model)

    if args.metric == 'all':
        evaluator = Evaluator('all', None, args.filtered, False, graphall)
        if args.filtered:
            evaluator.prepare_valid(test_dat)

        all_res = evaluator.run_all_matric(model, test_dat)
        for metric in sorted(all_res.keys()):
            print('{:20s}: {}'.format(metric, all_res[metric]))
    else:
        evaluator = Evaluator(args.metric, None, False, True, None)
        res = evaluator.run(model, test_dat)
        print('{:20s}: {}'.format(args.metric, res))
示例#3
0
文件: train.py 项目: shaoyx/kbc
def train(args):
    # setting for logging
    if not os.path.exists(args.log):
        os.mkdir(args.log)
    logger = logging.getLogger()
    logging.basicConfig(level=logging.INFO)
    log_path = os.path.join(args.log, 'log')
    file_handler = logging.FileHandler(log_path)
    fmt = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    file_handler.setFormatter(fmt)
    logger.addHandler(file_handler)

    # TODO: develop the recording of arguments in logging
    logger.info('Arguments...')
    for arg, val in sorted(vars(args).items()):
        logger.info('{:>10} -----> {}'.format(arg, val))

    ent_vocab = Vocab.load(args.ent)
    rel_vocab = Vocab.load(args.rel)
    n_entity, n_relation = len(ent_vocab), len(rel_vocab)

    # preparing data
    logger.info('preparing data...')
    train_dat = TripletDataset.load(args.train, ent_vocab, rel_vocab)
    valid_dat = TripletDataset.load(args.valid, ent_vocab, rel_vocab) if args.valid else None

    if args.filtered:
        logger.info('loading whole graph...')
        from utils.graph import TensorTypeGraph
        whole_graph = TensorTypeGraph.load_from_raw(args.graphall, ent_vocab, rel_vocab)
    else:
        whole_graph = None

    if args.opt == 'sgd':
        opt = SGD(args.lr)
    elif args.opt == 'adagrad':
        opt = Adagrad(args.lr)
    elif args.opt == 'dsgd':
        opt = DecaySGD(args.lr)
    else:
        raise NotImplementedError

    if args.l2_reg > 0:
        opt.set_l2_reg(args.l2_reg)
    if args.gradclip > 0:
        opt.set_gradclip(args.gradclip)

    logger.info('building model...')
    if args.method == 'complex':
        from models.complex import ComplEx
        model = ComplEx(n_entity=n_entity,
                        n_relation=n_relation,
                        margin=args.margin,
                        dim=args.dim,
                        mode=args.mode)
    elif args.method == 'distmult':
        from models.distmult import DistMult
        model = DistMult(n_entity=n_entity,
                         n_relation=n_relation,
                         margin=args.margin,
                         dim=args.dim,
                         mode=args.mode)
    elif args.method == 'transe':
        from models.transe import TransE
        model = TransE(n_entity=n_entity,
                       n_relation=n_relation,
                       margin=args.margin,
                       dim=args.dim,
                       mode=args.mode)
    elif args.method == 'hole':
        from models.hole import HolE
        model = HolE(n_entity=n_entity,
                     n_relation=n_relation,
                     margin=args.margin,
                     dim=args.dim,
                     mode=args.mode)
    elif args.method == 'rescal':
        from models.rescal import RESCAL
        model = RESCAL(n_entity=n_entity,
                       n_relation=n_relation,
                       margin=args.margin,
                       dim=args.dim,
                       mode=args.mode)
    elif args.method == 'analogy':
        from models.analogy import ANALOGY
        model = ANALOGY(n_entity=n_entity,
                        n_relation=n_relation,
                        margin=args.margin,
                        dim=args.dim,
                        cp_ratio=args.cp_ratio,
                        mode=args.mode)
    elif args.method == 'transe_set':
        from models.transe_set import TransE_set
        model = TransE_set(n_entity=n_entity,
                       n_relation=n_relation,
                       margin=args.margin,
                       dim=args.dim,
                       mode=args.mode)
    elif args.method == 'line':
        from models.line_model import LineModel
        model = LineModel(n_entity=n_entity,
                       n_relation=n_relation,
                       margin=args.margin,
                       dim=args.dim,
                       mode=args.mode)

    else:
        raise NotImplementedError

    # evaluator = Evaluator(args.metric, args.nbest, args.filtered, whole_graph) if args.valid or args.synthetic else None
    evaluator = Evaluator(args.metric, args.nbest, args.filtered, whole_graph) if args.valid else None
    # delete args.synthetic to run
    if args.filtered and args.valid:
        evaluator.prepare_valid(valid_dat)
    if args.mode == 'pairwise':
        trainer = PairwiseTrainer(model=model, opt=opt, save_step=args.save_step,
                                  batchsize=args.batch, logger=logger,
                                  evaluator=evaluator, valid_dat=valid_dat,
                                  n_negative=args.negative, epoch=args.epoch,
                                  model_dir=args.log)
    elif args.mode == 'single':
        trainer = SingleTrainer(model=model, opt=opt, save_step=args.save_step,
                                batchsize=args.batch, logger=logger,
                                evaluator=evaluator, valid_dat=valid_dat,
                                n_negative=args.negative, epoch=args.epoch,
                                model_dir=args.log)
    else:
        raise NotImplementedError

    trainer.fit(train_dat)

    logger.info('done all')
def train(args):
    # setting for logging
    if not os.path.exists(args.log):
        os.mkdir(args.log)
    logger = logging.getLogger()
    logging.basicConfig(level=logging.INFO)
    log_path = os.path.join(args.log, 'log')
    file_handler = logging.FileHandler(log_path)
    fmt = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    file_handler.setFormatter(fmt)
    logger.addHandler(file_handler)

    # TODO: develop the recording of arguments in logging
    logger.info('Arguments...')
    for arg, val in vars(args).items():
        logger.info('{:>10} -----> {}'.format(arg, val))

    ent_vocab = Vocab.load(args.ent)
    rel_vocab = Vocab.load(args.rel)
    n_entity, n_relation = len(ent_vocab), len(rel_vocab)

    # preparing data
    logger.info('preparing data...')
    train_dat = TripletDataset.load(args.train, ent_vocab, rel_vocab)
    valid_dat = TripletDataset.load(args.valid, ent_vocab,
                                    rel_vocab) if args.valid else None

    if args.filtered:
        logger.info('loading whole graph...')
        from utils.graph import TensorTypeGraph
        whole_graph = TensorTypeGraph.load_from_raw(args.graphall, ent_vocab,
                                                    rel_vocab)
    else:
        whole_graph = None

    if args.opt == 'sgd':
        opt = SGD(args.lr)
    elif args.opt == 'adagrad':
        opt = Adagrad(args.lr)
    else:
        raise NotImplementedError

    if args.l2_reg > 0:
        opt.set_l2_reg(args.l2_reg)
    if args.gradclip > 0:
        opt.set_gradclip(args.gradclip)

    logger.info('building model...')
    if args.method == 'complex':
        from models.complex import ComplEx
        model = ComplEx(n_entity=n_entity,
                        n_relation=n_relation,
                        margin=args.margin,
                        dim=args.dim,
                        mode=args.mode)
    elif args.method == 'distmult':
        from models.distmult import DistMult
        model = DistMult(n_entity=n_entity,
                         n_relation=n_relation,
                         margin=args.margin,
                         dim=args.dim,
                         mode=args.mode)
    elif args.method == 'transe':
        from models.transe import TransE
        model = TransE(n_entity=n_entity,
                       n_relation=n_relation,
                       margin=args.margin,
                       dim=args.dim,
                       mode=args.mode)
    elif args.method == 'hole':
        from models.hole import HolE
        model = HolE(n_entity=n_entity,
                     n_relation=n_relation,
                     margin=args.margin,
                     dim=args.dim,
                     mode=args.mode)
    elif args.method == 'rescal':
        from models.rescal import RESCAL
        model = RESCAL(n_entity=n_entity,
                       n_relation=n_relation,
                       margin=args.margin,
                       dim=args.dim,
                       mode=args.mode)
    elif args.method == 'analogy':
        from models.analogy import ANALOGY
        model = ANALOGY(n_entity=n_entity,
                        n_relation=n_relation,
                        margin=args.margin,
                        dim=args.dim,
                        cp_ratio=args.cp_ratio,
                        mode=args.mode)
    elif args.method == 'randwalk':
        from models.randwalk import RandWalk
        logger.info(
            'using random walk model to learning embedding unsupervisedly.')
        model = RandWalk(n_entity=n_entity,
                         n_relation=n_relation,
                         knowledge_path=args.train,
                         ent_vocab=ent_vocab,
                         rel_vocab=rel_vocab,
                         dim=args.dim,
                         output=args.log)
        model.train()
        model.save_model(os.path.join(args.log, model.__class__.__name__))
        return
    elif args.method == "lr":
        from models.lr import LogisticReg
        model = LogisticReg(n_entity=n_entity,
                            n_relation=n_relation,
                            train_path=args.train,
                            ent_vocab=ent_vocab,
                            rel_vocab=rel_vocab,
                            dim=args.dim,
                            output=args.log,
                            wv_model_path=args.wv_model,
                            negative=args.negative,
                            feat_type=args.feat_type)
        starttime = time()
        if args.mode == "triplet_cls":
            logger.info("Training a triple classifer")
            model.train_triple_classifer()
        else:
            model.train()
        endtime = time()
        logger.info("lr model train time {:.6f}".format(endtime - starttime))
        model.save_model(os.path.join(args.log, model.__class__.__name__))
        return
    else:
        raise NotImplementedError

    evaluator = Evaluator(
        args.metric, args.nbest, args.filtered,
        whole_graph) if args.valid or args.synthetic else None
    if args.filtered and args.valid:
        evaluator.prepare_valid(valid_dat)
    if args.mode == 'pairwise':
        trainer = PairwiseTrainer(model=model,
                                  opt=opt,
                                  save_step=args.save_step,
                                  batchsize=args.batch,
                                  logger=logger,
                                  evaluator=evaluator,
                                  valid_dat=valid_dat,
                                  n_negative=args.negative,
                                  epoch=args.epoch,
                                  model_dir=args.log)
    elif args.mode == 'single':
        trainer = SingleTrainer(model=model,
                                opt=opt,
                                save_step=args.save_step,
                                batchsize=args.batch,
                                logger=logger,
                                evaluator=evaluator,
                                valid_dat=valid_dat,
                                n_negative=args.negative,
                                epoch=args.epoch,
                                model_dir=args.log)
    else:
        raise NotImplementedError

    trainer.fit(train_dat)

    logger.info('done all')