Home

Awesome

<div id="top"></div> <div align="center">

TFLEX: Temporal Feature-Logic Embedding Framework for Complex Reasoning over Temporal Knowledge Graph

PyTorch acceptance license

</div>

Code for "TFLEX: Temporal Feature-Logic Embedding Framework for Complex Reasoning over Temporal Knowledge Graph" accepted to NeurIPS 2023.

[OpenReview] [arXiv] [Dataset: Google Drive]

Multi-hop logical reasoning over knowledge graph (KG) plays a fundamental role in many artificial intelligence tasks. Recent complex query embedding (CQE) methods for reasoning focus on static KGs, while temporal knowledge graphs (TKGs) have not been fully explored. Reasoning over TKGs has two challenges: 1. The query should answer entities or timestamps; 2. The operators should consider both set logic on entity set and temporal logic on timestamp set. To bridge this gap, we define the multi-hop logical reasoning problem on TKGs. With generated three datasets, we propose the first temporal CQE named Temporal Feature-Logic Embedding framework (TFLEX) to answer the temporal complex queries. We utilize vector logic to compute the logic part of Temporal Feature-Logic embeddings, thus naturally modeling all First-Order Logic (FOL) operations on entity set. In addition, our framework extends vector logic on timestamp set to cope with three extra temporal operators (After, Before and Between). Experiments on numerous query patterns demonstrate the effectiveness of our method.

Below is a typical multi-hop temporal complex query and its computation graph: "During François Hollande was the president of France, which countries did Xi Jinping visit but Barack Obama did not visit?". In the computation graph, there are entity set (blue circle), timestamp set (green triangle), time set projection (green arrow), entity set projection (blue arrow) and logical operators (red rectangle).

πŸ”” News

🌍 Contents

πŸ”¬ 1. Install

pip install -r requirements.txt
cd assistance
pip install -e .
cd ..

πŸš€ 2. Get Started

❗NOTE: Download the datasets in Google Drive (~5G) and place in data folder.

./data
  - ICEWS14
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid
  - ICEWS05-15
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid
  - GDELT
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid

Then run the command to train TFLEX on ICEWS14:

$ python train_TCQE_TFLEX.py --name="TFLEX_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14" --data_home="./data"

$ python train_TCQE_TFLEX.py --help
Usage: train_TCQE_TFLEX.py [OPTIONS]

Options:
  --data_home TEXT                The folder path to dataset.
  --dataset TEXT                  Which dataset to use: ICEWS14, ICEWS05_15,
                                  GDELT.
  --name TEXT                     Name of the experiment.
  --start_step INTEGER            start step.
  --max_steps INTEGER             Number of steps.
  --every_test_step INTEGER       test every k steps
  --every_valid_step INTEGER      validation every k steps.
  --batch_size INTEGER            Batch size.
  --test_batch_size INTEGER       Test batch size. Scoring to all is memory
                                  consuming. We need small test batch size.
  --negative_sample_size INTEGER  negative entities sampled per query
  --train_device TEXT             choice: cuda:0, cuda:1, cpu.
  --test_device TEXT              choice: cuda:0, cuda:1, cpu.
  --resume BOOLEAN                Resume from output directory.
  --resume_by_score FLOAT         Resume by score from output directory.
                                  Resume best if it is 0. Default: 0
  --lr FLOAT                      Learning rate.
  --cpu_num INTEGER               used to speed up torch.dataloader
  --hidden_dim INTEGER            embedding dimension
  --input_dropout FLOAT           Input layer dropout.
  --gamma FLOAT                   margin in the loss
  --center_reg FLOAT              center_reg for ConE, center_reg balances the
                                  in_cone dist and out_cone dist
  --train_tasks TEXT              the tasks for training
  --train_all BOOLEAN             if training all, it will use all tasks in
                                  data.train_queries_answers
  --eval_tasks TEXT               the tasks for evaluation
  --eval_all BOOLEAN              if evaluating all, it will use all tasks in
                                  data.test_queries_answers
  --help                          Show this message and exit.
