|
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)) |
|
|
|
|