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

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