<details> <summary>πŸ‘ˆ πŸ”Ž Full commands for reproducing all results in the paper</summary>
# ICEWS14
CUDA_VISIBLE_DEVICES=0 python train_TCQE_TFLEX.py --name="TFLEX_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X+ConE.py --name="X+ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X-1F.py --name="X-1F_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_entity_logic.py --name="X_without_entity_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_time_logic.py --name="X_without_time_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_logic.py --name="X_without_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_Query2box.py --name="Query2box_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_BetaE.py --name="BetaE_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_ConE.py --name="ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14"

CUDA_VISIBLE_DEVICES=0 python train_TCQE_Query2box.py --name="Query2box_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14" --resume=True --eval_tasks="Pe,Pe2,Pe3,e2i,e3i"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_BetaE.py --name="BetaE_dim800_gamma15" --hidden_dim=800 --test_batch_size=32 --every_test_step=10000 --dataset="ICEWS14" --resume=True --eval_tasks="Pe,Pe2,Pe3,e2i,e3i,e2i_N,e3i_N,Pe_e2i_Pe_NPe,e2i_PeN,e2i_NPe,e2u,Pe_e2u"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_ConE.py --name="ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS14" --resume=True --eval_tasks="Pe,Pe2,Pe3,e2i,e3i,e2i_N,e3i_N,Pe_e2i_Pe_NPe,e2i_PeN,e2i_NPe,e2u,Pe_e2u"

# ICEWS05-15
CUDA_VISIBLE_DEVICES=0 python train_TCQE_TFLEX.py --name="TFLEX_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X+ConE.py --name="X+ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X-1F.py --name="X-1F_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_entity_logic.py --name="X_without_entity_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_time_logic.py --name="X_without_time_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_logic.py --name="X_without_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_Query2box.py --name="Query2box_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_BetaE.py --name="BetaE_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_ConE.py --name="ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=16 --every_test_step=10000 --dataset="ICEWS05_15"

# GDELT
CUDA_VISIBLE_DEVICES=0 python train_TCQE_TFLEX.py --name="TFLEX_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X+ConE.py --name="X+ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X-1F.py --name="X-1F_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_entity_logic.py --name="X_without_entity_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_time_logic.py --name="X_without_time_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_X_without_logic.py --name="X_without_logic_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_Query2box.py --name="Query2box_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_BetaE.py --name="BetaE_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
CUDA_VISIBLE_DEVICES=0 python train_TCQE_ConE.py --name="ConE_dim800_gamma15" --hidden_dim=800 --test_batch_size=64 --every_test_step=100000 --dataset="GDELT"
</details> <br/>

🎯 3. Results

<details open> <summary>πŸ‘ˆ πŸ”Ž Reported results</summary>

table1_main_results

</details>

To support your research, we also open source some of our LaTeX files. Full LaTeX files can be found in arXiv.

πŸ”¬ 4. Visualization

Please refer to notebook/Draw.ipynb to visualize the inference process of temporal complex queries.

πŸ€– 5. Interpreter

To launch an interactive interpreter, please run python run_reasoning_interpreter.py

use_dataset(data_home="/data/TFLEX/data"); use_embedding_reasoning_interpreter("TFLEX_dim800_gamma15", device="cuda:1");
sample(task_name="e2i", k=1);
emb_e1=entity_token(); emb_r1=relation_token(); emb_t1=timestamp_token();
emb_e2=entity_token(); emb_r2=relation_token(); emb_t2=timestamp_token();
emb_q1 = Pe(emb_e1, emb_r1, emb_t1)
emb_q2 = Pe(emb_e2, emb_r2, emb_t2)
emb_q = And(emb_q1, emb_q2)
embedding_answer_entities(emb_q, topk=3)
use_groundtruth_reasoning_interpreter()
groundtruth_answer()
OK. The bot correctly predict the hard answer which only exists in the test set!

