You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

MatchingDataLoader.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import os
  2. from typing import Union, Dict
  3. from fastNLP.core.const import Const
  4. from fastNLP.core.vocabulary import Vocabulary
  5. from fastNLP.io.base_loader import DataInfo, DataSetLoader
  6. from fastNLP.io.dataset_loader import JsonLoader, CSVLoader
  7. from fastNLP.io.file_utils import _get_base_url, cached_path, PRETRAINED_BERT_MODEL_DIR
  8. from fastNLP.modules.encoder._bert import BertTokenizer
  9. class MatchingLoader(DataSetLoader):
  10. """
  11. 别名::class:`fastNLP.io.MatchingLoader` :class:`fastNLP.io.dataset_loader.MatchingLoader`
  12. 读取Matching任务的数据集
  13. :param dict paths: key是数据集名称(如train、dev、test),value是对应的文件名
  14. """
  15. def __init__(self, paths: dict=None):
  16. self.paths = paths
  17. def _load(self, path):
  18. """
  19. :param str path: 待读取数据集的路径名
  20. :return: fastNLP.DataSet ds: 返回一个DataSet对象,里面必须包含3个field:其中两个分别为两个句子
  21. 的原始字符串文本,第三个为标签
  22. """
  23. raise NotImplementedError
  24. def process(self, paths: Union[str, Dict[str, str]], dataset_name: str=None,
  25. to_lower=False, seq_len_type: str=None, bert_tokenizer: str=None,
  26. cut_text: int = None, get_index=True, auto_pad_length: int=None,
  27. auto_pad_token: str='<pad>', set_input: Union[list, str, bool]=True,
  28. set_target: Union[list, str, bool] = True, concat: Union[str, list, bool]=None, ) -> DataInfo:
  29. """
  30. :param paths: str或者Dict[str, str]。如果是str,则为数据集所在的文件夹或者是全路径文件名:如果是文件夹,
  31. 则会从self.paths里面找对应的数据集名称与文件名。如果是Dict,则为数据集名称(如train、dev、test)和
  32. 对应的全路径文件名。
  33. :param str dataset_name: 如果在paths里传入的是一个数据集的全路径文件名,那么可以用dataset_name来定义
  34. 这个数据集的名字,如果不定义则默认为train。
  35. :param bool to_lower: 是否将文本自动转为小写。默认值为False。
  36. :param str seq_len_type: 提供的seq_len类型,支持 ``seq_len`` :提供一个数字作为句子长度; ``mask`` :
  37. 提供一个0/1的mask矩阵作为句子长度; ``bert`` :提供segment_type_id(第一个句子为0,第二个句子为1)和
  38. attention mask矩阵(0/1的mask矩阵)。默认值为None,即不提供seq_len
  39. :param str bert_tokenizer: bert tokenizer所使用的词表所在的文件夹路径
  40. :param int cut_text: 将长于cut_text的内容截掉。默认为None,即不截。
  41. :param bool get_index: 是否需要根据词表将文本转为index
  42. :param int auto_pad_length: 是否需要将文本自动pad到一定长度(超过这个长度的文本将会被截掉),默认为不会自动pad
  43. :param str auto_pad_token: 自动pad的内容
  44. :param set_input: 如果为True,则会自动将相关的field(名字里含有Const.INPUT的)设置为input,如果为False
  45. 则不会将任何field设置为input。如果传入str或者List[str],则会根据传入的内容将相对应的field设置为input,
  46. 于此同时其他field不会被设置为input。默认值为True。
  47. :param set_target: set_target将控制哪些field可以被设置为target,用法与set_input一致。默认值为True。
  48. :param concat: 是否需要将两个句子拼接起来。如果为False则不会拼接。如果为True则会在两个句子之间插入一个<sep>。
  49. 如果传入一个长度为4的list,则分别表示插在第一句开始前、第一句结束后、第二句开始前、第二句结束后的标识符。如果
  50. 传入字符串 ``bert`` ,则会采用bert的拼接方式,等价于['[CLS]', '[SEP]', '', '[SEP]'].
  51. :return:
  52. """
  53. if isinstance(set_input, str):
  54. set_input = [set_input]
  55. if isinstance(set_target, str):
  56. set_target = [set_target]
  57. if isinstance(set_input, bool):
  58. auto_set_input = set_input
  59. else:
  60. auto_set_input = False
  61. if isinstance(set_target, bool):
  62. auto_set_target = set_target
  63. else:
  64. auto_set_target = False
  65. if isinstance(paths, str):
  66. if os.path.isdir(paths):
  67. path = {n: os.path.join(paths, self.paths[n]) for n in self.paths.keys()}
  68. else:
  69. path = {dataset_name if dataset_name is not None else 'train': paths}
  70. else:
  71. path = paths
  72. data_info = DataInfo()
  73. for data_name in path.keys():
  74. data_info.datasets[data_name] = self._load(path[data_name])
  75. for data_name, data_set in data_info.datasets.items():
  76. if auto_set_input:
  77. data_set.set_input(Const.INPUTS(0), Const.INPUTS(1))
  78. if auto_set_target:
  79. if Const.TARGET in data_set.get_field_names():
  80. data_set.set_target(Const.TARGET)
  81. if to_lower:
  82. for data_name, data_set in data_info.datasets.items():
  83. data_set.apply(lambda x: [w.lower() for w in x[Const.INPUTS(0)]], new_field_name=Const.INPUTS(0),
  84. is_input=auto_set_input)
  85. data_set.apply(lambda x: [w.lower() for w in x[Const.INPUTS(1)]], new_field_name=Const.INPUTS(1),
  86. is_input=auto_set_input)
  87. if bert_tokenizer is not None:
  88. if bert_tokenizer.lower() in PRETRAINED_BERT_MODEL_DIR:
  89. PRETRAIN_URL = _get_base_url('bert')
  90. model_name = PRETRAINED_BERT_MODEL_DIR[bert_tokenizer]
  91. model_url = PRETRAIN_URL + model_name
  92. model_dir = cached_path(model_url)
  93. # 检查是否存在
  94. elif os.path.isdir(bert_tokenizer):
  95. model_dir = bert_tokenizer
  96. else:
  97. raise ValueError(f"Cannot recognize BERT tokenizer from {bert_tokenizer}.")
  98. words_vocab = Vocabulary(padding='[PAD]', unknown='[UNK]')
  99. with open(os.path.join(model_dir, 'vocab.txt'), 'r') as f:
  100. lines = f.readlines()
  101. lines = [line.strip() for line in lines]
  102. words_vocab.add_word_lst(lines)
  103. words_vocab.build_vocab()
  104. tokenizer = BertTokenizer.from_pretrained(model_dir)
  105. for data_name, data_set in data_info.datasets.items():
  106. for fields in data_set.get_field_names():
  107. if Const.INPUT in fields:
  108. data_set.apply(lambda x: tokenizer.tokenize(' '.join(x[fields])), new_field_name=fields,
  109. is_input=auto_set_input)
  110. if isinstance(concat, bool):
  111. concat = 'default' if concat else None
  112. if concat is not None:
  113. if isinstance(concat, str):
  114. CONCAT_MAP = {'bert': ['[CLS]', '[SEP]', '', '[SEP]'],
  115. 'default': ['', '<sep>', '', '']}
  116. if concat.lower() in CONCAT_MAP:
  117. concat = CONCAT_MAP[concat]
  118. else:
  119. concat = 4 * [concat]
  120. assert len(concat) == 4, \
  121. f'Please choose a list with 4 symbols which at the beginning of first sentence ' \
  122. f'the end of first sentence, the begin of second sentence, and the end of second' \
  123. f'sentence. Your input is {concat}'
  124. for data_name, data_set in data_info.datasets.items():
  125. data_set.apply(lambda x: [concat[0]] + x[Const.INPUTS(0)] + [concat[1]] + [concat[2]] +
  126. x[Const.INPUTS(1)] + [concat[3]], new_field_name=Const.INPUT)
  127. data_set.apply(lambda x: [w for w in x[Const.INPUT] if len(w) > 0], new_field_name=Const.INPUT,
  128. is_input=auto_set_input)
  129. if seq_len_type is not None:
  130. if seq_len_type == 'seq_len': #
  131. for data_name, data_set in data_info.datasets.items():
  132. for fields in data_set.get_field_names():
  133. if Const.INPUT in fields:
  134. data_set.apply(lambda x: len(x[fields]),
  135. new_field_name=fields.replace(Const.INPUT, Const.INPUT_LEN),
  136. is_input=auto_set_input)
  137. elif seq_len_type == 'mask':
  138. for data_name, data_set in data_info.datasets.items():
  139. for fields in data_set.get_field_names():
  140. if Const.INPUT in fields:
  141. data_set.apply(lambda x: [1] * len(x[fields]),
  142. new_field_name=fields.replace(Const.INPUT, Const.INPUT_LEN),
  143. is_input=auto_set_input)
  144. elif seq_len_type == 'bert':
  145. for data_name, data_set in data_info.datasets.items():
  146. if Const.INPUT not in data_set.get_field_names():
  147. raise KeyError(f'Field ``{Const.INPUT}`` not in {data_name} data set: '
  148. f'got {data_set.get_field_names()}')
  149. data_set.apply(lambda x: [0] * (len(x[Const.INPUTS(0)]) + 2) + [1] * (len(x[Const.INPUTS(1)]) + 1),
  150. new_field_name=Const.INPUT_LENS(0), is_input=auto_set_input)
  151. data_set.apply(lambda x: [1] * len(x[Const.INPUT_LENS(0)]),
  152. new_field_name=Const.INPUT_LENS(1), is_input=auto_set_input)
  153. if auto_pad_length is not None:
  154. cut_text = min(auto_pad_length, cut_text if cut_text is not None else auto_pad_length)
  155. if cut_text is not None:
  156. for data_name, data_set in data_info.datasets.items():
  157. for fields in data_set.get_field_names():
  158. if (Const.INPUT in fields) or ((Const.INPUT_LEN in fields) and (seq_len_type != 'seq_len')):
  159. data_set.apply(lambda x: x[fields][: cut_text], new_field_name=fields,
  160. is_input=auto_set_input)
  161. data_set_list = [d for n, d in data_info.datasets.items()]
  162. assert len(data_set_list) > 0, f'There are NO data sets in data info!'
  163. if bert_tokenizer is None:
  164. words_vocab = Vocabulary(padding=auto_pad_token)
  165. words_vocab = words_vocab.from_dataset(*[d for n, d in data_info.datasets.items() if 'train' in n],
  166. field_name=[n for n in data_set_list[0].get_field_names()
  167. if (Const.INPUT in n)],
  168. no_create_entry_dataset=[d for n, d in data_info.datasets.items()
  169. if 'train' not in n])
  170. target_vocab = Vocabulary(padding=None, unknown=None)
  171. target_vocab = target_vocab.from_dataset(*[d for n, d in data_info.datasets.items() if 'train' in n],
  172. field_name=Const.TARGET)
  173. data_info.vocabs = {Const.INPUT: words_vocab, Const.TARGET: target_vocab}
  174. if get_index:
  175. for data_name, data_set in data_info.datasets.items():
  176. for fields in data_set.get_field_names():
  177. if Const.INPUT in fields:
  178. data_set.apply(lambda x: [words_vocab.to_index(w) for w in x[fields]], new_field_name=fields,
  179. is_input=auto_set_input)
  180. if Const.TARGET in data_set.get_field_names():
  181. data_set.apply(lambda x: target_vocab.to_index(x[Const.TARGET]), new_field_name=Const.TARGET,
  182. is_input=auto_set_input, is_target=auto_set_target)
  183. if auto_pad_length is not None:
  184. if seq_len_type == 'seq_len':
  185. raise RuntimeError(f'the sequence will be padded with the length {auto_pad_length}, '
  186. f'so the seq_len_type cannot be `{seq_len_type}`!')
  187. for data_name, data_set in data_info.datasets.items():
  188. for fields in data_set.get_field_names():
  189. if Const.INPUT in fields:
  190. data_set.apply(lambda x: x[fields] + [words_vocab.to_index(words_vocab.padding)] *
  191. (auto_pad_length - len(x[fields])), new_field_name=fields,
  192. is_input=auto_set_input)
  193. elif (Const.INPUT_LEN in fields) and (seq_len_type != 'seq_len'):
  194. data_set.apply(lambda x: x[fields] + [0] * (auto_pad_length - len(x[fields])),
  195. new_field_name=fields, is_input=auto_set_input)
  196. for data_name, data_set in data_info.datasets.items():
  197. if isinstance(set_input, list):
  198. data_set.set_input(*[inputs for inputs in set_input if inputs in data_set.get_field_names()])
  199. if isinstance(set_target, list):
  200. data_set.set_target(*[target for target in set_target if target in data_set.get_field_names()])
  201. return data_info
  202. class SNLILoader(MatchingLoader, JsonLoader):
  203. """
  204. 别名::class:`fastNLP.io.SNLILoader` :class:`fastNLP.io.dataset_loader.SNLILoader`
  205. 读取SNLI数据集,读取的DataSet包含fields::
  206. words1: list(str),第一句文本, premise
  207. words2: list(str), 第二句文本, hypothesis
  208. target: str, 真实标签
  209. 数据来源: https://nlp.stanford.edu/projects/snli/snli_1.0.zip
  210. """
  211. def __init__(self, paths: dict=None):
  212. fields = {
  213. 'sentence1_binary_parse': Const.INPUTS(0),
  214. 'sentence2_binary_parse': Const.INPUTS(1),
  215. 'gold_label': Const.TARGET,
  216. }
  217. paths = paths if paths is not None else {
  218. 'train': 'snli_1.0_train.jsonl',
  219. 'dev': 'snli_1.0_dev.jsonl',
  220. 'test': 'snli_1.0_test.jsonl'}
  221. MatchingLoader.__init__(self, paths=paths)
  222. JsonLoader.__init__(self, fields=fields)
  223. def _load(self, path):
  224. ds = JsonLoader._load(self, path)
  225. parentheses_table = str.maketrans({'(': None, ')': None})
  226. ds.apply(lambda ins: ins[Const.INPUTS(0)].translate(parentheses_table).strip().split(),
  227. new_field_name=Const.INPUTS(0))
  228. ds.apply(lambda ins: ins[Const.INPUTS(1)].translate(parentheses_table).strip().split(),
  229. new_field_name=Const.INPUTS(1))
  230. ds.drop(lambda x: x[Const.TARGET] == '-')
  231. return ds
  232. class RTELoader(MatchingLoader, CSVLoader):
  233. """
  234. 别名::class:`fastNLP.io.RTELoader` :class:`fastNLP.io.dataset_loader.RTELoader`
  235. 读取RTE数据集,读取的DataSet包含fields::
  236. words1: list(str),第一句文本, premise
  237. words2: list(str), 第二句文本, hypothesis
  238. target: str, 真实标签
  239. 数据来源:
  240. """
  241. def __init__(self, paths: dict=None):
  242. paths = paths if paths is not None else {
  243. 'train': 'train.tsv',
  244. 'dev': 'dev.tsv',
  245. 'test': 'test.tsv' # test set has not label
  246. }
  247. MatchingLoader.__init__(self, paths=paths)
  248. self.fields = {
  249. 'sentence1': Const.INPUTS(0),
  250. 'sentence2': Const.INPUTS(1),
  251. 'label': Const.TARGET,
  252. }
  253. CSVLoader.__init__(self, sep='\t')
  254. def _load(self, path):
  255. ds = CSVLoader._load(self, path)
  256. for k, v in self.fields.items():
  257. if v in ds.get_field_names():
  258. ds.rename_field(k, v)
  259. for fields in ds.get_all_fields():
  260. if Const.INPUT in fields:
  261. ds.apply(lambda x: x[fields].strip().split(), new_field_name=fields)
  262. return ds
  263. class QNLILoader(MatchingLoader, CSVLoader):
  264. """
  265. 别名::class:`fastNLP.io.QNLILoader` :class:`fastNLP.io.dataset_loader.QNLILoader`
  266. 读取QNLI数据集,读取的DataSet包含fields::
  267. words1: list(str),第一句文本, premise
  268. words2: list(str), 第二句文本, hypothesis
  269. target: str, 真实标签
  270. 数据来源:
  271. """
  272. def __init__(self, paths: dict=None):
  273. paths = paths if paths is not None else {
  274. 'train': 'train.tsv',
  275. 'dev': 'dev.tsv',
  276. 'test': 'test.tsv' # test set has not label
  277. }
  278. MatchingLoader.__init__(self, paths=paths)
  279. self.fields = {
  280. 'question': Const.INPUTS(0),
  281. 'sentence': Const.INPUTS(1),
  282. 'label': Const.TARGET,
  283. }
  284. CSVLoader.__init__(self, sep='\t')
  285. def _load(self, path):
  286. ds = CSVLoader._load(self, path)
  287. for k, v in self.fields.items():
  288. if v in ds.get_field_names():
  289. ds.rename_field(k, v)
  290. for fields in ds.get_all_fields():
  291. if Const.INPUT in fields:
  292. ds.apply(lambda x: x[fields].strip().split(), new_field_name=fields)
  293. return ds
  294. class MNLILoader(MatchingLoader, CSVLoader):
  295. """
  296. 别名::class:`fastNLP.io.MNLILoader` :class:`fastNLP.io.dataset_loader.MNLILoader`
  297. 读取MNLI数据集,读取的DataSet包含fields::
  298. words1: list(str),第一句文本, premise
  299. words2: list(str), 第二句文本, hypothesis
  300. target: str, 真实标签
  301. 数据来源:
  302. """
  303. def __init__(self, paths: dict=None):
  304. paths = paths if paths is not None else {
  305. 'train': 'train.tsv',
  306. 'dev_matched': 'dev_matched.tsv',
  307. 'dev_mismatched': 'dev_mismatched.tsv',
  308. 'test_matched': 'test_matched.tsv',
  309. 'test_mismatched': 'test_mismatched.tsv',
  310. # 'test_0.9_matched': 'multinli_0.9_test_matched_unlabeled.txt',
  311. # 'test_0.9_mismatched': 'multinli_0.9_test_mismatched_unlabeled.txt',
  312. # test_0.9_mathed与mismatched是MNLI0.9版本的(数据来源:kaggle)
  313. }
  314. MatchingLoader.__init__(self, paths=paths)
  315. CSVLoader.__init__(self, sep='\t')
  316. self.fields = {
  317. 'sentence1_binary_parse': Const.INPUTS(0),
  318. 'sentence2_binary_parse': Const.INPUTS(1),
  319. 'gold_label': Const.TARGET,
  320. }
  321. def _load(self, path):
  322. ds = CSVLoader._load(self, path)
  323. for k, v in self.fields.items():
  324. if k in ds.get_field_names():
  325. ds.rename_field(k, v)
  326. if Const.TARGET in ds.get_field_names():
  327. if ds[0][Const.TARGET] == 'hidden':
  328. ds.delete_field(Const.TARGET)
  329. parentheses_table = str.maketrans({'(': None, ')': None})
  330. ds.apply(lambda ins: ins[Const.INPUTS(0)].translate(parentheses_table).strip().split(),
  331. new_field_name=Const.INPUTS(0))
  332. ds.apply(lambda ins: ins[Const.INPUTS(1)].translate(parentheses_table).strip().split(),
  333. new_field_name=Const.INPUTS(1))
  334. if Const.TARGET in ds.get_field_names():
  335. ds.drop(lambda x: x[Const.TARGET] == '-')
  336. return ds
  337. class QuoraLoader(MatchingLoader, CSVLoader):
  338. """
  339. 别名::class:`fastNLP.io.QuoraLoader` :class:`fastNLP.io.dataset_loader.QuoraLoader`
  340. 读取MNLI数据集,读取的DataSet包含fields::
  341. words1: list(str),第一句文本, premise
  342. words2: list(str), 第二句文本, hypothesis
  343. target: str, 真实标签
  344. 数据来源:
  345. """
  346. def __init__(self, paths: dict=None):
  347. paths = paths if paths is not None else {
  348. 'train': 'train.tsv',
  349. 'dev': 'dev.tsv',
  350. 'test': 'test.tsv',
  351. }
  352. MatchingLoader.__init__(self, paths=paths)
  353. CSVLoader.__init__(self, sep='\t', headers=(Const.TARGET, Const.INPUTS(0), Const.INPUTS(1), 'pairID'))
  354. def _load(self, path):
  355. ds = CSVLoader._load(self, path)
  356. return ds