a b/test/cadec/cadec_eval.py
1
from gensim import models
2
import os
3
import sys
4
import torch
5
import numpy as np
6
from transformers import AutoTokenizer, AutoModel, AutoConfig
7
8
9
batch_size = 64
10
device = "cuda:1"
11
12
13
def main():
14
    filename = sys.argv[1]
15
    print(filename)
16
17
    bert_like = False
18
    if filename[-3:] in ["vec", "txt"]:
19
        W = load_vectors(filename, dev=False)
20
    elif filename[-3:] == "bin":
21
        W = load_vectors_bin(filename)
22
    else:
23
        bert_like = True
24
        try:
25
            config = AutoConfig.from_pretrained(filename)
26
            model = AutoModel.from_pretrained(
27
                filename, config=config).to(device)
28
        except BaseException:
29
            model = torch.load(os.path.join(
30
                filename, 'pytorch_model.bin')).to(device)
31
32
        try:
33
            model.output_hidden_states = False
34
        except BaseException:
35
            pass
36
37
        try:
38
            tokenizer = AutoTokenizer.from_pretrained(filename)
39
        except BaseException:
40
            tokenizer = AutoTokenizer.from_pretrained(
41
                os.path.join(filename, "../"))
42
43
    top_k = 3
44
    if bert_like:
45
        eval(model, tokenizer, './cadec/data/cadec', top_k=top_k, summary_method="CLS")
46
        eval(model, tokenizer, './cadec/data/cadec', top_k=top_k, summary_method="MEAN")
47
        eval(model, tokenizer, './cadec/data/psytar_disjoint_folds', top_k=top_k, summary_method="CLS")
48
        eval(model, tokenizer, './cadec/data/psytar_disjoint_folds', top_k=top_k, summary_method="MEAN")
49
    else:
50
        eval(W, None, './cadec/data/cadec', top_k=top_k)
51
        eval(W, None, './cadec/data/psytar_disjoint_folds', top_k=top_k)
52
53
54
def get_bert_embed(phrase_list, m, tok, normalize=True, summary_method="CLS"):
55
    input_ids = []
56
    for phrase in phrase_list:
57
        input_ids.append(tok.encode_plus(
58
            phrase, max_length=32, add_special_tokens=True,
59
            truncation=True, pad_to_max_length=True)['input_ids'])
60
    m.eval()
61
62
    count = len(input_ids)
63
    now_count = 0
64
    with torch.no_grad():
65
        while now_count < count:
66
            input_gpu_0 = torch.LongTensor(input_ids[now_count:min(
67
                now_count + batch_size, count)]).to(device)
68
            if summary_method == "CLS":
69
                embed = m(input_gpu_0)[1]
70
            if summary_method == "MEAN":
71
                embed = torch.mean(m(input_gpu_0)[0], dim=1)
72
            if normalize:
73
                embed_norm = torch.norm(
74
                    embed, p=2, dim=1, keepdim=True).clamp(min=1e-12)
75
                embed = embed / embed_norm
76
            embed_np = embed.cpu().detach().numpy()
77
            if now_count == 0:
78
                output = embed_np
79
            else:
80
                output = np.concatenate((output, embed_np), axis=0)
81
            now_count = min(now_count + batch_size, count)
82
    return output
83
84
85
def eval_one(m, tok, folder, top_k, summary_method=None):
86
    with open(os.path.join(folder, "standard.txt"), "r", encoding="utf-8") as f:
87
        lines = f.readlines()
88
    label2id = {line.strip().split(
89
        "\t")[0]: index for index, line in enumerate(lines)}
90
    standard_lines = [line.strip().split("\t") for line in lines]
91
    #standard_feat = np.array([get_bert_embed(text, m, tok) for (label, text) in standard_lines])
92
    if tok is not None:
93
        standard_feat = get_bert_embed(
94
            [text for (label, text) in standard_lines], m, tok, normalize=True, summary_method=summary_method)
95
    else:
96
        standard_feat = embed(
97
            [text for (label, text) in standard_lines], m.vector_size, m)
98
99
    with open(os.path.join(folder, "test.txt"), "r", encoding="utf-8") as f:
100
        lines = f.readlines()
101
    test_lines = [line.strip().split("\t") for line in lines]
102
    #test_feat = np.array([get_bert_embed(text, m, tok) for (label, text) in test_lines])
103
    if tok is not None:
104
        test_feat = get_bert_embed(
105
            [text for (label, text) in test_lines], m, tok, normalize=True, summary_method=summary_method)
106
    else:
107
        test_feat = embed(
108
            [text for (label, text) in test_lines], m.vector_size, m)
109
110
    sim_mat = np.dot(test_feat, standard_feat.T)
111
112
    correct_1 = 0
113
    correct_k = 0
114
    pred_top_k = torch.topk(torch.FloatTensor(sim_mat), k=top_k)[
115
        1].cpu().numpy()
116
    for i in range(len(test_lines)):
117
        true_id = label2id[test_lines[i][0]]
118
        if pred_top_k[i][0] == true_id:
119
            correct_1 += 1
120
        if true_id in list(pred_top_k[i]):
121
            correct_k += 1
122
    acc_1 = correct_1 / len(test_lines)
123
    acc_k = correct_k / len(test_lines)
124
    return acc_1, acc_k
125
126
127
def eval(m, tok, task_name, top_k=3, summary_method=None):
128
    acc_1_list = []
129
    acc_k_list = []
130
    for p in os.listdir(task_name):
131
        acc_1, acc_k = eval_one(m, tok, os.path.join(task_name, p), top_k, summary_method=summary_method)
132
        acc_1_list.append(acc_1)
133
        acc_k_list.append(acc_k)
134
    print(task_name, summary_method)
135
    print(f"top_k={top_k}")
136
    print(acc_1_list)
137
    print(acc_k_list)
138
    print(sum(acc_1_list) / 5, sum(acc_k_list) / 5)
139
140
    return None
141
142
143
def load_vectors(filename):
144
    W = {}
145
    with open(filename, 'r') as f:
146
        for i, line in enumerate(f.readlines()):
147
            if i == 0:
148
                continue
149
            toks = line.strip().split()
150
            w = toks[0]
151
            vec = np.array(map(float, toks[1:]))
152
            W[w] = vec
153
    return W
154
155
156
def load_vectors_bin(filename):
157
    w = models.KeyedVectors.load_word2vec_format(filename, binary=True)
158
    return w
159
160
161
def cosine(u, v):
162
    return np.dot(u, v)
163
164
165
def norm(v):
166
    return np.dot(v, v)**0.5
167
168
169
def embed_one(phrase, dim, W):
170
    words = phrase.split()
171
    vectors = [W[w] for w in words if (w in W)]
172
    v = sum(vectors, np.zeros(dim))
173
    return v / (norm(v) + 1e-9)
174
175
176
def embed(phrase_list, dim, W):
177
    return np.array([embed_one(phrase, dim, W) for phrase in phrase_list])
178
179
180
if __name__ == '__main__':
181
    main()