πŸ“š 6. Dataset

<details> <summary>πŸ‘ˆ πŸ”Ž Data directory structure</summary>
./data
  - ICEWS14
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid
  - ICEWS05-15
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid
  - GDELT
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid
</details> <details> <summary>πŸ‘ˆ πŸ”Ž Dataset statistics: queries_count</summary>
queryICEWS14ICEWS05_15GDELT
trainvalidtesttrainvalidtesttrainvalidtest
Pe667838837884834404245829456441115102273842273432
Pe27282634824037368962100001000022153091000010000
Pe37282634924083368962100001000022153091000010000
e2i7282633053655368962100001000022153091000010000
e3i7282629663023368962100001000022153091000010000
Pt42690733174191427712879528752687326199780199419
aPt13234441144116826210000100002215301000010000
bPt13234441144116826210000100002215301000010000
Pe_Pt7282338536383689610000100002215301000010000
Pt_sPe_Pt13234554162936826210000100002215301000010000
Pt_oPe_Pt13234548062426826210000100002215301000010000
t2i7282651126631368962100001000022153091000010000
t3i7282630943296368962100001000022153091000010000
e2i_N7282294929753689610000100002215301000010000
e3i_N7282291329143689610000100002215301000010000
Pe_e2i_Pe_NPe7282296830123689610000100002215301000010000
e2i_PeN7282297130313689610000100002215301000010000
e2i_NPe7282306131923689610000100002215301000010000
t2i_N7282313533283689610000100002215301000010000
t3i_N7282292429443689610000100002215301000010000
Pe_t2i_PtPe_NPt7282303131273689610000100002215301000010000
t2i_PtN7282330036093689610000100002215301000010000
t2i_NPt7282487354643689610000100002215301000010000
e2u-29132913-1000010000-1000010000
Pe_e2u-29132913-1000010000-1000010000
t2u-29132913-1000010000-1000010000
Pe_t2u-29132913-1000010000-1000010000
t2i_Pe-29132913-1000010000-1000010000
Pe_t2i-29132913-1000010000-1000010000
e2i_Pe-29132913-1000010000-1000010000
Pe_e2i-29132913-1000010000-1000010000
between7282291329133689610000100002215301000010000
Pe_aPt7282413447336826210000100002215301000010000
Pe_bPt7282397045653689610000100002215301000010000
Pt_sPe7282497656083689610000100002215301000010000
Pt_oPe7282332136213689610000100002215301000010000
Pt_se2i7282322634663689610000100002215301000010000
Pt_oe2i7282323634853689610000100002215301000010000
Pe_at2i7282460753383689610000100002215301000010000
Pe_bt2i7282458353863689610000100002215301000010000
</details> <details> <summary>πŸ‘ˆ πŸ”Ž Dataset statistics: avg_answers_count</summary>
queryICEWS14ICEWS05_15GDELT
trainvalidtesttrainvalidtesttrainvalidtest
Pe1.091.011.011.071.011.012.071.211.21
Pe21.032.192.231.022.152.192.616.516.13
Pe31.042.252.291.022.182.215.1110.8610.70
e2i1.022.762.841.012.362.521.052.302.32
e3i1.001.571.591.001.261.261.001.201.35
Pt1.711.221.212.581.611.603.361.661.66
aPt177.99176.09175.892022.162003.851998.71156.48155.38153.41
bPt181.20179.88179.261929.981923.751919.83160.38159.29157.42
Pe_Pt1.587.908.622.8418.1120.6326.5642.5441.33
Pt_sPe_Pt1.797.267.472.4913.5110.864.9214.1312.80
Pt_oPe_Pt1.757.277.482.5513.0114.344.6214.4712.90
t2i1.196.296.383.0729.4525.611.978.987.76
t3i1.012.883.141.0810.0310.221.063.793.52
e2i_N1.022.102.141.012.052.082.044.664.58
e3i_N1.001.001.001.001.001.001.021.191.37
Pe_e2i_Pe_NPe1.042.212.251.022.162.193.678.548.12
e2i_PeN1.042.222.261.022.172.213.678.668.36
e2i_NPe1.183.033.111.122.872.994.008.157.81
t2i_N1.153.313.441.214.064.202.918.787.56
t3i_N1.001.021.031.011.021.021.153.193.20
Pe_t2i_PtPe_NPt1.082.592.701.082.472.624.1012.0211.37
t2i_PtN1.415.225.471.708.108.114.5612.5611.32
t2i_NPt8.1425.9626.2366.99154.01147.3417.5835.6032.22
e2u0.003.123.170.002.382.400.005.045.41
Pe_e2u0.002.382.440.001.241.250.009.3910.78
t2u0.004.354.530.005.575.920.009.7010.51
Pe_t2u0.002.722.830.001.241.280.009.9011.27
t2i_Pe0.001.031.030.001.011.020.001.341.44
Pe_t2i0.001.141.160.001.071.080.002.012.20
e2i_Pe0.001.001.000.001.001.000.001.071.10
Pe_e2i0.002.182.240.001.321.330.005.085.49
between122.61120.94120.271407.871410.391404.76214.16210.99207.85
Pe_aPt4.6716.7316.5018.6843.8046.2349.3166.2168.88
Pe_bPt4.5317.0716.8018.7045.8148.2367.6784.7983.00
Pt_sPe8.6528.8629.2271.51162.36155.4627.5545.8343.73
Pt_oPe1.415.235.461.688.368.213.8411.3110.06
Pt_se2i1.315.726.191.379.009.302.768.727.66
Pt_oe2i1.326.517.001.4410.4910.892.558.177.27
Pe_at2i7.2622.6321.9830.4060.0353.1888.77101.60101.88
Pe_bt2i7.2721.9221.2330.3161.5964.9888.80100.64100.67
</details> <br/>

