asahi417's picture
init
afcb4ea
import json
import os
import tarfile
import zipfile
import gzip
import requests
from random import shuffle, seed
from glob import glob
from itertools import chain
import gdown
validation_ratio = 0.2
top_n = 10
def wget(url, cache_dir: str = './cache', gdrive_filename: str = None):
""" wget and uncompress data_iterator """
os.makedirs(cache_dir, exist_ok=True)
if url.startswith('https://drive.google.com'):
assert gdrive_filename is not None, 'please provide fileaname for gdrive download'
gdown.download(url, f'{cache_dir}/{gdrive_filename}', quiet=False)
filename = gdrive_filename
else:
filename = os.path.basename(url)
with open(f'{cache_dir}/{filename}', "wb") as f:
r = requests.get(url)
f.write(r.content)
path = f'{cache_dir}/{filename}'
if path.endswith('.tar.gz') or path.endswith('.tgz') or path.endswith('.tar'):
if path.endswith('.tar'):
tar = tarfile.open(path)
else:
tar = tarfile.open(path, "r:gz")
tar.extractall(cache_dir)
tar.close()
os.remove(path)
elif path.endswith('.zip'):
with zipfile.ZipFile(path, 'r') as zip_ref:
zip_ref.extractall(cache_dir)
os.remove(path)
elif path.endswith('.gz'):
with gzip.open(path, 'rb') as f:
with open(path.replace('.gz', ''), 'wb') as f_write:
f_write.write(f.read())
os.remove(path)
def get_training_data():
""" Get RelBERT training data
Returns
-------
pairs: dictionary of list (positive pairs, negative pairs)
{'1b': [[0.6, ('office', 'desk'), ..], [[-0.1, ('aaa', 'bbb'), ...]]
"""
cache_dir = 'cache'
os.makedirs(cache_dir, exist_ok=True)
remove_relation = None
path_answer = f'{cache_dir}/Phase2Answers'
path_scale = f'{cache_dir}/Phase2AnswersScaled'
url = 'https://drive.google.com/u/0/uc?id=0BzcZKTSeYL8VYWtHVmxUR3FyUmc&export=download'
filename = 'SemEval-2012-Platinum-Ratings.tar.gz'
if not (os.path.exists(path_scale) and os.path.exists(path_answer)):
wget(url, gdrive_filename=filename, cache_dir=cache_dir)
files_answer = [os.path.basename(i) for i in glob(f'{path_answer}/*.txt')]
files_scale = [os.path.basename(i) for i in glob(f'{path_scale}/*.txt')]
assert files_answer == files_scale, f'files are not matched: {files_scale} vs {files_answer}'
positives = {}
negatives = {}
all_relation_type = {}
positives_score = {}
seed(42)
# score_range = [90.0, 88.7] # the absolute value of max/min prototypicality rating
for i in files_scale:
relation_id = i.split('-')[-1].replace('.txt', '')
if remove_relation and int(relation_id[:-1]) in remove_relation:
continue
with open(f'{path_answer}/{i}', 'r') as f:
lines_answer = [_l.replace('"', '').split('\t') for _l in f.read().split('\n')
if not _l.startswith('#') and len(_l)]
relation_type = list(set(list(zip(*lines_answer))[-1]))
assert len(relation_type) == 1, relation_type
relation_type = relation_type[0]
with open(f'{path_scale}/{i}', 'r') as f:
# list of tuple [score, ("a", "b")]
scales = [[float(_l[:5]), _l[6:].replace('"', '')] for _l in f.read().split('\n')
if not _l.startswith('#') and len(_l)]
scales = sorted(scales, key=lambda _x: _x[0])
# positive pairs are in the reverse order of prototypicality score
positive_pairs = [[s, tuple(p.split(':'))] for s, p in filter(lambda _x: _x[0] > 0, scales)]
positive_pairs = sorted(positive_pairs, key=lambda x: x[0], reverse=True)
positive_pairs = positive_pairs[:min(top_n, len(positive_pairs))]
shuffle(positive_pairs)
positives_score[relation_id] = positive_pairs
positives[relation_id] = list(list(zip(*positive_pairs))[1])
negative_pairs = [tuple(p.split(':')) for s, p in filter(lambda _x: _x[0] < 0, scales)]
shuffle(negative_pairs)
negatives[relation_id] = negative_pairs
all_relation_type[relation_id] = relation_type
# consider positive from other relation as negative
for k in positives.keys():
negatives[k] += list(chain(*[_v for _k, _v in positives.items() if _k != k]))
# split train & validation
positives_valid = {k: v[:int(len(v) * validation_ratio)] for k, v in positives.items()}
positives_train = {k: v[int(len(v) * validation_ratio):] for k, v in positives.items()}
negatives_valid = {k: v[:int(len(v) * validation_ratio)] for k, v in negatives.items()}
negatives_train = {k: v[int(len(v) * validation_ratio):] for k, v in negatives.items()}
positives_score_valid = {k: v[:int(len(v) * validation_ratio)] for k, v in positives_score.items()}
positives_score_train = {k: v[int(len(v) * validation_ratio):] for k, v in positives_score.items()}
outputs = []
for positives, negatives, positives_score in zip(
[positives_train, positives_valid],
[negatives_train, negatives_valid],
[positives_score_train, positives_score_valid]):
pairs = {k: [positives[k], negatives[k]] for k in positives.keys()}
parent = list(set([i[:-1] for i in all_relation_type.keys()]))
relation_structure = {p: [i for i in all_relation_type.keys() if p == i[:-1]] for p in parent}
for k, v in relation_structure.items():
positive = list(chain(*[positives_score[_v] for _v in v]))
positive = list(list(zip(*sorted(positive, key=lambda x: x[0], reverse=True)))[1])
negative = []
for _k, _v in relation_structure.items():
if _k != k:
negative += list(chain(*[positives[__v] for __v in _v]))
pairs[k] = [positive, negative]
outputs.append([{'relation_type': k, 'positives': pos, 'negatives': neg} for k, (pos, neg) in pairs.items()])
return outputs
if __name__ == '__main__':
data_train, data_valid = get_training_data()
with open('dataset/train.jsonl', 'w') as f_writer:
f_writer.write('\n'.join([json.dumps(i) for i in data_train]))
with open('dataset/valid.jsonl', 'w') as f_writer:
f_writer.write('\n'.join([json.dumps(i) for i in data_valid]))