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 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import os
  2. from nltk import Tree
  3. from typing import Union, Dict
  4. from fastNLP.core.const import Const
  5. from fastNLP.core.vocabulary import Vocabulary
  6. from fastNLP.io.base_loader import DataInfo
  7. from fastNLP.io.dataset_loader import JsonLoader, DataSetLoader
  8. from fastNLP.io.file_utils import _get_base_url, cached_path, PRETRAINED_BERT_MODEL_DIR
  9. from fastNLP.modules.encoder._bert import BertTokenizer
  10. class MatchingLoader(DataSetLoader):
  11. """
  12. 别名::class:`fastNLP.io.MatchingLoader` :class:`fastNLP.io.dataset_loader.MatchingLoader`
  13. 读取Matching任务的数据集
  14. """
  15. def __init__(self, paths: dict=None):
  16. """
  17. :param dict paths: key是数据集名称(如train、dev、test),value是对应的文件名
  18. """
  19. self.paths = paths
  20. def _load(self, path):
  21. """
  22. :param str path: 待读取数据集的路径名
  23. :return: fastNLP.DataSet ds: 返回一个DataSet对象,里面必须包含3个field:其中两个分别为两个句子
  24. 的原始字符串文本,第三个为标签
  25. """
  26. raise NotImplementedError
  27. def process(self, paths: Union[str, Dict[str, str]], dataset_name: str=None,
  28. to_lower=False, seq_len_type: str=None, bert_tokenizer: str=None,
  29. get_index=True, 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 bool get_index: 是否需要根据词表将文本转为index
  43. :param set_input: 如果为True,则会自动将相关的field(名字里含有Const.INPUT的)设置为input,如果为False
  44. 则不会将任何field设置为input。如果传入str或者List[str],则会根据传入的内容将相对应的field设置为input,
  45. 于此同时其他field不会被设置为input。默认值为True。
  46. :param set_target: set_target将控制哪些field可以被设置为target,用法与set_input一致。默认值为True。
  47. :param concat: 是否需要将两个句子拼接起来。如果为False则不会拼接。如果为True则会在两个句子之间插入一个<sep>。
  48. 如果传入一个长度为4的list,则分别表示插在第一句开始前、第一句结束后、第二句开始前、第二句结束后的标识符。如果
  49. 传入字符串 ``bert`` ,则会采用bert的拼接方式,等价于['[CLS]', '[SEP]', '', '[SEP]'].
  50. :return:
  51. """
  52. if isinstance(set_input, str):
  53. set_input = [set_input]
  54. if isinstance(set_target, str):
  55. set_target = [set_target]
  56. if isinstance(set_input, bool):
  57. auto_set_input = set_input
  58. else:
  59. auto_set_input = False
  60. if isinstance(set_target, bool):
  61. auto_set_target = set_target
  62. else:
  63. auto_set_target = False
  64. if isinstance(paths, str):
  65. if os.path.isdir(paths):
  66. path = {n: os.path.join(paths, self.paths[n]) for n in self.paths.keys()}
  67. else:
  68. path = {dataset_name if dataset_name is not None else 'train': paths}
  69. else:
  70. path = paths
  71. data_info = DataInfo()
  72. for data_name in path.keys():
  73. data_info.datasets[data_name] = self._load(path[data_name])
  74. for data_name, data_set in data_info.datasets.items():
  75. if auto_set_input:
  76. data_set.set_input(Const.INPUTS(0), Const.INPUTS(1))
  77. if auto_set_target:
  78. data_set.set_target(Const.TARGET)
  79. if to_lower:
  80. for data_name, data_set in data_info.datasets.items():
  81. data_set.apply(lambda x: [w.lower() for w in x[Const.INPUTS(0)]], new_field_name=Const.INPUTS(0),
  82. is_input=auto_set_input)
  83. data_set.apply(lambda x: [w.lower() for w in x[Const.INPUTS(1)]], new_field_name=Const.INPUTS(1),
  84. is_input=auto_set_input)
  85. if bert_tokenizer is not None:
  86. if bert_tokenizer.lower() in PRETRAINED_BERT_MODEL_DIR:
  87. PRETRAIN_URL = _get_base_url('bert')
  88. model_name = PRETRAINED_BERT_MODEL_DIR[bert_tokenizer]
  89. model_url = PRETRAIN_URL + model_name
  90. model_dir = cached_path(model_url)
  91. # 检查是否存在
  92. elif os.path.isdir(bert_tokenizer):
  93. model_dir = bert_tokenizer
  94. else:
  95. raise ValueError(f"Cannot recognize BERT tokenizer from {bert_tokenizer}.")
  96. tokenizer = BertTokenizer.from_pretrained(model_dir)
  97. for data_name, data_set in data_info.datasets.items():
  98. for fields in data_set.get_field_names():
  99. if Const.INPUT in fields:
  100. data_set.apply(lambda x: tokenizer.tokenize(' '.join(x[fields])), new_field_name=fields,
  101. is_input=auto_set_input)
  102. if isinstance(concat, bool):
  103. concat = 'default' if concat else None
  104. if concat is not None:
  105. if isinstance(concat, str):
  106. CONCAT_MAP = {'bert': ['[CLS]', '[SEP]', '', '[SEP]'],
  107. 'default': ['', '<sep>', '', '']}
  108. if concat.lower() in CONCAT_MAP:
  109. concat = CONCAT_MAP[concat]
  110. else:
  111. concat = 4 * [concat]
  112. assert len(concat) == 4, \
  113. f'Please choose a list with 4 symbols which at the beginning of first sentence ' \
  114. f'the end of first sentence, the begin of second sentence, and the end of second' \
  115. f'sentence. Your input is {concat}'
  116. for data_name, data_set in data_info.datasets.items():
  117. data_set.apply(lambda x: [concat[0]] + x[Const.INPUTS(0)] + [concat[1]] + [concat[2]] +
  118. x[Const.INPUTS(1)] + [concat[3]], new_field_name=Const.INPUT)
  119. data_set.apply(lambda x: [w for w in x[Const.INPUT] if len(w) > 0], new_field_name=Const.INPUT,
  120. is_input=auto_set_input)
  121. if seq_len_type is not None:
  122. if seq_len_type == 'seq_len': #
  123. for data_name, data_set in data_info.datasets.items():
  124. for fields in data_set.get_field_names():
  125. if Const.INPUT in fields:
  126. data_set.apply(lambda x: len(x[fields]),
  127. new_field_name=fields.replace(Const.INPUT, Const.INPUT_LEN),
  128. is_input=auto_set_input)
  129. elif seq_len_type == 'mask':
  130. for data_name, data_set in data_info.datasets.items():
  131. for fields in data_set.get_field_names():
  132. if Const.INPUT in fields:
  133. data_set.apply(lambda x: [1] * len(x[fields]),
  134. new_field_name=fields.replace(Const.INPUT, Const.INPUT_LEN),
  135. is_input=auto_set_input)
  136. elif seq_len_type == 'bert':
  137. for data_name, data_set in data_info.datasets.items():
  138. if Const.INPUT not in data_set.get_field_names():
  139. raise KeyError(f'Field ``{Const.INPUT}`` not in {data_name} data set: '
  140. f'got {data_set.get_field_names()}')
  141. data_set.apply(lambda x: [0] * (len(x[Const.INPUTS(0)]) + 2) + [1] * (len(x[Const.INPUTS(1)]) + 1),
  142. new_field_name=Const.INPUT_LENS(0), is_input=auto_set_input)
  143. data_set.apply(lambda x: [1] * len(x[Const.INPUT_LENS(0)]),
  144. new_field_name=Const.INPUT_LENS(1), is_input=auto_set_input)
  145. data_set_list = [d for n, d in data_info.datasets.items()]
  146. assert len(data_set_list) > 0, f'There are NO data sets in data info!'
  147. if bert_tokenizer is not None:
  148. words_vocab = Vocabulary(padding='[PAD]', unknown='[UNK]')
  149. with open(os.path.join(model_dir, 'vocab.txt'), 'r') as f:
  150. lines = f.readlines()
  151. lines = [line.strip() for line in lines]
  152. words_vocab.add_word_lst(lines)
  153. words_vocab.build_vocab()
  154. else:
  155. words_vocab = Vocabulary()
  156. words_vocab = words_vocab.from_dataset(*[d for n, d in data_info.datasets.items() if 'train' in n],
  157. field_name=[n for n in data_set_list[0].get_field_names()
  158. if (Const.INPUT in n)],
  159. no_create_entry_dataset=[d for n, d in data_info.datasets.items()
  160. if 'train' not in n])
  161. target_vocab = Vocabulary(padding=None, unknown=None)
  162. target_vocab = target_vocab.from_dataset(*data_set_list, field_name=Const.TARGET)
  163. data_info.vocabs = {Const.INPUT: words_vocab, Const.TARGET: target_vocab}
  164. if get_index:
  165. for data_name, data_set in data_info.datasets.items():
  166. for fields in data_set.get_field_names():
  167. if Const.INPUT in fields:
  168. data_set.apply(lambda x: [words_vocab.to_index(w) for w in x[fields]], new_field_name=fields,
  169. is_input=auto_set_input)
  170. data_set.apply(lambda x: target_vocab.to_index(x[Const.TARGET]), new_field_name=Const.TARGET,
  171. is_input=auto_set_input, is_target=auto_set_target)
  172. for data_name, data_set in data_info.datasets.items():
  173. if isinstance(set_input, list):
  174. data_set.set_input(*set_input)
  175. if isinstance(set_target, list):
  176. data_set.set_target(*set_target)
  177. return data_info
  178. class SNLILoader(MatchingLoader, JsonLoader):
  179. """
  180. 别名::class:`fastNLP.io.SNLILoader` :class:`fastNLP.io.dataset_loader.SNLILoader`
  181. 读取SNLI数据集,读取的DataSet包含fields::
  182. words1: list(str),第一句文本, premise
  183. words2: list(str), 第二句文本, hypothesis
  184. target: str, 真实标签
  185. 数据来源: https://nlp.stanford.edu/projects/snli/snli_1.0.zip
  186. """
  187. def __init__(self, paths: dict=None):
  188. fields = {
  189. 'sentence1_parse': Const.INPUTS(0),
  190. 'sentence2_parse': Const.INPUTS(1),
  191. 'gold_label': Const.TARGET,
  192. }
  193. paths = paths if paths is not None else {
  194. 'train': 'snli_1.0_train.jsonl',
  195. 'dev': 'snli_1.0_dev.jsonl',
  196. 'test': 'snli_1.0_test.jsonl'}
  197. # super(SNLILoader, self).__init__(fields=fields, paths=paths)
  198. MatchingLoader.__init__(self, paths=paths)
  199. JsonLoader.__init__(self, fields=fields)
  200. def _load(self, path):
  201. # ds = super(SNLILoader, self)._load(path)
  202. ds = JsonLoader._load(self, path)
  203. def parse_tree(x):
  204. t = Tree.fromstring(x)
  205. return t.leaves()
  206. ds.apply(lambda ins: parse_tree(
  207. ins[Const.INPUTS(0)]), new_field_name=Const.INPUTS(0))
  208. ds.apply(lambda ins: parse_tree(
  209. ins[Const.INPUTS(1)]), new_field_name=Const.INPUTS(1))
  210. ds.drop(lambda x: x[Const.TARGET] == '-')
  211. return ds