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.

matching.py 15 kB

6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import os
  2. from typing import Union, Dict, List
  3. from ...core.const import Const
  4. from ...core.vocabulary import Vocabulary
  5. from ..base_loader import DataBundle, DataSetLoader
  6. from ..file_utils import _get_base_url, cached_path, PRETRAINED_BERT_MODEL_DIR
  7. from ...modules.encoder.bert import BertTokenizer
  8. class MatchingLoader(DataSetLoader):
  9. """
  10. 别名::class:`fastNLP.io.MatchingLoader` :class:`fastNLP.io.data_loader.MatchingLoader`
  11. 读取Matching任务的数据集
  12. :param dict paths: key是数据集名称(如train、dev、test),value是对应的文件名
  13. """
  14. def __init__(self, paths: dict=None):
  15. self.paths = paths
  16. def _load(self, path):
  17. """
  18. :param str path: 待读取数据集的路径名
  19. :return: fastNLP.DataSet ds: 返回一个DataSet对象,里面必须包含3个field:其中两个分别为两个句子
  20. 的原始字符串文本,第三个为标签
  21. """
  22. raise NotImplementedError
  23. def process(self, paths: Union[str, Dict[str, str]], dataset_name: str=None,
  24. to_lower=False, seq_len_type: str=None, bert_tokenizer: str=None,
  25. cut_text: int = None, get_index=True, auto_pad_length: int=None,
  26. auto_pad_token: str='<pad>', set_input: Union[list, str, bool]=True,
  27. set_target: Union[list, str, bool]=True, concat: Union[str, list, bool]=None,
  28. extra_split: List[str]=None, ) -> DataBundle:
  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. :param extra_split: 额外的分隔符,即除了空格之外的用于分词的字符。
  52. :return:
  53. """
  54. if isinstance(set_input, str):
  55. set_input = [set_input]
  56. if isinstance(set_target, str):
  57. set_target = [set_target]
  58. if isinstance(set_input, bool):
  59. auto_set_input = set_input
  60. else:
  61. auto_set_input = False
  62. if isinstance(set_target, bool):
  63. auto_set_target = set_target
  64. else:
  65. auto_set_target = False
  66. if isinstance(paths, str):
  67. if os.path.isdir(paths):
  68. path = {n: os.path.join(paths, self.paths[n]) for n in self.paths.keys()}
  69. else:
  70. path = {dataset_name if dataset_name is not None else 'train': paths}
  71. else:
  72. path = paths
  73. data_info = DataBundle()
  74. for data_name in path.keys():
  75. data_info.datasets[data_name] = self._load(path[data_name])
  76. for data_name, data_set in data_info.datasets.items():
  77. if auto_set_input:
  78. data_set.set_input(Const.INPUTS(0), Const.INPUTS(1))
  79. if auto_set_target:
  80. if Const.TARGET in data_set.get_field_names():
  81. data_set.set_target(Const.TARGET)
  82. if extra_split is not None:
  83. for data_name, data_set in data_info.datasets.items():
  84. data_set.apply(lambda x: ' '.join(x[Const.INPUTS(0)]), new_field_name=Const.INPUTS(0))
  85. data_set.apply(lambda x: ' '.join(x[Const.INPUTS(1)]), new_field_name=Const.INPUTS(1))
  86. for s in extra_split:
  87. data_set.apply(lambda x: x[Const.INPUTS(0)].replace(s, ' ' + s + ' '),
  88. new_field_name=Const.INPUTS(0))
  89. data_set.apply(lambda x: x[Const.INPUTS(0)].replace(s, ' ' + s + ' '),
  90. new_field_name=Const.INPUTS(0))
  91. _filt = lambda x: x
  92. data_set.apply(lambda x: list(filter(_filt, x[Const.INPUTS(0)].split(' '))),
  93. new_field_name=Const.INPUTS(0), is_input=auto_set_input)
  94. data_set.apply(lambda x: list(filter(_filt, x[Const.INPUTS(1)].split(' '))),
  95. new_field_name=Const.INPUTS(1), is_input=auto_set_input)
  96. _filt = None
  97. if to_lower:
  98. for data_name, data_set in data_info.datasets.items():
  99. data_set.apply(lambda x: [w.lower() for w in x[Const.INPUTS(0)]], new_field_name=Const.INPUTS(0),
  100. is_input=auto_set_input)
  101. data_set.apply(lambda x: [w.lower() for w in x[Const.INPUTS(1)]], new_field_name=Const.INPUTS(1),
  102. is_input=auto_set_input)
  103. if bert_tokenizer is not None:
  104. if bert_tokenizer.lower() in PRETRAINED_BERT_MODEL_DIR:
  105. PRETRAIN_URL = _get_base_url('bert')
  106. model_name = PRETRAINED_BERT_MODEL_DIR[bert_tokenizer]
  107. model_url = PRETRAIN_URL + model_name
  108. model_dir = cached_path(model_url)
  109. # 检查是否存在
  110. elif os.path.isdir(bert_tokenizer):
  111. model_dir = bert_tokenizer
  112. else:
  113. raise ValueError(f"Cannot recognize BERT tokenizer from {bert_tokenizer}.")
  114. words_vocab = Vocabulary(padding='[PAD]', unknown='[UNK]')
  115. with open(os.path.join(model_dir, 'vocab.txt'), 'r') as f:
  116. lines = f.readlines()
  117. lines = [line.strip() for line in lines]
  118. words_vocab.add_word_lst(lines)
  119. words_vocab.build_vocab()
  120. tokenizer = BertTokenizer.from_pretrained(model_dir)
  121. for data_name, data_set in data_info.datasets.items():
  122. for fields in data_set.get_field_names():
  123. if Const.INPUT in fields:
  124. data_set.apply(lambda x: tokenizer.tokenize(' '.join(x[fields])), new_field_name=fields,
  125. is_input=auto_set_input)
  126. if isinstance(concat, bool):
  127. concat = 'default' if concat else None
  128. if concat is not None:
  129. if isinstance(concat, str):
  130. CONCAT_MAP = {'bert': ['[CLS]', '[SEP]', '', '[SEP]'],
  131. 'default': ['', '<sep>', '', '']}
  132. if concat.lower() in CONCAT_MAP:
  133. concat = CONCAT_MAP[concat]
  134. else:
  135. concat = 4 * [concat]
  136. assert len(concat) == 4, \
  137. f'Please choose a list with 4 symbols which at the beginning of first sentence ' \
  138. f'the end of first sentence, the begin of second sentence, and the end of second' \
  139. f'sentence. Your input is {concat}'
  140. for data_name, data_set in data_info.datasets.items():
  141. data_set.apply(lambda x: [concat[0]] + x[Const.INPUTS(0)] + [concat[1]] + [concat[2]] +
  142. x[Const.INPUTS(1)] + [concat[3]], new_field_name=Const.INPUT)
  143. data_set.apply(lambda x: [w for w in x[Const.INPUT] if len(w) > 0], new_field_name=Const.INPUT,
  144. is_input=auto_set_input)
  145. if seq_len_type is not None:
  146. if seq_len_type == 'seq_len': #
  147. for data_name, data_set in data_info.datasets.items():
  148. for fields in data_set.get_field_names():
  149. if Const.INPUT in fields:
  150. data_set.apply(lambda x: len(x[fields]),
  151. new_field_name=fields.replace(Const.INPUT, Const.INPUT_LEN),
  152. is_input=auto_set_input)
  153. elif seq_len_type == 'mask':
  154. for data_name, data_set in data_info.datasets.items():
  155. for fields in data_set.get_field_names():
  156. if Const.INPUT in fields:
  157. data_set.apply(lambda x: [1] * len(x[fields]),
  158. new_field_name=fields.replace(Const.INPUT, Const.INPUT_LEN),
  159. is_input=auto_set_input)
  160. elif seq_len_type == 'bert':
  161. for data_name, data_set in data_info.datasets.items():
  162. if Const.INPUT not in data_set.get_field_names():
  163. raise KeyError(f'Field ``{Const.INPUT}`` not in {data_name} data set: '
  164. f'got {data_set.get_field_names()}')
  165. data_set.apply(lambda x: [0] * (len(x[Const.INPUTS(0)]) + 2) + [1] * (len(x[Const.INPUTS(1)]) + 1),
  166. new_field_name=Const.INPUT_LENS(0), is_input=auto_set_input)
  167. data_set.apply(lambda x: [1] * len(x[Const.INPUT_LENS(0)]),
  168. new_field_name=Const.INPUT_LENS(1), is_input=auto_set_input)
  169. if auto_pad_length is not None:
  170. cut_text = min(auto_pad_length, cut_text if cut_text is not None else auto_pad_length)
  171. if cut_text is not None:
  172. for data_name, data_set in data_info.datasets.items():
  173. for fields in data_set.get_field_names():
  174. if (Const.INPUT in fields) or ((Const.INPUT_LEN in fields) and (seq_len_type != 'seq_len')):
  175. data_set.apply(lambda x: x[fields][: cut_text], new_field_name=fields,
  176. is_input=auto_set_input)
  177. data_set_list = [d for n, d in data_info.datasets.items()]
  178. assert len(data_set_list) > 0, f'There are NO data sets in data info!'
  179. if bert_tokenizer is None:
  180. words_vocab = Vocabulary(padding=auto_pad_token)
  181. words_vocab = words_vocab.from_dataset(*[d for n, d in data_info.datasets.items() if 'train' in n],
  182. field_name=[n for n in data_set_list[0].get_field_names()
  183. if (Const.INPUT in n)],
  184. no_create_entry_dataset=[d for n, d in data_info.datasets.items()
  185. if 'train' not in n])
  186. target_vocab = Vocabulary(padding=None, unknown=None)
  187. target_vocab = target_vocab.from_dataset(*[d for n, d in data_info.datasets.items() if 'train' in n],
  188. field_name=Const.TARGET)
  189. data_info.vocabs = {Const.INPUT: words_vocab, Const.TARGET: target_vocab}
  190. if get_index:
  191. for data_name, data_set in data_info.datasets.items():
  192. for fields in data_set.get_field_names():
  193. if Const.INPUT in fields:
  194. data_set.apply(lambda x: [words_vocab.to_index(w) for w in x[fields]], new_field_name=fields,
  195. is_input=auto_set_input)
  196. if Const.TARGET in data_set.get_field_names():
  197. data_set.apply(lambda x: target_vocab.to_index(x[Const.TARGET]), new_field_name=Const.TARGET,
  198. is_input=auto_set_input, is_target=auto_set_target)
  199. if auto_pad_length is not None:
  200. if seq_len_type == 'seq_len':
  201. raise RuntimeError(f'the sequence will be padded with the length {auto_pad_length}, '
  202. f'so the seq_len_type cannot be `{seq_len_type}`!')
  203. for data_name, data_set in data_info.datasets.items():
  204. for fields in data_set.get_field_names():
  205. if Const.INPUT in fields:
  206. data_set.apply(lambda x: x[fields] + [words_vocab.to_index(words_vocab.padding)] *
  207. (auto_pad_length - len(x[fields])), new_field_name=fields,
  208. is_input=auto_set_input)
  209. elif (Const.INPUT_LEN in fields) and (seq_len_type != 'seq_len'):
  210. data_set.apply(lambda x: x[fields] + [0] * (auto_pad_length - len(x[fields])),
  211. new_field_name=fields, is_input=auto_set_input)
  212. for data_name, data_set in data_info.datasets.items():
  213. if isinstance(set_input, list):
  214. data_set.set_input(*[inputs for inputs in set_input if inputs in data_set.get_field_names()])
  215. if isinstance(set_target, list):
  216. data_set.set_target(*[target for target in set_target if target in data_set.get_field_names()])
  217. return data_info