Datasets:

Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
License:
File size: 2,967 Bytes
1bb8d13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
import os
import json
import pandas as pd
from statistics import mean
from datasets import load_dataset
from relbert import RelBERT


def cosine_similarity(a, b):
    norm_a = sum(map(lambda x: x * x, a)) ** 0.5
    norm_b = sum(map(lambda x: x * x, b)) ** 0.5
    return sum(map(lambda x: x[0] * x[1], zip(a, b))) / (norm_a * norm_b)


# load dataset
data = load_dataset("cardiffnlp/relentless_full", split="test")
full_result = []

for lm in ['relbert-roberta-base-nce-t-rex', 'relbert-roberta-base-nce-nell']:
    os.makedirs(f"./experiments/results/relbert/{lm}", exist_ok=True)
    scorer = None
    for d in data:
        ppl_file = f"experiments/results/relbert/{lm}/ppl.{d['relation_type'].replace(' ', '_').replace('/', '__')}.jsonl"
        anchor_embeddings = [(a, b) for a, b in d['positive_examples']]
        option_embeddings = [(x, y) for x, y in d['pairs']]

        if not os.path.exists(ppl_file):

            if scorer is None:
                scorer = RelBERT(f"relbert/{lm}")
            anchor_embeddings = scorer.get_embedding(d['positive_examples'])
            option_embeddings = scorer.get_embedding(d['pairs'], batch_size=64)
            similarity = [[cosine_similarity(a, b) for b in anchor_embeddings] for a in option_embeddings]
            output = [{"similarity": s} for s in similarity]
            with open(ppl_file, "w") as f:
                f.write("\n".join([json.dumps(i) for i in output]))

        with open(ppl_file) as f:
            similarity = [json.loads(i)['similarity'] for i in f.read().split("\n") if len(i) > 0]

        true_rank = d['ranks']
        assert len(true_rank) == len(similarity), f"Mismatch in number of examples: {len(true_rank)} vs {len(similarity)}"
        prediction = [max(s) for s in similarity]
        rank_map = {p: n for n, p in enumerate(sorted(prediction, reverse=True), 1)}
        prediction_max = [rank_map[p] for p in prediction]

        prediction = [min(s) for s in similarity]
        rank_map = {p: n for n, p in enumerate(sorted(prediction, reverse=True), 1)}
        prediction_min = [rank_map[p] for p in prediction]

        prediction = [mean(s) for s in similarity]
        rank_map = {p: n for n, p in enumerate(sorted(prediction, reverse=True), 1)}
        prediction_mean = [rank_map[p] for p in prediction]

        tmp = pd.DataFrame([true_rank, prediction_max, prediction_min, prediction_mean]).T
        cor_max = tmp.corr("spearman").values[0, 1]
        cor_min = tmp.corr("spearman").values[0, 2]
        cor_mean = tmp.corr("spearman").values[0, 3]
        full_result.append({"model": f"RelBERT\textsubscript{'{'}{lm.upper()}{'}'}", "relation_type": d['relation_type'], "correlation": cor_max})

df = pd.DataFrame(full_result)
df = df.pivot(columns="relation_type", index="model", values="correlation")
df['average'] = df.mean(1)
df.to_csv("experiments/results/relbert/relbert_misc.csv")
df = (100 * df).round()
print(df.to_markdown())
print(df.to_latex())