-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_k_shot_data.py
181 lines (164 loc) · 7.1 KB
/
generate_k_shot_data.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""This script samples K examples randomly without replacement from the original data."""
import argparse
import os
import numpy as np
import pandas as pd
from pandas import DataFrame
def get_label(task, line):
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style
line = line.strip().split('\t')
if task == 'CoLA':
return line[1]
elif task == 'MNLI':
return line[-1]
elif task == 'MRPC':
return line[0]
elif task == 'QNLI':
return line[-1]
elif task == 'QQP':
return line[-1]
elif task == 'RTE':
return line[-1]
elif task == 'SNLI':
return line[-1]
elif task == 'SST-2':
return line[-1]
elif task == 'STS-B':
return 0 if float(line[-1]) < 2.5 else 1
elif task == 'WNLI':
return line[-1]
else:
raise NotImplementedError
else:
return line[0]
def load_datasets(data_dir, tasks):
datasets = {}
for task in tasks:
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style (tsv)
dataset = {}
dirname = os.path.join(data_dir, task)
if task == "MNLI":
splits = ["train", "dev_matched", "dev_mismatched"]
else:
splits = ["train", "dev"]
for split in splits:
filename = os.path.join(dirname, f"{split}.tsv")
with open(filename, "r") as f:
lines = f.readlines()
dataset[split] = lines
datasets[task] = dataset
else:
# Other datasets (csv)
dataset = {}
dirname = os.path.join(data_dir, task)
splits = ["train", "test"]
for split in splits:
filename = os.path.join(dirname, f"{split}.csv")
dataset[split] = pd.read_csv(filename, header=None)
datasets[task] = dataset
return datasets
def split_header(task, lines):
"""
Returns if the task file has a header or not. Only for GLUE tasks.
"""
if task in ["CoLA"]:
return [], lines
elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]:
return lines[0:1], lines[1:]
else:
raise ValueError("Unknown GLUE task.")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--k", type=int, default=16,
help="Training examples for each class.")
parser.add_argument("--task", type=str, nargs="+",
default=['SST-2', 'sst-5', 'mr', 'cr', 'mpqa', 'subj', 'trec', 'CoLA', 'MRPC', 'QQP', 'STS-B', 'MNLI', 'SNLI', 'QNLI', 'RTE'],
help="Task names")
parser.add_argument("--seed", type=int, nargs="+",
default=[100, 13, 21, 42, 87],
help="Random seeds")
parser.add_argument("--data_dir", type=str, default="data/original", help="Path to original data")
parser.add_argument("--output_dir", type=str, default="data", help="Output path")
parser.add_argument("--mode", type=str, default='k-shot', choices=['k-shot', 'k-shot-10x'], help="k-shot or k-shot-10x (10x dev set)")
args = parser.parse_args()
args.output_dir = os.path.join(args.output_dir, args.mode)
k = args.k
print("K =", k)
datasets = load_datasets(args.data_dir, args.task)
for seed in args.seed:
print("Seed = %d" % (seed))
for task, dataset in datasets.items():
# Set random seed
np.random.seed(seed)
# Shuffle the training set
print("| Task = %s" % (task))
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style
train_header, train_lines = split_header(task, dataset["train"])
np.random.shuffle(train_lines)
else:
# Other datasets
train_lines = dataset['train'].values.tolist()
np.random.shuffle(train_lines)
# Set up dir
task_dir = os.path.join(args.output_dir, task)
setting_dir = os.path.join(task_dir, f"{k}-{seed}")
os.makedirs(setting_dir, exist_ok=True)
# Write test splits
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
# GLUE style
# Use the original development set as the test set (the original test sets are not publicly available)
for split, lines in dataset.items():
if split.startswith("train"):
continue
split = split.replace('dev', 'test')
with open(os.path.join(setting_dir, f"{split}.tsv"), "w") as f:
for line in lines:
f.write(line)
else:
# Other datasets
# Use the original test sets
dataset['test'].to_csv(os.path.join(setting_dir, 'test.csv'), header=False, index=False)
# Get label list for balanced sampling
label_list = {}
for line in train_lines:
label = get_label(task, line)
if label not in label_list:
label_list[label] = [line]
else:
label_list[label].append(line)
if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]:
with open(os.path.join(setting_dir, "train.tsv"), "w") as f:
for line in train_header:
f.write(line)
for label in label_list:
for line in label_list[label][:k]:
f.write(line)
name = "dev.tsv"
if task == 'MNLI':
name = "dev_matched.tsv"
with open(os.path.join(setting_dir, name), "w") as f:
for line in train_header:
f.write(line)
for label in label_list:
dev_rate = 11 if '10x' in args.mode else 2
for line in label_list[label][k:k*dev_rate]:
f.write(line)
else:
new_train = []
for label in label_list:
for line in label_list[label][:k]:
new_train.append(line)
new_train = DataFrame(new_train)
new_train.to_csv(os.path.join(setting_dir, 'train.csv'), header=False, index=False)
new_dev = []
for label in label_list:
dev_rate = 11 if '10x' in args.mode else 2
for line in label_list[label][k:k*dev_rate]:
new_dev.append(line)
new_dev = DataFrame(new_dev)
new_dev.to_csv(os.path.join(setting_dir, 'dev.csv'), header=False, index=False)
if __name__ == "__main__":
main()