πŸ“š Explore the dataset

To speed up the training, we have preprocessed the dataset and cached the data in ./data/{dataset_name}/cache/. And we aim to provide a unified, human-friendly interface to access the dataset. That is, we need to annotate the type of each data object in the dataset and allow to access as attribution. The type annotation is friendly to IDE and can help us to avoid some bugs, otherwise, we won't know the type of object before loading it.

To inspect the dataset in jupyter notebook, we can use the following code:

from ComplexTemporalQueryData import ICEWS14, ICEWS05_15, GDELT
from ComplexTemporalQueryData import ComplexTemporalQueryDatasetCachePath, TemporalComplexQueryData

data_home = "./data"
if dataset_name == "ICEWS14":
    dataset = ICEWS14(data_home)
elif dataset_name == "ICEWS05_15":
    dataset = ICEWS05_15(data_home)
elif dataset_name == "GDELT":
    dataset = GDELT(data_home)
cache = ComplexTemporalQueryDatasetCachePath(dataset.cache_path)
data = TemporalComplexQueryData(dataset, cache_path=cache)
data.preprocess_data_if_needed()
data.load_cache([
    "meta",
    "all_timestamps",  # -> ./data/{dataset_name}/cache/all_timestamps.pkl
    "idx2entity",
    "test_queries_answers",
])
print(data.entity_count)  # with "meta" loaded
print(data.all_timestamps)  # directly access as attribution with cache "all_timestamps" loaded
print(data.test_queries_answers)  # all cache can be found in dir "./data/{dataset_name}/cache", specific in class ComplexTemporalQueryDatasetCachePath
<details> <summary>πŸ‘ˆ πŸ”Ž Available attribution and cache</summary>
# (s, r, o, t)
self.all_triples: List[Tuple[str, str, str, str]]
self.train_triples: List[Tuple[str, str, str, str]]
self.test_triples: List[Tuple[str, str, str, str]]
self.valid_triples: List[Tuple[str, str, str, str]]

