File size: 2,658 Bytes
bd607ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import json
import os
from itertools import product
from statistics import mean

import pandas as pd
from datasets import load_dataset


def process(name, split, output):
    data = load_dataset("relbert/t_rex", name, split=split)
    df = data.to_pandas()
    df.pop('text')
    df.pop('title')
    df['pairs'] = [[i, j] for i, j in zip(df.pop('subject'), df.pop('object'))]
    rel_sim_data = [{
        "relation_type": pred,
        "positives": g['pairs'].values.tolist(),
        "negatives": df[df.predicate != pred]['pairs'].values.tolist()
    } for pred, g in df.groupby("predicate") if len(g) >= 2]
    with open(output, "w") as f:
        f.write('\n'.join([json.dumps(i) for i in rel_sim_data]))


parameters_min_e_freq = [1, 2, 3, 4]
parameters_max_p_freq = [100, 50, 25, 10]
os.makedirs("data", exist_ok=True)

for min_e_freq, max_p_freq in product(parameters_min_e_freq, parameters_max_p_freq):
    for s in ['train', 'validation']:
        process(
            name=f"filter_unified.min_entity_{min_e_freq}_max_predicate_{max_p_freq}",
            split=s,
            output=f"data/filter_unified.min_entity_{min_e_freq}_max_predicate_{max_p_freq}.{s}.jsonl")

process(
    name=f"filter_unified.min_entity_{min_e_freq}_max_predicate_{max_p_freq}",
    split='test',
    output=f"data/filter_unified.test.jsonl")


stats = []
for min_e_freq, max_p_freq in product(parameters_min_e_freq, parameters_max_p_freq):
    stats_tmp = {"data": f"filter_unified.min_entity_{min_e_freq}_max_predicate_{max_p_freq}"}
    for s in ['train', 'validation']:
        with open(f"data/filter_unified.min_entity_{min_e_freq}_max_predicate_{max_p_freq}.{s}.jsonl") as f:
            tmp = [json.loads(i) for i in f.read().split('\n') if len(i) > 0]
            stats_tmp[f'num of relation types ({s})'] = len(tmp)
            stats_tmp[f'average num of positive pairs ({s})'] = round(mean([len(i['positives']) for i in tmp]))
            stats_tmp[f'average num of negative pairs ({s})'] = round(mean([len(i['negatives']) for i in tmp]))
    stats.append(stats_tmp)
df_stats = pd.DataFrame(stats)
df_stats.index = df_stats.pop('data')
print(df_stats.to_markdown())

stats_tmp = {}
with open("data/filter_unified.test.jsonl") as f:
    tmp = [json.loads(i) for i in f.read().split('\n') if len(i) > 0]
    stats_tmp[f'num of relation types (test)'] = len(tmp)
    stats_tmp[f'average num of positive pairs (test)'] = round(mean([len(i['positives']) for i in tmp]))
    stats_tmp[f'average num of negative pairs (test)'] = round(mean([len(i['negatives']) for i in tmp]))
df_stats_test = pd.DataFrame([stats_tmp])
print(df_stats_test.to_markdown(index=False))