|
| 1 | +# Copyright (c) 2017-present, Facebook, Inc. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | +# |
| 7 | + |
| 8 | +''' |
| 9 | +STS-{2012,2013,2014,2015,2016} (unsupervised) and |
| 10 | +STS-benchmark (supervised) tasks |
| 11 | +''' |
| 12 | + |
| 13 | +from __future__ import absolute_import, division, unicode_literals |
| 14 | + |
| 15 | +import os |
| 16 | +import io |
| 17 | +import numpy as np |
| 18 | +import logging |
| 19 | + |
| 20 | +from scipy.stats import spearmanr, pearsonr |
| 21 | + |
| 22 | +from senteval.utils import cosine |
| 23 | +from senteval.sick import SICKEval |
| 24 | + |
| 25 | + |
| 26 | +class STSEval(object): |
| 27 | + def loadFile(self, fpath): |
| 28 | + self.data = {} |
| 29 | + self.samples = [] |
| 30 | + |
| 31 | + for dataset in self.datasets: |
| 32 | + sent1, sent2 = zip(*[l.split("\t") for l in |
| 33 | + io.open(fpath + '/STS.input.%s.txt' % dataset, |
| 34 | + encoding='utf8').read().splitlines()]) |
| 35 | + raw_scores = np.array([x for x in |
| 36 | + io.open(fpath + '/STS.gs.%s.txt' % dataset, |
| 37 | + encoding='utf8') |
| 38 | + .read().splitlines()]) |
| 39 | + not_empty_idx = raw_scores != '' |
| 40 | + |
| 41 | + gs_scores = [float(x) for x in raw_scores[not_empty_idx]] |
| 42 | + sent1 = np.array([s.split() for s in sent1], dtype=object)[not_empty_idx] |
| 43 | + sent2 = np.array([s.split() for s in sent2], dtype=object)[not_empty_idx] |
| 44 | + |
| 45 | + # sort data by length to minimize padding in batcher |
| 46 | + sorted_data = sorted(zip(sent1, sent2, gs_scores), |
| 47 | + key=lambda z: (len(z[0]), len(z[1]), z[2])) |
| 48 | + sent1, sent2, gs_scores = map(list, zip(*sorted_data)) |
| 49 | + |
| 50 | + self.data[dataset] = (sent1, sent2, gs_scores) |
| 51 | + self.samples += sent1 + sent2 |
| 52 | + |
| 53 | + def do_prepare(self, params, prepare): |
| 54 | + if 'similarity' in params: |
| 55 | + self.similarity = params.similarity |
| 56 | + else: # Default similarity is cosine |
| 57 | + self.similarity = lambda s1, s2: np.nan_to_num(cosine(np.nan_to_num(s1), np.nan_to_num(s2))) |
| 58 | + return prepare(params, self.samples) |
| 59 | + |
| 60 | + def run(self, params, batcher): |
| 61 | + results = {} |
| 62 | + all_sys_scores = [] |
| 63 | + all_gs_scores = [] |
| 64 | + for dataset in self.datasets: |
| 65 | + sys_scores = [] |
| 66 | + input1, input2, gs_scores = self.data[dataset] |
| 67 | + for ii in range(0, len(gs_scores), params.batch_size): |
| 68 | + batch1 = input1[ii:ii + params.batch_size] |
| 69 | + batch2 = input2[ii:ii + params.batch_size] |
| 70 | + |
| 71 | + # we assume get_batch already throws out the faulty ones |
| 72 | + if len(batch1) == len(batch2) and len(batch1) > 0: |
| 73 | + enc1 = batcher(params, batch1) |
| 74 | + enc2 = batcher(params, batch2) |
| 75 | + |
| 76 | + for kk in range(enc2.shape[0]): |
| 77 | + sys_score = self.similarity(enc1[kk], enc2[kk]) |
| 78 | + sys_scores.append(sys_score) |
| 79 | + all_sys_scores.extend(sys_scores) |
| 80 | + all_gs_scores.extend(gs_scores) |
| 81 | + results[dataset] = {'pearson': pearsonr(sys_scores, gs_scores), |
| 82 | + 'spearman': spearmanr(sys_scores, gs_scores), |
| 83 | + 'nsamples': len(sys_scores)} |
| 84 | + logging.debug('%s : pearson = %.4f, spearman = %.4f' % |
| 85 | + (dataset, results[dataset]['pearson'][0], |
| 86 | + results[dataset]['spearman'][0])) |
| 87 | + |
| 88 | + weights = [results[dset]['nsamples'] for dset in results.keys()] |
| 89 | + list_prs = np.array([results[dset]['pearson'][0] for |
| 90 | + dset in results.keys()]) |
| 91 | + list_spr = np.array([results[dset]['spearman'][0] for |
| 92 | + dset in results.keys()]) |
| 93 | + |
| 94 | + avg_pearson = np.average(list_prs) |
| 95 | + avg_spearman = np.average(list_spr) |
| 96 | + wavg_pearson = np.average(list_prs, weights=weights) |
| 97 | + wavg_spearman = np.average(list_spr, weights=weights) |
| 98 | + all_pearson = pearsonr(all_sys_scores, all_gs_scores) |
| 99 | + all_spearman = spearmanr(all_sys_scores, all_gs_scores) |
| 100 | + results['all'] = {'pearson': {'all': all_pearson[0], |
| 101 | + 'mean': avg_pearson, |
| 102 | + 'wmean': wavg_pearson}, |
| 103 | + 'spearman': {'all': all_spearman[0], |
| 104 | + 'mean': avg_spearman, |
| 105 | + 'wmean': wavg_spearman}} |
| 106 | + logging.debug('ALL : Pearson = %.4f, \ |
| 107 | + Spearman = %.4f' % (all_pearson[0], all_spearman[0])) |
| 108 | + logging.debug('ALL (weighted average) : Pearson = %.4f, \ |
| 109 | + Spearman = %.4f' % (wavg_pearson, wavg_spearman)) |
| 110 | + logging.debug('ALL (average) : Pearson = %.4f, \ |
| 111 | + Spearman = %.4f\n' % (avg_pearson, avg_spearman)) |
| 112 | + |
| 113 | + return results |
| 114 | + |
| 115 | + |
| 116 | +class STS12Eval(STSEval): |
| 117 | + def __init__(self, taskpath, seed=1111): |
| 118 | + logging.debug('***** Transfer task : STS12 *****\n\n') |
| 119 | + self.seed = seed |
| 120 | + self.datasets = ['MSRpar', 'MSRvid', 'SMTeuroparl', |
| 121 | + 'surprise.OnWN', 'surprise.SMTnews'] |
| 122 | + self.loadFile(taskpath) |
| 123 | + |
| 124 | + |
| 125 | +class STS13Eval(STSEval): |
| 126 | + # STS13 here does not contain the "SMT" subtask due to LICENSE issue |
| 127 | + def __init__(self, taskpath, seed=1111): |
| 128 | + logging.debug('***** Transfer task : STS13 (-SMT) *****\n\n') |
| 129 | + self.seed = seed |
| 130 | + self.datasets = ['FNWN', 'headlines', 'OnWN'] |
| 131 | + self.loadFile(taskpath) |
| 132 | + |
| 133 | + |
| 134 | +class STS14Eval(STSEval): |
| 135 | + def __init__(self, taskpath, seed=1111): |
| 136 | + logging.debug('***** Transfer task : STS14 *****\n\n') |
| 137 | + self.seed = seed |
| 138 | + self.datasets = ['deft-forum', 'deft-news', 'headlines', |
| 139 | + 'images', 'OnWN', 'tweet-news'] |
| 140 | + self.loadFile(taskpath) |
| 141 | + |
| 142 | + |
| 143 | +class STS15Eval(STSEval): |
| 144 | + def __init__(self, taskpath, seed=1111): |
| 145 | + logging.debug('***** Transfer task : STS15 *****\n\n') |
| 146 | + self.seed = seed |
| 147 | + self.datasets = ['answers-forums', 'answers-students', |
| 148 | + 'belief', 'headlines', 'images'] |
| 149 | + self.loadFile(taskpath) |
| 150 | + |
| 151 | + |
| 152 | +class STS16Eval(STSEval): |
| 153 | + def __init__(self, taskpath, seed=1111): |
| 154 | + logging.debug('***** Transfer task : STS16 *****\n\n') |
| 155 | + self.seed = seed |
| 156 | + self.datasets = ['answer-answer', 'headlines', 'plagiarism', |
| 157 | + 'postediting', 'question-question'] |
| 158 | + self.loadFile(taskpath) |
| 159 | + |
| 160 | + |
| 161 | +class STSBenchmarkEval(STSEval): |
| 162 | + def __init__(self, task_path, seed=1111): |
| 163 | + logging.debug('\n\n***** Transfer task : STSBenchmark*****\n\n') |
| 164 | + self.seed = seed |
| 165 | + self.samples = [] |
| 166 | + #train = self.loadFile(os.path.join(task_path, 'sts-train.csv')) |
| 167 | + #dev = self.loadFile(os.path.join(task_path, 'sts-dev.csv')) |
| 168 | + #test = self.loadFile(os.path.join(task_path, 'sts-test.csv')) |
| 169 | + #self.datasets = ['train', 'dev', 'test'] |
| 170 | + #self.data = {'train': train, 'dev': dev, 'test': test} |
| 171 | + test = self.loadFile(os.path.join(task_path, 'sts-test.csv')) |
| 172 | + self.datasets = ['test'] |
| 173 | + self.data = {'test': test} |
| 174 | + |
| 175 | + def loadFile(self, fpath): |
| 176 | + sick_data = {'X_A': [], 'X_B': [], 'y': []} |
| 177 | + with io.open(fpath, 'r', encoding='utf-8') as f: |
| 178 | + for line in f: |
| 179 | + text = line.strip().split('\t') |
| 180 | + sick_data['X_A'].append(text[5].split()) |
| 181 | + sick_data['X_B'].append(text[6].split()) |
| 182 | + sick_data['y'].append(text[4]) |
| 183 | + |
| 184 | + sick_data['y'] = [float(s) for s in sick_data['y']] |
| 185 | + self.samples += sick_data['X_A'] + sick_data["X_B"] |
| 186 | + return (sick_data['X_A'], sick_data["X_B"], sick_data['y']) |
| 187 | + |
| 188 | +class STSBenchmarkEvalDev(STSEval): |
| 189 | + def __init__(self, task_path, seed=1111): |
| 190 | + logging.debug('\n\n***** Transfer task : STSBenchmark*****\n\n') |
| 191 | + self.seed = seed |
| 192 | + self.samples = [] |
| 193 | + #train = self.loadFile(os.path.join(task_path, 'sts-train.csv')) |
| 194 | + #dev = self.loadFile(os.path.join(task_path, 'sts-dev.csv')) |
| 195 | + #test = self.loadFile(os.path.join(task_path, 'sts-test.csv')) |
| 196 | + #self.datasets = ['train', 'dev', 'test'] |
| 197 | + #self.data = {'train': train, 'dev': dev, 'test': test} |
| 198 | + dev = self.loadFile(os.path.join(task_path, 'sts-dev.csv')) |
| 199 | + self.datasets = ['dev'] |
| 200 | + self.data = {'dev': dev} |
| 201 | + |
| 202 | + def loadFile(self, fpath): |
| 203 | + sick_data = {'X_A': [], 'X_B': [], 'y': []} |
| 204 | + with io.open(fpath, 'r', encoding='utf-8') as f: |
| 205 | + for line in f: |
| 206 | + text = line.strip().split('\t') |
| 207 | + sick_data['X_A'].append(text[5].split()) |
| 208 | + sick_data['X_B'].append(text[6].split()) |
| 209 | + sick_data['y'].append(text[4]) |
| 210 | + |
| 211 | + sick_data['y'] = [float(s) for s in sick_data['y']] |
| 212 | + self.samples += sick_data['X_A'] + sick_data["X_B"] |
| 213 | + return (sick_data['X_A'], sick_data["X_B"], sick_data['y']) |
| 214 | + |
| 215 | +class STSBenchmarkFinetune(SICKEval): |
| 216 | + def __init__(self, task_path, seed=1111): |
| 217 | + logging.debug('\n\n***** Transfer task : STSBenchmark*****\n\n') |
| 218 | + self.seed = seed |
| 219 | + train = self.loadFile(os.path.join(task_path, 'sts-train.csv')) |
| 220 | + dev = self.loadFile(os.path.join(task_path, 'sts-dev.csv')) |
| 221 | + test = self.loadFile(os.path.join(task_path, 'sts-test.csv')) |
| 222 | + self.sick_data = {'train': train, 'dev': dev, 'test': test} |
| 223 | + |
| 224 | + def loadFile(self, fpath): |
| 225 | + sick_data = {'X_A': [], 'X_B': [], 'y': []} |
| 226 | + with io.open(fpath, 'r', encoding='utf-8') as f: |
| 227 | + for line in f: |
| 228 | + text = line.strip().split('\t') |
| 229 | + sick_data['X_A'].append(text[5].split()) |
| 230 | + sick_data['X_B'].append(text[6].split()) |
| 231 | + sick_data['y'].append(text[4]) |
| 232 | + |
| 233 | + sick_data['y'] = [float(s) for s in sick_data['y']] |
| 234 | + return sick_data |
| 235 | + |
| 236 | +class SICKRelatednessEval(STSEval): |
| 237 | + def __init__(self, task_path, seed=1111): |
| 238 | + logging.debug('\n\n***** Transfer task : SICKRelatedness*****\n\n') |
| 239 | + self.seed = seed |
| 240 | + self.samples = [] |
| 241 | + #train = self.loadFile(os.path.join(task_path, 'SICK_train.txt')) |
| 242 | + #dev = self.loadFile(os.path.join(task_path, 'SICK_trial.txt')) |
| 243 | + #test = self.loadFile(os.path.join(task_path, 'SICK_test_annotated.txt')) |
| 244 | + #self.datasets = ['train', 'dev', 'test'] |
| 245 | + #self.data = {'train': train, 'dev': dev, 'test': test} |
| 246 | + test = self.loadFile(os.path.join(task_path, 'SICK_test_annotated.txt')) |
| 247 | + self.datasets = ['test'] |
| 248 | + self.data = {'test': test} |
| 249 | + |
| 250 | + def loadFile(self, fpath): |
| 251 | + skipFirstLine = True |
| 252 | + sick_data = {'X_A': [], 'X_B': [], 'y': []} |
| 253 | + with io.open(fpath, 'r', encoding='utf-8') as f: |
| 254 | + for line in f: |
| 255 | + if skipFirstLine: |
| 256 | + skipFirstLine = False |
| 257 | + else: |
| 258 | + text = line.strip().split('\t') |
| 259 | + sick_data['X_A'].append(text[1].split()) |
| 260 | + sick_data['X_B'].append(text[2].split()) |
| 261 | + sick_data['y'].append(text[3]) |
| 262 | + |
| 263 | + sick_data['y'] = [float(s) for s in sick_data['y']] |
| 264 | + self.samples += sick_data['X_A'] + sick_data["X_B"] |
| 265 | + return (sick_data['X_A'], sick_data["X_B"], sick_data['y']) |
0 commit comments