# (s, r, o, t)
self.all_triples_ids: List[Tuple[int, int, int, int]]
self.train_triples_ids: List[Tuple[int, int, int, int]]
self.test_triples_ids: List[Tuple[int, int, int, int]]
self.valid_triples_ids: List[Tuple[int, int, int, int]]

self.all_relations: List[str]  # name
self.all_entities: List[str]
self.all_timestamps: List[str]
self.entities_ids: List[int]  # id, starting from 0
self.relations_ids: List[int]  # origin in [0, relation_count), reversed relation in [relation_count, 2*relation_count)
self.timestamps_ids: List[int]

self.entity2idx: Dict[str, int]
self.idx2entity: Dict[int, str]
self.relation2idx: Dict[str, int]
self.idx2relation: Dict[int, str]
self.timestamp2idx: Dict[str, int]
self.idx2timestamp: Dict[int, str]

# Dict[str, Dict[str, Union[List[str], List[Tuple[List[int], Set[int]]]]]]
#       |                       |                     |          |
#     structure name      args name list              |          |
#                                    ids corresponding to args   |
#                                                          answers id set
# 1. `structure name` is the name of a function (named query function), parsed to AST and eval to get results.
# 2. `args name list` is the arg list of query function.
# 3. train_queries_answers, valid_queries_answers and test_queries_answers are heavy to load (~10G+ memory)
#    we suggest to load by query task, e.g. load_cache_by_tasks(["Pe", "Pe2", "Pe3", "e2i", "e3i"], "train")
self.train_queries_answers: TYPE_train_queries_answers = {
    # "Pe_aPt": {
    #     "args": ["e1", "r1", "e2", "r2", "e3"],
    #     "queries_answers": [
    #         ([1, 2, 3, 4, 5], {2, 3, 5}),
    #         ([1, 2, 3, 4, 5], {2, 3, 5}),
    #         ([1, 2, 3, 4, 5], {2, 3, 5}),
    #     ]
    # }
    # >>> answers = Pe_aPt(1, 2, 3, 4, 5)
    # then, answers == {2, 3}
}
self.valid_queries_answers: TYPE_test_queries_answers = {
    # "Pe_aPt": {
    #     "args": ["e1", "r1", "e2", "r2", "e3"],
    #     "queries_answers": [
    #         ([1, 2, 3, 4, 5], {2, 3}, {2, 3, 5}),
    #         ([1, 2, 3, 4, 5], {2, 3}, {2, 3, 5}),
    #         ([1, 2, 3, 4, 5], {2, 3}, {2, 3, 5}),
    #     ]
    # }
    # >>> answers = Pe_aPt(1, 2, 3, 4, 5)
    # in training set, answers == {2, 3}
    # in validation set, answers == {2, 3, 5}, harder and more complete
}
self.test_queries_answers: TYPE_test_queries_answers = {
    # "Pe_aPt": {
    #     "args": ["e1", "r1", "e2", "r2", "e3"],
    #     "queries_answers": [
    #         ([1, 2, 3, 4, 5], {2, 3, 5}, {2, 3, 5, 6}),
    #         ([1, 2, 3, 4, 5], {2, 3, 5}, {2, 3, 5, 6}),
    #         ([1, 2, 3, 4, 5], {2, 3, 5}, {2, 3, 5, 6}),
    #     ]
    # }
    # >>> answers = Pe_aPt(1, 2, 3, 4, 5)
    # in training and validation set, answers == {2, 3}
    # in testing set, answers == {2, 3, 5}, harder and more complete
}

# meta info
# `load_cache(["meta"])` will load below all.
self.query_meta = {
    # "Pe_aPt": {
    #     "queries_count": 1,
    #     "avg_answers_count": 1
    # }
}
self.entity_count: int
self.relation_count: int
self.timestamp_count: int
self.valid_triples_count: int
self.test_triples_count: int
self.train_triples_count: int
self.triple_count: int
</details>

or we can load or save the cache using pickle, bypassing the load_cache method:

import pickle

def cache_data(data, cache_path: Union[str, Path]):
    with open(str(cache_path), 'wb') as f:
        pickle.dump(data, f)


def read_cache(cache_path: Union[str, Path]):
    with open(str(cache_path), 'rb') as f:
        return pickle.load(f)

# or we can use
# from toolbox.data.functional import read_cache, cache_data
idx2entity = read_cache("./data/{dataset_name}/cache/idx2entity.pkl")
print(type(idx2entity))
cache_data(idx2entity, "./data/{dataset_name}/cache/idx2entity.pkl")

πŸ“š Customize your own TKG complex query dataset

To implement other temporal knowledge graph complex query datasets, we need to provide initial data files and customize a dataset schema class:

"""
./data
  - ICEWS14
    - cache
      - cache_xxx.pkl
      - cache_xxx.pkl
    - train
    - test
    - valid
"""
from toolbox.data.DatasetSchema import RelationalTripletDatasetSchema

class ICEWS14(RelationalTripletDatasetSchema):
    def __init__(self, home: Union[Path, str] = "data"):
        super(ICEWS14, self).__init__("ICEWS14", home)

    def get_data_paths(self) -> Dict[str, Path]:
        return {
            # provided initial data file
            # txt utf-8 format, ecah line is
            # "{subject_name}\t{relation_name}\t{object_name}\t{timestamp_name}\n"
            'train': self.get_dataset_path_child('train'),  # data/ICEWS14/train,
            'test': self.get_dataset_path_child('test'),  # data/ICEWS14/test
            'valid': self.get_dataset_path_child('valid'),  # data/ICEWS14/valid
        }

    def get_dataset_path(self):
        return self.root_path  # data root path = "data"

dataset = ICEWS14("./data")
print(dataset.root_path)  # data
print(dataset.dataset_path)  # data/ICEWS14, specific in get_dataset_path()
print(dataset.cache_path) # data/ICEWS14/cache

# then use it as is introduced above
cache = ComplexTemporalQueryDatasetCachePath(dataset.cache_path)
data = TemporalComplexQueryData(dataset, cache_path=cache)
...

To generate temporal complex queries (TCQs), we have a terminal user interface: python run_sampling_TCQs.py.

$ python run_sampling_TCQs.py --help
Usage: run_sampling_TCQs.py [OPTIONS]

Options:
  --data_home TEXT  The folder path to dataset.
  --dataset TEXT    Which dataset to use: ICEWS14, ICEWS05_15, GDELT.
  --help            Show this message and exit.

$ python run_sampling_TCQs.py --data_home data --dataset ICEWS14
preparing data
entities_ids 7128
relations_ids 230
timestamps_ids 365
Pe train 66783 valid 8837 test 8848
Pt train 42690 valid 7331 test 7419
...

To show the meta of the generated dataset, run python run_meta.py.

$ python run_meta.py --help
Usage: run_meta.py [OPTIONS]

Options:
  --data_home TEXT  The folder path to dataset.
  --help            Show this message and exit.

🀝 Citation

Please condiser citing this paper if you use the code or data from our work. Thanks a lot :)

(Xueyuan et al., 2023 preferred, instead of Lin et al., 2023)

@inproceedings{
  xueyuan2023tflex,
  title={TFLEX: Temporal Feature-Logic Embedding Framework for Complex Reasoning over Temporal Knowledge Graph},
  author={Lin Xueyuan and Haihong E and Chengjin Xu and Gengxian Zhou and Haoran Luo and Tianyi Hu and Fenglong Su and Ningyuan Li and Mingzhi Sun},
  booktitle={Thirty-seventh Conference on Neural Information Processing Systems},
  year={2023},
  url={https://openreview.net/forum?id=oaGdsgB18L}
}

TFLEX is released under the Apache License 2.0 license.

<p align="right">(<a href="#top">back to top</a>)</p>