├── README.md ├── abduction_model.py ├── bert ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── __init__.py ├── create_pretraining_data.py ├── extract_features.py ├── modeling.py ├── modeling_test.py ├── multilingual.md ├── optimization.py ├── optimization_test.py ├── predicting_movie_reviews_with_bert_on_tf_hub.ipynb ├── requirements.txt ├── run_classifier.py ├── run_classifier_with_tfhub.py ├── run_pretraining.py ├── run_squad.py ├── sample_text.txt ├── tokenization.py └── tokenization_test.py ├── bert_class.py ├── checkrules.py ├── data ├── data_utils.py └── dataset.zip ├── data_utils.py ├── judger.py ├── pk_files └── this is the result's pickle files folder ├── result └── this is the result folder ├── result_utils.py ├── rule_file.txt ├── sentence_model.py ├── ss_abl_model.py ├── tmp ├── abl_predict_0.json ├── abl_predict_1.json ├── abl_train_0.json └── this is the tmp folder ├── tools.py └── train_bert.py /README.md: -------------------------------------------------------------------------------- 1 | 🌟 **New!** [ABLkit](https://github.com/AbductiveLearning/ABLkit) released: A toolkit for Abductive Learning with high flexibility, user-friendly interface, and optimized performance. Welcome to try it out!🚀 2 | 3 | # Semi-Supervised Abductive Learning for Theft Judicial Sentencing 4 | 5 | This is the repository for holding the sample code of the Semi-Supervised Abductive Learning framework for Theft Judicial Sentencing experiments in _Semi-Supervised Abductive Learning and Its Application to Theft Judicial Sentencing_ in ICDM 2020. 6 | 7 | **This code is only tested in Linux environment.** 8 | 9 | ## Dependency 10 | 11 | - Python 3.6 12 | 13 | - tensorflow 1.12.0 14 | 15 | 16 | ## Running Code 17 | 18 | ### Set Data File Path 19 | 20 | ```python3 21 | # Before running code, we should set data file path first. 22 | # By default, all data files are in "./data/" 23 | 24 | # Data file path's setting codes are lies on line 207 - 212 in "ss_abl_model.py". 25 | # Bert Pretrain json file name 26 | pretrain_filename = "0_0.10.json" 27 | 28 | # Sentence model supervised traning data file path 29 | pretrain_money_filename = "./data/0_0.10.csv" 30 | 31 | # Unlabeled data file name 32 | abl_train_filename = "1_0.90.json" 33 | abl_train_money_filename = "1_0.90.csv" 34 | 35 | # Bert test data file name 36 | test_filename = "10.json" 37 | # Sentence model test data file name 38 | test_money_filename = "10.csv" 39 | ``` 40 | 41 | ```bash 42 | unzip data/dataset.zip 43 | wget https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip 44 | unzip chinese_L-12_H-768_A-12.zip 45 | python ss_abl_model.py 46 | ``` 47 | 48 | ### Parameters 49 | 50 | Our model's parameters are listed below. 51 | 52 | ```python3 53 | # Model's Parameter and default value 54 | abl_max_change_num = 2 # The max number of label could be changed on abduction 55 | 56 | abl_times = 1 # The model traning iteration number 57 | rule_file_path = "rule_test_file.txt" # abduction rule file path 58 | 59 | pretrain_bert_train_epochs = 16 # The epoch number of BERT training on Supervised data 60 | pretrain_sentence_model_times = 3 # The epoch number of sentence model traning on Supervised data 61 | abl_bert_train_epochs = 1 # The epoch number per iteration of BERT traning on abduction process 62 | abl_sentence_model_times = 3 # The epoch number per iteration of sentence model traning on abduction process 63 | 64 | ``` 65 | -------------------------------------------------------------------------------- /abduction_model.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | from sklearn import linear_model 3 | 4 | import pickle as pk 5 | 6 | from checkrules import CheckRules 7 | 8 | from data_utils import load_json 9 | from sentence_model import SentenceModel 10 | import copy 11 | import numpy as np 12 | 13 | def check_attr(attr, matched): 14 | if matched[0]==1 and matched[11]==0 and attr[0]==0: 15 | return False 16 | if matched[0]==0 and attr[0]==1: 17 | return False 18 | if matched[1] != attr[1]: 19 | return False 20 | if matched[2]==0 and attr[2]==1: 21 | return False 22 | if matched[2]==1 and matched[10]==0 and attr[2]==0: 23 | return False 24 | if matched[3]==1 and matched[10]==0 and attr[3]==0: 25 | return False 26 | if matched[3]==0 and attr[3]==1: 27 | return False 28 | if matched[4]==1 and matched[12]==1 and attr[4]==0: 29 | return False 30 | if matched[4]==0 and attr[4]==1: 31 | return False 32 | if matched[5] != attr[5]: 33 | return False 34 | if matched[7]==1 and attr[7]==0: 35 | return False 36 | if matched[8]==1 and attr[8]==0: 37 | return False 38 | if matched[9]==1 and attr[0]==0 and attr[1]==0 and attr[2]==0 and attr[4]==0 and attr[5]==0: 39 | return False 40 | 41 | return True 42 | 43 | 44 | 45 | def attr_convert(attr, pos): 46 | attr_copy = attr.copy() 47 | for idx in pos: 48 | attr_copy[idx] = 1 - attr_copy[idx] 49 | return attr_copy 50 | 51 | class SentenceAbduction: 52 | def set_predict_model(self, model): 53 | self.model = model 54 | 55 | def get_matching_re(self, context): 56 | vec = [0] * len(self.facter_strs) 57 | if context is None: 58 | print("Context can not be found!") 59 | return vec 60 | 61 | for i in range(len(self.facter_strs)): 62 | facter_str = self.facter_strs[i] 63 | for facter in facter_str: 64 | loc = context.find(facter) 65 | if loc != -1: 66 | if i == 7 or i == 8: 67 | if abs(context.find(self.not_facter_room_theft_str)-loc) <= 20: 68 | vec[i] = 0 69 | else: 70 | vec[i] = 1 71 | elif i == 0: 72 | if context[loc-1]=='未': 73 | vec[i] = 0 74 | else: 75 | vec[i] = 1 76 | else: 77 | vec[i] = 1 78 | return vec 79 | 80 | def build_dict(self, json_list): 81 | context_dict = {} 82 | for data in json_list: 83 | ah = data[0]['ah'] 84 | context_dict[ah] = data 85 | return context_dict 86 | 87 | def get_penalty_type(self, money, attrs): 88 | [no_damage, attitude, surrender, again, young, forgive, tool, room, theft] = attrs 89 | if money < self.LARGE: 90 | if room == 1 or theft == 1: 91 | return 0 92 | if money >= 500 and again == 1: 93 | return 0 94 | elif money < self.HUGE: 95 | return 0 96 | elif money < self.EXTRA_HUGE: 97 | return 1 98 | else: 99 | return 2 100 | return -1 101 | 102 | def validate(self, money, attrs, month): 103 | [no_damage, attitude, surrender, again, young, forgive, tool, room, theft] = attrs 104 | prob = self.check.judge(attrs) 105 | if prob < 1e-6: 106 | return False 107 | 108 | penalty_type = self.get_penalty_type(money, attrs) 109 | if penalty_type == -1: 110 | return False 111 | if penalty_type == 0: 112 | if month <= 3 * 12: 113 | return True 114 | elif month >= 3 * 12 and month <= 10 * 12 and room == 1 and money >= 15000: 115 | return True 116 | else: 117 | return False 118 | if penalty_type == 1: 119 | if month >= 3 * 12 and month <= 10 * 12: 120 | return True 121 | if month <= 3 * 12 and surrender == 1: 122 | return True 123 | if month >= 10 * 12 and room == 1 and money >= 150000: 124 | return True 125 | if penalty_type == 2: 126 | if month >= 10 * 12: 127 | return True 128 | if month <= 10 * 12 and month >= 3 * 12 and (surrender == 1 or young == 1): 129 | return True 130 | return False 131 | 132 | def predict_and_validate(self, X, attrs, target_month): 133 | Y = self.model.predict(X, attrs) 134 | for i in range(len(X)): 135 | [money] = X[i] 136 | if self.validate(money, attrs[i], target_month[i]) == False: 137 | Y[i] = -1 138 | return Y 139 | 140 | def select_abduced_result(self, attrs, months, target_month): 141 | err = 999 142 | if len(attrs) == 0: 143 | return None, None 144 | assert len(attrs) > 0 145 | if abs(months[0] - target_month) <= 0.1: 146 | return attrs[0], months[0] 147 | for attr, month in zip(attrs, months): 148 | if month < 0: 149 | continue 150 | if abs(month - target_month) < err: 151 | selected_attr = attr 152 | selected_month = month 153 | err = abs(selected_month - target_month) 154 | return selected_attr, selected_month 155 | 156 | def abduce_npos(self, money, attr, target_month, n, match_res): 157 | if n == 0: 158 | [predicted_month] = self.predict_and_validate([money], [attr], [target_month]) 159 | return attr, predicted_month 160 | pos_list = list(combinations(range(len(attr)), n)) 161 | err = 99 162 | abduced_attr = None 163 | abduced_month = -1 164 | for pos in pos_list: 165 | new_attr = attr_convert(attr, pos) 166 | 167 | if self.word_match and check_attr(new_attr, match_res) == False: 168 | continue 169 | 170 | [predicted_month] = self.predict_and_validate([money], [new_attr], [target_month]) 171 | if abs(predicted_month - target_month) < err: 172 | err = abs(predicted_month - target_month) 173 | abduced_attr = new_attr.copy() 174 | abduced_month = predicted_month 175 | return abduced_attr, abduced_month 176 | 177 | 178 | def remove_label(self, content, label, k): 179 | judgement = [] 180 | modified_thres = 0.9 181 | for con in content: 182 | pro = con["pro"] 183 | if label in con["label"]: 184 | if pro[k] <= modified_thres: 185 | con["label"].remove(label) 186 | #print("remove label:", label) 187 | else: 188 | pass#print("should remove but not remove:", label) 189 | judgement.append(con) 190 | return judgement 191 | 192 | def get_pro_matrix(self, data): 193 | pro_matrix = [] 194 | for line in data: 195 | pro_matrix.append(line["pro"]) 196 | return pro_matrix 197 | 198 | def get_pre_max_n(self, li): 199 | max_value = max(li) 200 | index = li.index(max(li)) 201 | li[index] = 0 202 | return index, max_value 203 | 204 | def add_index_label(self, judgement, index, label): 205 | line = judgement[index] 206 | if label not in line['label']: 207 | line["label"].append(label) 208 | return judgement 209 | 210 | def get_matching_idxs(self, judgement, k): 211 | indexs = [] 212 | facter_str = self.facter_strs[k] 213 | for i,line in enumerate(judgement): 214 | for facter in facter_str: 215 | if line['sentence'].find(facter) != -1 and not((k==7 or k==8) and line['sentence'].find(self.not_facter_room_theft_str) != -1) and not(k==2 and line['sentence'].find(self.not_facter_surrender_str1) != -1) and not(k==2 and line['sentence'].find(self.not_facter_surrender_str2) != -1) and not(k==0 and line['sentence'].find(self.order_facter_damage_str[0]) != -1) : 216 | indexs.append(i) 217 | break 218 | return indexs 219 | 220 | def add_maxpro_label(self, judgement, matrix, k, label): 221 | res_list = [] 222 | change = True 223 | modified_thres = 0.1 224 | 225 | for j in range(len(matrix)): 226 | res_list.append(matrix[j][k]) 227 | 228 | indexs = self.get_matching_idxs(judgement, k) 229 | if len(indexs) != 0: 230 | #print("add label by matching:", label) 231 | for idx in indexs: 232 | judgement = self.add_index_label(judgement, idx, label) 233 | return judgement 234 | 235 | max_index = res_list.index(max(res_list)) 236 | if res_list[max_index] < modified_thres: 237 | change = False 238 | #print("Should add but not add:", label) 239 | 240 | if change: 241 | #print("add label with max prob:", label) 242 | if k in [0, 1, 3, 5, 6, 7]: 243 | indexs = [] 244 | for i in range(2): 245 | index, max_value = self.get_pre_max_n(res_list) 246 | if max_value >= modified_thres: 247 | indexs.append(index) 248 | for iid in indexs: 249 | judgement = self.add_index_label(judgement, iid, label) 250 | return judgement 251 | else: 252 | judgement = self.add_index_label(judgement, max_index, label) 253 | return judgement 254 | else: 255 | return judgement 256 | 257 | def __init__(self, model, rule_file_path, word_match = False): 258 | self.label2id ={"no_damage": 0, "attitude": 1, "surrender": 2, "again": 3, "young": 4, 259 | "forgive": 5, "tool": 6, "indoor": 7, "theft": 8} 260 | self.id2label = {value:key for key, value in self.label2id.items()} 261 | self.LARGE = 1000 262 | self.HUGE = 30000 263 | self.EXTRA_HUGE = 300000 264 | 265 | self.check = CheckRules(rule_file_path) 266 | self.model = model 267 | self.word_match = word_match 268 | 269 | facter_damage_str = ["追回", "退还", "没有给被害人造成损失", "赔偿", "发还", "退缴", "退赔", "追还", "退赃", "返还", "未给被害人造成经济损失","归还"] 270 | facter_attitude_str = ["如实供述", "主动交代", "认罪", "悔罪", "坦白", "如实交待"] 271 | facter_surrender_str = ["自首"] 272 | facter_again_str = ["因犯", "曾因犯罪", "累犯", "前科"] 273 | facter_young_str = ["未成年", "未满十八周岁",'未满18周岁','不满十八周岁','不满18周岁'] 274 | facter_forgive_str = ["谅解","原谅"] 275 | facter_tool_str = ["作案工具", "盗窃用的工具", "盗窃用工具"] 276 | facter_room_str = ["入室", "入户","家中","卧室"] 277 | facter_theft_str = ["扒窃", "扒取","扒走","上衣","口袋", "衣兜"] 278 | facter_less_str = ["从轻处罚", "减轻处罚"] 279 | facter_neg_str = ["不予采纳","不具有","不符","不构成","不属","不认定","不予认定"] 280 | self.order_facter_damage_str = ["责令"] 281 | facter_closed_str = ["不公开开庭"] 282 | self.facter_strs = [facter_damage_str, facter_attitude_str, facter_surrender_str, facter_again_str, facter_young_str, facter_forgive_str, facter_tool_str, facter_room_str, facter_theft_str, facter_less_str, facter_neg_str, self.order_facter_damage_str, facter_closed_str] 283 | 284 | self.not_facter_room_theft_str = "多次盗窃、入户盗窃、携带凶器盗窃、扒窃的" 285 | self.not_facter_surrender_str1 = "犯罪以后自动投案,如实供述自己的罪行的" 286 | self.not_facter_surrender_str2 = "对于自首的犯罪分子,可以从轻或者减轻处罚" 287 | 288 | def __abduce(self, money, attr, target_month, context, max_change_num): 289 | abduced_attrs = [] 290 | abduced_months = [] 291 | 292 | match_res = self.get_matching_re(context) 293 | for change_num in range(max_change_num+1): 294 | abduced_attr, abduced_month = self.abduce_npos(money, attr, target_month, change_num, match_res) 295 | if abduced_month == -1: 296 | continue 297 | abduced_attrs.append(abduced_attr) 298 | abduced_months.append(abduced_month) 299 | abduced_attr, abduced_month = self.select_abduced_result(abduced_attrs, abduced_months, target_month) 300 | change = not(abduced_attr is None or attr==abduced_attr) 301 | if abduced_attr is None: 302 | print("Ad-hoc", context, money, attr, target_month, "specially: ", match_res, attr) 303 | return abduced_attr, abduced_month, change 304 | 305 | def abduce(self, money, attr, month, data, max_change_num): 306 | context = None 307 | if data is not None: 308 | context = "".join([d["sentence"].replace(" ", "") for d in data]) 309 | judgement_json = copy.deepcopy(data) 310 | if data is None: 311 | return None, None, None 312 | abduced_attr, abduced_month, change \ 313 | = self.__abduce(money, attr, month, context, max_change_num) 314 | 315 | if change == True: 316 | assert len(abduced_attr) == len(attr) 317 | #print("no_damage", "attitude", "surrender", "again", "young", "forgive", "tool", "indoor", "theft") 318 | #print(attr, month) 319 | #print(abduced_attr, abduced_month) 320 | #print(context) 321 | #print(judgement_json) 322 | 323 | pro_matrix = self.get_pro_matrix(judgement_json) 324 | for k, v in enumerate(abduced_attr): 325 | if v != attr[k] or (v == attr[k] and v==1): 326 | if v == 0: 327 | judgement_json = self.remove_label(judgement_json, self.id2label[k], k) 328 | elif v == 1: 329 | judgement_json = self.add_maxpro_label(judgement_json, pro_matrix, k, self.id2label[k]) 330 | else: 331 | print("error with label is not 0/1, detail is:", data[0]["ah"], attr, k, v) 332 | return abduced_attr, abduced_month, judgement_json 333 | 334 | def abduce_batch(self, json_file_path, ahs, moneys, attrs, months, max_change_num): 335 | abduced_attrs = [] 336 | abduced_months = [] 337 | judgement_jsons = [] 338 | 339 | context_dict = self.build_dict(load_json(json_file_path)) 340 | for ah, money, attr, month in zip(ahs, moneys, attrs, months): 341 | data = context_dict.get(ah, None) 342 | abduced_attr, abduced_month, judgement_json = self.abduce(money, attr, month, data, max_change_num) 343 | if abduced_attr is None: 344 | continue 345 | 346 | abduced_attrs.append(abduced_attr) 347 | abduced_months.append(abduced_month) 348 | judgement_jsons.append(judgement_json) 349 | 350 | return abduced_attrs, abduced_months, judgement_jsons 351 | 352 | def ad_hoc_test(self, money, attr, month, context, max_change_num): 353 | return self.__abduce(money, attr, month, context, max_change_num) 354 | 355 | -------------------------------------------------------------------------------- /bert/.gitignore: -------------------------------------------------------------------------------- 1 | # Initially taken from Github's Python gitignore file 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # celery beat schedule file 86 | celerybeat-schedule 87 | 88 | # SageMath parsed files 89 | *.sage.py 90 | 91 | # Environments 92 | .env 93 | .venv 94 | env/ 95 | venv/ 96 | ENV/ 97 | env.bak/ 98 | venv.bak/ 99 | 100 | # Spyder project settings 101 | .spyderproject 102 | .spyproject 103 | 104 | # Rope project settings 105 | .ropeproject 106 | 107 | # mkdocs documentation 108 | /site 109 | 110 | # mypy 111 | .mypy_cache/ 112 | .dmypy.json 113 | dmypy.json 114 | 115 | # Pyre type checker 116 | .pyre/ 117 | -------------------------------------------------------------------------------- /bert/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | BERT needs to maintain permanent compatibility with the pre-trained model files, 4 | so we do not plan to make any major changes to this library (other than what was 5 | promised in the README). However, we can accept small patches related to 6 | re-factoring and documentation. To submit contributes, there are just a few 7 | small guidelines you need to follow. 8 | 9 | ## Contributor License Agreement 10 | 11 | Contributions to this project must be accompanied by a Contributor License 12 | Agreement. You (or your employer) retain the copyright to your contribution; 13 | this simply gives us permission to use and redistribute your contributions as 14 | part of the project. Head over to to see 15 | your current agreements on file or to sign a new one. 16 | 17 | You generally only need to submit a CLA once, so if you've already submitted one 18 | (even if it was for a different project), you probably don't need to do it 19 | again. 20 | 21 | ## Code reviews 22 | 23 | All submissions, including submissions by project members, require review. We 24 | use GitHub pull requests for this purpose. Consult 25 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 26 | information on using pull requests. 27 | 28 | ## Community Guidelines 29 | 30 | This project follows 31 | [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). 32 | -------------------------------------------------------------------------------- /bert/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /bert/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | -------------------------------------------------------------------------------- /bert/create_pretraining_data.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Create masked LM/next sentence masked_lm TF examples for BERT.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import collections 22 | import random 23 | import tokenization 24 | import tensorflow as tf 25 | 26 | flags = tf.flags 27 | 28 | FLAGS = flags.FLAGS 29 | 30 | flags.DEFINE_string("input_file", None, 31 | "Input raw text file (or comma-separated list of files).") 32 | 33 | flags.DEFINE_string( 34 | "output_file", None, 35 | "Output TF example file (or comma-separated list of files).") 36 | 37 | flags.DEFINE_string("vocab_file", None, 38 | "The vocabulary file that the BERT model was trained on.") 39 | 40 | flags.DEFINE_bool( 41 | "do_lower_case", True, 42 | "Whether to lower case the input text. Should be True for uncased " 43 | "models and False for cased models.") 44 | 45 | flags.DEFINE_bool( 46 | "do_whole_word_mask", False, 47 | "Whether to use whole word masking rather than per-WordPiece masking.") 48 | 49 | flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.") 50 | 51 | flags.DEFINE_integer("max_predictions_per_seq", 20, 52 | "Maximum number of masked LM predictions per sequence.") 53 | 54 | flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.") 55 | 56 | flags.DEFINE_integer( 57 | "dupe_factor", 10, 58 | "Number of times to duplicate the input data (with different masks).") 59 | 60 | flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.") 61 | 62 | flags.DEFINE_float( 63 | "short_seq_prob", 0.1, 64 | "Probability of creating sequences which are shorter than the " 65 | "maximum length.") 66 | 67 | 68 | class TrainingInstance(object): 69 | """A single training instance (sentence pair).""" 70 | 71 | def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, 72 | is_random_next): 73 | self.tokens = tokens 74 | self.segment_ids = segment_ids 75 | self.is_random_next = is_random_next 76 | self.masked_lm_positions = masked_lm_positions 77 | self.masked_lm_labels = masked_lm_labels 78 | 79 | def __str__(self): 80 | s = "" 81 | s += "tokens: %s\n" % (" ".join( 82 | [tokenization.printable_text(x) for x in self.tokens])) 83 | s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) 84 | s += "is_random_next: %s\n" % self.is_random_next 85 | s += "masked_lm_positions: %s\n" % (" ".join( 86 | [str(x) for x in self.masked_lm_positions])) 87 | s += "masked_lm_labels: %s\n" % (" ".join( 88 | [tokenization.printable_text(x) for x in self.masked_lm_labels])) 89 | s += "\n" 90 | return s 91 | 92 | def __repr__(self): 93 | return self.__str__() 94 | 95 | 96 | def write_instance_to_example_files(instances, tokenizer, max_seq_length, 97 | max_predictions_per_seq, output_files): 98 | """Create TF example files from `TrainingInstance`s.""" 99 | writers = [] 100 | for output_file in output_files: 101 | writers.append(tf.python_io.TFRecordWriter(output_file)) 102 | 103 | writer_index = 0 104 | 105 | total_written = 0 106 | for (inst_index, instance) in enumerate(instances): 107 | input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) 108 | input_mask = [1] * len(input_ids) 109 | segment_ids = list(instance.segment_ids) 110 | assert len(input_ids) <= max_seq_length 111 | 112 | while len(input_ids) < max_seq_length: 113 | input_ids.append(0) 114 | input_mask.append(0) 115 | segment_ids.append(0) 116 | 117 | assert len(input_ids) == max_seq_length 118 | assert len(input_mask) == max_seq_length 119 | assert len(segment_ids) == max_seq_length 120 | 121 | masked_lm_positions = list(instance.masked_lm_positions) 122 | masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) 123 | masked_lm_weights = [1.0] * len(masked_lm_ids) 124 | 125 | while len(masked_lm_positions) < max_predictions_per_seq: 126 | masked_lm_positions.append(0) 127 | masked_lm_ids.append(0) 128 | masked_lm_weights.append(0.0) 129 | 130 | next_sentence_label = 1 if instance.is_random_next else 0 131 | 132 | features = collections.OrderedDict() 133 | features["input_ids"] = create_int_feature(input_ids) 134 | features["input_mask"] = create_int_feature(input_mask) 135 | features["segment_ids"] = create_int_feature(segment_ids) 136 | features["masked_lm_positions"] = create_int_feature(masked_lm_positions) 137 | features["masked_lm_ids"] = create_int_feature(masked_lm_ids) 138 | features["masked_lm_weights"] = create_float_feature(masked_lm_weights) 139 | features["next_sentence_labels"] = create_int_feature([next_sentence_label]) 140 | 141 | tf_example = tf.train.Example(features=tf.train.Features(feature=features)) 142 | 143 | writers[writer_index].write(tf_example.SerializeToString()) 144 | writer_index = (writer_index + 1) % len(writers) 145 | 146 | total_written += 1 147 | 148 | if inst_index < 20: 149 | tf.logging.info("*** Example ***") 150 | tf.logging.info("tokens: %s" % " ".join( 151 | [tokenization.printable_text(x) for x in instance.tokens])) 152 | 153 | for feature_name in features.keys(): 154 | feature = features[feature_name] 155 | values = [] 156 | if feature.int64_list.value: 157 | values = feature.int64_list.value 158 | elif feature.float_list.value: 159 | values = feature.float_list.value 160 | tf.logging.info( 161 | "%s: %s" % (feature_name, " ".join([str(x) for x in values]))) 162 | 163 | for writer in writers: 164 | writer.close() 165 | 166 | tf.logging.info("Wrote %d total instances", total_written) 167 | 168 | 169 | def create_int_feature(values): 170 | feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) 171 | return feature 172 | 173 | 174 | def create_float_feature(values): 175 | feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) 176 | return feature 177 | 178 | 179 | def create_training_instances(input_files, tokenizer, max_seq_length, 180 | dupe_factor, short_seq_prob, masked_lm_prob, 181 | max_predictions_per_seq, rng): 182 | """Create `TrainingInstance`s from raw text.""" 183 | all_documents = [[]] 184 | 185 | # Input file format: 186 | # (1) One sentence per line. These should ideally be actual sentences, not 187 | # entire paragraphs or arbitrary spans of text. (Because we use the 188 | # sentence boundaries for the "next sentence prediction" task). 189 | # (2) Blank lines between documents. Document boundaries are needed so 190 | # that the "next sentence prediction" task doesn't span between documents. 191 | for input_file in input_files: 192 | with tf.gfile.GFile(input_file, "r") as reader: 193 | while True: 194 | line = tokenization.convert_to_unicode(reader.readline()) 195 | if not line: 196 | break 197 | line = line.strip() 198 | 199 | # Empty lines are used as document delimiters 200 | if not line: 201 | all_documents.append([]) 202 | tokens = tokenizer.tokenize(line) 203 | if tokens: 204 | all_documents[-1].append(tokens) 205 | 206 | # Remove empty documents 207 | all_documents = [x for x in all_documents if x] 208 | rng.shuffle(all_documents) 209 | 210 | vocab_words = list(tokenizer.vocab.keys()) 211 | instances = [] 212 | for _ in range(dupe_factor): 213 | for document_index in range(len(all_documents)): 214 | instances.extend( 215 | create_instances_from_document( 216 | all_documents, document_index, max_seq_length, short_seq_prob, 217 | masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) 218 | 219 | rng.shuffle(instances) 220 | return instances 221 | 222 | 223 | def create_instances_from_document( 224 | all_documents, document_index, max_seq_length, short_seq_prob, 225 | masked_lm_prob, max_predictions_per_seq, vocab_words, rng): 226 | """Creates `TrainingInstance`s for a single document.""" 227 | document = all_documents[document_index] 228 | 229 | # Account for [CLS], [SEP], [SEP] 230 | max_num_tokens = max_seq_length - 3 231 | 232 | # We *usually* want to fill up the entire sequence since we are padding 233 | # to `max_seq_length` anyways, so short sequences are generally wasted 234 | # computation. However, we *sometimes* 235 | # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter 236 | # sequences to minimize the mismatch between pre-training and fine-tuning. 237 | # The `target_seq_length` is just a rough target however, whereas 238 | # `max_seq_length` is a hard limit. 239 | target_seq_length = max_num_tokens 240 | if rng.random() < short_seq_prob: 241 | target_seq_length = rng.randint(2, max_num_tokens) 242 | 243 | # We DON'T just concatenate all of the tokens from a document into a long 244 | # sequence and choose an arbitrary split point because this would make the 245 | # next sentence prediction task too easy. Instead, we split the input into 246 | # segments "A" and "B" based on the actual "sentences" provided by the user 247 | # input. 248 | instances = [] 249 | current_chunk = [] 250 | current_length = 0 251 | i = 0 252 | while i < len(document): 253 | segment = document[i] 254 | current_chunk.append(segment) 255 | current_length += len(segment) 256 | if i == len(document) - 1 or current_length >= target_seq_length: 257 | if current_chunk: 258 | # `a_end` is how many segments from `current_chunk` go into the `A` 259 | # (first) sentence. 260 | a_end = 1 261 | if len(current_chunk) >= 2: 262 | a_end = rng.randint(1, len(current_chunk) - 1) 263 | 264 | tokens_a = [] 265 | for j in range(a_end): 266 | tokens_a.extend(current_chunk[j]) 267 | 268 | tokens_b = [] 269 | # Random next 270 | is_random_next = False 271 | if len(current_chunk) == 1 or rng.random() < 0.5: 272 | is_random_next = True 273 | target_b_length = target_seq_length - len(tokens_a) 274 | 275 | # This should rarely go for more than one iteration for large 276 | # corpora. However, just to be careful, we try to make sure that 277 | # the random document is not the same as the document 278 | # we're processing. 279 | for _ in range(10): 280 | random_document_index = rng.randint(0, len(all_documents) - 1) 281 | if random_document_index != document_index: 282 | break 283 | 284 | random_document = all_documents[random_document_index] 285 | random_start = rng.randint(0, len(random_document) - 1) 286 | for j in range(random_start, len(random_document)): 287 | tokens_b.extend(random_document[j]) 288 | if len(tokens_b) >= target_b_length: 289 | break 290 | # We didn't actually use these segments so we "put them back" so 291 | # they don't go to waste. 292 | num_unused_segments = len(current_chunk) - a_end 293 | i -= num_unused_segments 294 | # Actual next 295 | else: 296 | is_random_next = False 297 | for j in range(a_end, len(current_chunk)): 298 | tokens_b.extend(current_chunk[j]) 299 | truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) 300 | 301 | assert len(tokens_a) >= 1 302 | assert len(tokens_b) >= 1 303 | 304 | tokens = [] 305 | segment_ids = [] 306 | tokens.append("[CLS]") 307 | segment_ids.append(0) 308 | for token in tokens_a: 309 | tokens.append(token) 310 | segment_ids.append(0) 311 | 312 | tokens.append("[SEP]") 313 | segment_ids.append(0) 314 | 315 | for token in tokens_b: 316 | tokens.append(token) 317 | segment_ids.append(1) 318 | tokens.append("[SEP]") 319 | segment_ids.append(1) 320 | 321 | (tokens, masked_lm_positions, 322 | masked_lm_labels) = create_masked_lm_predictions( 323 | tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) 324 | instance = TrainingInstance( 325 | tokens=tokens, 326 | segment_ids=segment_ids, 327 | is_random_next=is_random_next, 328 | masked_lm_positions=masked_lm_positions, 329 | masked_lm_labels=masked_lm_labels) 330 | instances.append(instance) 331 | current_chunk = [] 332 | current_length = 0 333 | i += 1 334 | 335 | return instances 336 | 337 | 338 | MaskedLmInstance = collections.namedtuple("MaskedLmInstance", 339 | ["index", "label"]) 340 | 341 | 342 | def create_masked_lm_predictions(tokens, masked_lm_prob, 343 | max_predictions_per_seq, vocab_words, rng): 344 | """Creates the predictions for the masked LM objective.""" 345 | 346 | cand_indexes = [] 347 | for (i, token) in enumerate(tokens): 348 | if token == "[CLS]" or token == "[SEP]": 349 | continue 350 | # Whole Word Masking means that if we mask all of the wordpieces 351 | # corresponding to an original word. When a word has been split into 352 | # WordPieces, the first token does not have any marker and any subsequence 353 | # tokens are prefixed with ##. So whenever we see the ## token, we 354 | # append it to the previous set of word indexes. 355 | # 356 | # Note that Whole Word Masking does *not* change the training code 357 | # at all -- we still predict each WordPiece independently, softmaxed 358 | # over the entire vocabulary. 359 | if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and 360 | token.startswith("##")): 361 | cand_indexes[-1].append(i) 362 | else: 363 | cand_indexes.append([i]) 364 | 365 | rng.shuffle(cand_indexes) 366 | 367 | output_tokens = list(tokens) 368 | 369 | num_to_predict = min(max_predictions_per_seq, 370 | max(1, int(round(len(tokens) * masked_lm_prob)))) 371 | 372 | masked_lms = [] 373 | covered_indexes = set() 374 | for index_set in cand_indexes: 375 | if len(masked_lms) >= num_to_predict: 376 | break 377 | # If adding a whole-word mask would exceed the maximum number of 378 | # predictions, then just skip this candidate. 379 | if len(masked_lms) + len(index_set) > num_to_predict: 380 | continue 381 | is_any_index_covered = False 382 | for index in index_set: 383 | if index in covered_indexes: 384 | is_any_index_covered = True 385 | break 386 | if is_any_index_covered: 387 | continue 388 | for index in index_set: 389 | covered_indexes.add(index) 390 | 391 | masked_token = None 392 | # 80% of the time, replace with [MASK] 393 | if rng.random() < 0.8: 394 | masked_token = "[MASK]" 395 | else: 396 | # 10% of the time, keep original 397 | if rng.random() < 0.5: 398 | masked_token = tokens[index] 399 | # 10% of the time, replace with random word 400 | else: 401 | masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] 402 | 403 | output_tokens[index] = masked_token 404 | 405 | masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) 406 | assert len(masked_lms) <= num_to_predict 407 | masked_lms = sorted(masked_lms, key=lambda x: x.index) 408 | 409 | masked_lm_positions = [] 410 | masked_lm_labels = [] 411 | for p in masked_lms: 412 | masked_lm_positions.append(p.index) 413 | masked_lm_labels.append(p.label) 414 | 415 | return (output_tokens, masked_lm_positions, masked_lm_labels) 416 | 417 | 418 | def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): 419 | """Truncates a pair of sequences to a maximum sequence length.""" 420 | while True: 421 | total_length = len(tokens_a) + len(tokens_b) 422 | if total_length <= max_num_tokens: 423 | break 424 | 425 | trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b 426 | assert len(trunc_tokens) >= 1 427 | 428 | # We want to sometimes truncate from the front and sometimes from the 429 | # back to add more randomness and avoid biases. 430 | if rng.random() < 0.5: 431 | del trunc_tokens[0] 432 | else: 433 | trunc_tokens.pop() 434 | 435 | 436 | def main(_): 437 | tf.logging.set_verbosity(tf.logging.INFO) 438 | 439 | tokenizer = tokenization.FullTokenizer( 440 | vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) 441 | 442 | input_files = [] 443 | for input_pattern in FLAGS.input_file.split(","): 444 | input_files.extend(tf.gfile.Glob(input_pattern)) 445 | 446 | tf.logging.info("*** Reading from input files ***") 447 | for input_file in input_files: 448 | tf.logging.info(" %s", input_file) 449 | 450 | rng = random.Random(FLAGS.random_seed) 451 | instances = create_training_instances( 452 | input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor, 453 | FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq, 454 | rng) 455 | 456 | output_files = FLAGS.output_file.split(",") 457 | tf.logging.info("*** Writing to output files ***") 458 | for output_file in output_files: 459 | tf.logging.info(" %s", output_file) 460 | 461 | write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length, 462 | FLAGS.max_predictions_per_seq, output_files) 463 | 464 | 465 | if __name__ == "__main__": 466 | flags.mark_flag_as_required("input_file") 467 | flags.mark_flag_as_required("output_file") 468 | flags.mark_flag_as_required("vocab_file") 469 | tf.app.run() 470 | -------------------------------------------------------------------------------- /bert/extract_features.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Extract pre-computed feature vectors from BERT.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import codecs 22 | import collections 23 | import json 24 | import re 25 | 26 | import modeling 27 | import tokenization 28 | import tensorflow as tf 29 | 30 | flags = tf.flags 31 | 32 | FLAGS = flags.FLAGS 33 | 34 | flags.DEFINE_string("input_file", None, "") 35 | 36 | flags.DEFINE_string("output_file", None, "") 37 | 38 | flags.DEFINE_string("layers", "-1,-2,-3,-4", "") 39 | 40 | flags.DEFINE_string( 41 | "bert_config_file", None, 42 | "The config json file corresponding to the pre-trained BERT model. " 43 | "This specifies the model architecture.") 44 | 45 | flags.DEFINE_integer( 46 | "max_seq_length", 128, 47 | "The maximum total input sequence length after WordPiece tokenization. " 48 | "Sequences longer than this will be truncated, and sequences shorter " 49 | "than this will be padded.") 50 | 51 | flags.DEFINE_string( 52 | "init_checkpoint", None, 53 | "Initial checkpoint (usually from a pre-trained BERT model).") 54 | 55 | flags.DEFINE_string("vocab_file", None, 56 | "The vocabulary file that the BERT model was trained on.") 57 | 58 | flags.DEFINE_bool( 59 | "do_lower_case", True, 60 | "Whether to lower case the input text. Should be True for uncased " 61 | "models and False for cased models.") 62 | 63 | flags.DEFINE_integer("batch_size", 32, "Batch size for predictions.") 64 | 65 | flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") 66 | 67 | flags.DEFINE_string("master", None, 68 | "If using a TPU, the address of the master.") 69 | 70 | flags.DEFINE_integer( 71 | "num_tpu_cores", 8, 72 | "Only used if `use_tpu` is True. Total number of TPU cores to use.") 73 | 74 | flags.DEFINE_bool( 75 | "use_one_hot_embeddings", False, 76 | "If True, tf.one_hot will be used for embedding lookups, otherwise " 77 | "tf.nn.embedding_lookup will be used. On TPUs, this should be True " 78 | "since it is much faster.") 79 | 80 | 81 | class InputExample(object): 82 | 83 | def __init__(self, unique_id, text_a, text_b): 84 | self.unique_id = unique_id 85 | self.text_a = text_a 86 | self.text_b = text_b 87 | 88 | 89 | class InputFeatures(object): 90 | """A single set of features of data.""" 91 | 92 | def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): 93 | self.unique_id = unique_id 94 | self.tokens = tokens 95 | self.input_ids = input_ids 96 | self.input_mask = input_mask 97 | self.input_type_ids = input_type_ids 98 | 99 | 100 | def input_fn_builder(features, seq_length): 101 | """Creates an `input_fn` closure to be passed to TPUEstimator.""" 102 | 103 | all_unique_ids = [] 104 | all_input_ids = [] 105 | all_input_mask = [] 106 | all_input_type_ids = [] 107 | 108 | for feature in features: 109 | all_unique_ids.append(feature.unique_id) 110 | all_input_ids.append(feature.input_ids) 111 | all_input_mask.append(feature.input_mask) 112 | all_input_type_ids.append(feature.input_type_ids) 113 | 114 | def input_fn(params): 115 | """The actual input function.""" 116 | batch_size = params["batch_size"] 117 | 118 | num_examples = len(features) 119 | 120 | # This is for demo purposes and does NOT scale to large data sets. We do 121 | # not use Dataset.from_generator() because that uses tf.py_func which is 122 | # not TPU compatible. The right way to load data is with TFRecordReader. 123 | d = tf.data.Dataset.from_tensor_slices({ 124 | "unique_ids": 125 | tf.constant(all_unique_ids, shape=[num_examples], dtype=tf.int32), 126 | "input_ids": 127 | tf.constant( 128 | all_input_ids, shape=[num_examples, seq_length], 129 | dtype=tf.int32), 130 | "input_mask": 131 | tf.constant( 132 | all_input_mask, 133 | shape=[num_examples, seq_length], 134 | dtype=tf.int32), 135 | "input_type_ids": 136 | tf.constant( 137 | all_input_type_ids, 138 | shape=[num_examples, seq_length], 139 | dtype=tf.int32), 140 | }) 141 | 142 | d = d.batch(batch_size=batch_size, drop_remainder=False) 143 | return d 144 | 145 | return input_fn 146 | 147 | 148 | def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu, 149 | use_one_hot_embeddings): 150 | """Returns `model_fn` closure for TPUEstimator.""" 151 | 152 | def model_fn(features, labels, mode, params): # pylint: disable=unused-argument 153 | """The `model_fn` for TPUEstimator.""" 154 | 155 | unique_ids = features["unique_ids"] 156 | input_ids = features["input_ids"] 157 | input_mask = features["input_mask"] 158 | input_type_ids = features["input_type_ids"] 159 | 160 | model = modeling.BertModel( 161 | config=bert_config, 162 | is_training=False, 163 | input_ids=input_ids, 164 | input_mask=input_mask, 165 | token_type_ids=input_type_ids, 166 | use_one_hot_embeddings=use_one_hot_embeddings) 167 | 168 | if mode != tf.estimator.ModeKeys.PREDICT: 169 | raise ValueError("Only PREDICT modes are supported: %s" % (mode)) 170 | 171 | tvars = tf.trainable_variables() 172 | scaffold_fn = None 173 | (assignment_map, 174 | initialized_variable_names) = modeling.get_assignment_map_from_checkpoint( 175 | tvars, init_checkpoint) 176 | if use_tpu: 177 | 178 | def tpu_scaffold(): 179 | tf.train.init_from_checkpoint(init_checkpoint, assignment_map) 180 | return tf.train.Scaffold() 181 | 182 | scaffold_fn = tpu_scaffold 183 | else: 184 | tf.train.init_from_checkpoint(init_checkpoint, assignment_map) 185 | 186 | tf.logging.info("**** Trainable Variables ****") 187 | for var in tvars: 188 | init_string = "" 189 | if var.name in initialized_variable_names: 190 | init_string = ", *INIT_FROM_CKPT*" 191 | tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, 192 | init_string) 193 | 194 | all_layers = model.get_all_encoder_layers() 195 | 196 | predictions = { 197 | "unique_id": unique_ids, 198 | } 199 | 200 | for (i, layer_index) in enumerate(layer_indexes): 201 | predictions["layer_output_%d" % i] = all_layers[layer_index] 202 | 203 | output_spec = tf.contrib.tpu.TPUEstimatorSpec( 204 | mode=mode, predictions=predictions, scaffold_fn=scaffold_fn) 205 | return output_spec 206 | 207 | return model_fn 208 | 209 | 210 | def convert_examples_to_features(examples, seq_length, tokenizer): 211 | """Loads a data file into a list of `InputBatch`s.""" 212 | 213 | features = [] 214 | for (ex_index, example) in enumerate(examples): 215 | tokens_a = tokenizer.tokenize(example.text_a) 216 | 217 | tokens_b = None 218 | if example.text_b: 219 | tokens_b = tokenizer.tokenize(example.text_b) 220 | 221 | if tokens_b: 222 | # Modifies `tokens_a` and `tokens_b` in place so that the total 223 | # length is less than the specified length. 224 | # Account for [CLS], [SEP], [SEP] with "- 3" 225 | _truncate_seq_pair(tokens_a, tokens_b, seq_length - 3) 226 | else: 227 | # Account for [CLS] and [SEP] with "- 2" 228 | if len(tokens_a) > seq_length - 2: 229 | tokens_a = tokens_a[0:(seq_length - 2)] 230 | 231 | # The convention in BERT is: 232 | # (a) For sequence pairs: 233 | # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] 234 | # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 235 | # (b) For single sequences: 236 | # tokens: [CLS] the dog is hairy . [SEP] 237 | # type_ids: 0 0 0 0 0 0 0 238 | # 239 | # Where "type_ids" are used to indicate whether this is the first 240 | # sequence or the second sequence. The embedding vectors for `type=0` and 241 | # `type=1` were learned during pre-training and are added to the wordpiece 242 | # embedding vector (and position vector). This is not *strictly* necessary 243 | # since the [SEP] token unambiguously separates the sequences, but it makes 244 | # it easier for the model to learn the concept of sequences. 245 | # 246 | # For classification tasks, the first vector (corresponding to [CLS]) is 247 | # used as as the "sentence vector". Note that this only makes sense because 248 | # the entire model is fine-tuned. 249 | tokens = [] 250 | input_type_ids = [] 251 | tokens.append("[CLS]") 252 | input_type_ids.append(0) 253 | for token in tokens_a: 254 | tokens.append(token) 255 | input_type_ids.append(0) 256 | tokens.append("[SEP]") 257 | input_type_ids.append(0) 258 | 259 | if tokens_b: 260 | for token in tokens_b: 261 | tokens.append(token) 262 | input_type_ids.append(1) 263 | tokens.append("[SEP]") 264 | input_type_ids.append(1) 265 | 266 | input_ids = tokenizer.convert_tokens_to_ids(tokens) 267 | 268 | # The mask has 1 for real tokens and 0 for padding tokens. Only real 269 | # tokens are attended to. 270 | input_mask = [1] * len(input_ids) 271 | 272 | # Zero-pad up to the sequence length. 273 | while len(input_ids) < seq_length: 274 | input_ids.append(0) 275 | input_mask.append(0) 276 | input_type_ids.append(0) 277 | 278 | assert len(input_ids) == seq_length 279 | assert len(input_mask) == seq_length 280 | assert len(input_type_ids) == seq_length 281 | 282 | if ex_index < 5: 283 | tf.logging.info("*** Example ***") 284 | tf.logging.info("unique_id: %s" % (example.unique_id)) 285 | tf.logging.info("tokens: %s" % " ".join( 286 | [tokenization.printable_text(x) for x in tokens])) 287 | tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) 288 | tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) 289 | tf.logging.info( 290 | "input_type_ids: %s" % " ".join([str(x) for x in input_type_ids])) 291 | 292 | features.append( 293 | InputFeatures( 294 | unique_id=example.unique_id, 295 | tokens=tokens, 296 | input_ids=input_ids, 297 | input_mask=input_mask, 298 | input_type_ids=input_type_ids)) 299 | return features 300 | 301 | 302 | def _truncate_seq_pair(tokens_a, tokens_b, max_length): 303 | """Truncates a sequence pair in place to the maximum length.""" 304 | 305 | # This is a simple heuristic which will always truncate the longer sequence 306 | # one token at a time. This makes more sense than truncating an equal percent 307 | # of tokens from each, since if one sequence is very short then each token 308 | # that's truncated likely contains more information than a longer sequence. 309 | while True: 310 | total_length = len(tokens_a) + len(tokens_b) 311 | if total_length <= max_length: 312 | break 313 | if len(tokens_a) > len(tokens_b): 314 | tokens_a.pop() 315 | else: 316 | tokens_b.pop() 317 | 318 | 319 | def read_examples(input_file): 320 | """Read a list of `InputExample`s from an input file.""" 321 | examples = [] 322 | unique_id = 0 323 | with tf.gfile.GFile(input_file, "r") as reader: 324 | while True: 325 | line = tokenization.convert_to_unicode(reader.readline()) 326 | if not line: 327 | break 328 | line = line.strip() 329 | text_a = None 330 | text_b = None 331 | m = re.match(r"^(.*) \|\|\| (.*)$", line) 332 | if m is None: 333 | text_a = line 334 | else: 335 | text_a = m.group(1) 336 | text_b = m.group(2) 337 | examples.append( 338 | InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b)) 339 | unique_id += 1 340 | return examples 341 | 342 | 343 | def main(_): 344 | tf.logging.set_verbosity(tf.logging.INFO) 345 | 346 | layer_indexes = [int(x) for x in FLAGS.layers.split(",")] 347 | 348 | bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) 349 | 350 | tokenizer = tokenization.FullTokenizer( 351 | vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) 352 | 353 | is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 354 | run_config = tf.contrib.tpu.RunConfig( 355 | master=FLAGS.master, 356 | tpu_config=tf.contrib.tpu.TPUConfig( 357 | num_shards=FLAGS.num_tpu_cores, 358 | per_host_input_for_training=is_per_host)) 359 | 360 | examples = read_examples(FLAGS.input_file) 361 | 362 | features = convert_examples_to_features( 363 | examples=examples, seq_length=FLAGS.max_seq_length, tokenizer=tokenizer) 364 | 365 | unique_id_to_feature = {} 366 | for feature in features: 367 | unique_id_to_feature[feature.unique_id] = feature 368 | 369 | model_fn = model_fn_builder( 370 | bert_config=bert_config, 371 | init_checkpoint=FLAGS.init_checkpoint, 372 | layer_indexes=layer_indexes, 373 | use_tpu=FLAGS.use_tpu, 374 | use_one_hot_embeddings=FLAGS.use_one_hot_embeddings) 375 | 376 | # If TPU is not available, this will fall back to normal Estimator on CPU 377 | # or GPU. 378 | estimator = tf.contrib.tpu.TPUEstimator( 379 | use_tpu=FLAGS.use_tpu, 380 | model_fn=model_fn, 381 | config=run_config, 382 | predict_batch_size=FLAGS.batch_size) 383 | 384 | input_fn = input_fn_builder( 385 | features=features, seq_length=FLAGS.max_seq_length) 386 | 387 | with codecs.getwriter("utf-8")(tf.gfile.Open(FLAGS.output_file, 388 | "w")) as writer: 389 | for result in estimator.predict(input_fn, yield_single_examples=True): 390 | unique_id = int(result["unique_id"]) 391 | feature = unique_id_to_feature[unique_id] 392 | output_json = collections.OrderedDict() 393 | output_json["linex_index"] = unique_id 394 | all_features = [] 395 | for (i, token) in enumerate(feature.tokens): 396 | all_layers = [] 397 | for (j, layer_index) in enumerate(layer_indexes): 398 | layer_output = result["layer_output_%d" % j] 399 | layers = collections.OrderedDict() 400 | layers["index"] = layer_index 401 | layers["values"] = [ 402 | round(float(x), 6) for x in layer_output[i:(i + 1)].flat 403 | ] 404 | all_layers.append(layers) 405 | features = collections.OrderedDict() 406 | features["token"] = token 407 | features["layers"] = all_layers 408 | all_features.append(features) 409 | output_json["features"] = all_features 410 | writer.write(json.dumps(output_json) + "\n") 411 | 412 | 413 | if __name__ == "__main__": 414 | flags.mark_flag_as_required("input_file") 415 | flags.mark_flag_as_required("vocab_file") 416 | flags.mark_flag_as_required("bert_config_file") 417 | flags.mark_flag_as_required("init_checkpoint") 418 | flags.mark_flag_as_required("output_file") 419 | tf.app.run() 420 | -------------------------------------------------------------------------------- /bert/modeling_test.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import collections 20 | import json 21 | import random 22 | import re 23 | 24 | import modeling 25 | import six 26 | import tensorflow as tf 27 | 28 | 29 | class BertModelTest(tf.test.TestCase): 30 | 31 | class BertModelTester(object): 32 | 33 | def __init__(self, 34 | parent, 35 | batch_size=13, 36 | seq_length=7, 37 | is_training=True, 38 | use_input_mask=True, 39 | use_token_type_ids=True, 40 | vocab_size=99, 41 | hidden_size=32, 42 | num_hidden_layers=5, 43 | num_attention_heads=4, 44 | intermediate_size=37, 45 | hidden_act="gelu", 46 | hidden_dropout_prob=0.1, 47 | attention_probs_dropout_prob=0.1, 48 | max_position_embeddings=512, 49 | type_vocab_size=16, 50 | initializer_range=0.02, 51 | scope=None): 52 | self.parent = parent 53 | self.batch_size = batch_size 54 | self.seq_length = seq_length 55 | self.is_training = is_training 56 | self.use_input_mask = use_input_mask 57 | self.use_token_type_ids = use_token_type_ids 58 | self.vocab_size = vocab_size 59 | self.hidden_size = hidden_size 60 | self.num_hidden_layers = num_hidden_layers 61 | self.num_attention_heads = num_attention_heads 62 | self.intermediate_size = intermediate_size 63 | self.hidden_act = hidden_act 64 | self.hidden_dropout_prob = hidden_dropout_prob 65 | self.attention_probs_dropout_prob = attention_probs_dropout_prob 66 | self.max_position_embeddings = max_position_embeddings 67 | self.type_vocab_size = type_vocab_size 68 | self.initializer_range = initializer_range 69 | self.scope = scope 70 | 71 | def create_model(self): 72 | input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length], 73 | self.vocab_size) 74 | 75 | input_mask = None 76 | if self.use_input_mask: 77 | input_mask = BertModelTest.ids_tensor( 78 | [self.batch_size, self.seq_length], vocab_size=2) 79 | 80 | token_type_ids = None 81 | if self.use_token_type_ids: 82 | token_type_ids = BertModelTest.ids_tensor( 83 | [self.batch_size, self.seq_length], self.type_vocab_size) 84 | 85 | config = modeling.BertConfig( 86 | vocab_size=self.vocab_size, 87 | hidden_size=self.hidden_size, 88 | num_hidden_layers=self.num_hidden_layers, 89 | num_attention_heads=self.num_attention_heads, 90 | intermediate_size=self.intermediate_size, 91 | hidden_act=self.hidden_act, 92 | hidden_dropout_prob=self.hidden_dropout_prob, 93 | attention_probs_dropout_prob=self.attention_probs_dropout_prob, 94 | max_position_embeddings=self.max_position_embeddings, 95 | type_vocab_size=self.type_vocab_size, 96 | initializer_range=self.initializer_range) 97 | 98 | model = modeling.BertModel( 99 | config=config, 100 | is_training=self.is_training, 101 | input_ids=input_ids, 102 | input_mask=input_mask, 103 | token_type_ids=token_type_ids, 104 | scope=self.scope) 105 | 106 | outputs = { 107 | "embedding_output": model.get_embedding_output(), 108 | "sequence_output": model.get_sequence_output(), 109 | "pooled_output": model.get_pooled_output(), 110 | "all_encoder_layers": model.get_all_encoder_layers(), 111 | } 112 | return outputs 113 | 114 | def check_output(self, result): 115 | self.parent.assertAllEqual( 116 | result["embedding_output"].shape, 117 | [self.batch_size, self.seq_length, self.hidden_size]) 118 | 119 | self.parent.assertAllEqual( 120 | result["sequence_output"].shape, 121 | [self.batch_size, self.seq_length, self.hidden_size]) 122 | 123 | self.parent.assertAllEqual(result["pooled_output"].shape, 124 | [self.batch_size, self.hidden_size]) 125 | 126 | def test_default(self): 127 | self.run_tester(BertModelTest.BertModelTester(self)) 128 | 129 | def test_config_to_json_string(self): 130 | config = modeling.BertConfig(vocab_size=99, hidden_size=37) 131 | obj = json.loads(config.to_json_string()) 132 | self.assertEqual(obj["vocab_size"], 99) 133 | self.assertEqual(obj["hidden_size"], 37) 134 | 135 | def run_tester(self, tester): 136 | with self.test_session() as sess: 137 | ops = tester.create_model() 138 | init_op = tf.group(tf.global_variables_initializer(), 139 | tf.local_variables_initializer()) 140 | sess.run(init_op) 141 | output_result = sess.run(ops) 142 | tester.check_output(output_result) 143 | 144 | self.assert_all_tensors_reachable(sess, [init_op, ops]) 145 | 146 | @classmethod 147 | def ids_tensor(cls, shape, vocab_size, rng=None, name=None): 148 | """Creates a random int32 tensor of the shape within the vocab size.""" 149 | if rng is None: 150 | rng = random.Random() 151 | 152 | total_dims = 1 153 | for dim in shape: 154 | total_dims *= dim 155 | 156 | values = [] 157 | for _ in range(total_dims): 158 | values.append(rng.randint(0, vocab_size - 1)) 159 | 160 | return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name) 161 | 162 | def assert_all_tensors_reachable(self, sess, outputs): 163 | """Checks that all the tensors in the graph are reachable from outputs.""" 164 | graph = sess.graph 165 | 166 | ignore_strings = [ 167 | "^.*/assert_less_equal/.*$", 168 | "^.*/dilation_rate$", 169 | "^.*/Tensordot/concat$", 170 | "^.*/Tensordot/concat/axis$", 171 | "^testing/.*$", 172 | ] 173 | 174 | ignore_regexes = [re.compile(x) for x in ignore_strings] 175 | 176 | unreachable = self.get_unreachable_ops(graph, outputs) 177 | filtered_unreachable = [] 178 | for x in unreachable: 179 | do_ignore = False 180 | for r in ignore_regexes: 181 | m = r.match(x.name) 182 | if m is not None: 183 | do_ignore = True 184 | if do_ignore: 185 | continue 186 | filtered_unreachable.append(x) 187 | unreachable = filtered_unreachable 188 | 189 | self.assertEqual( 190 | len(unreachable), 0, "The following ops are unreachable: %s" % 191 | (" ".join([x.name for x in unreachable]))) 192 | 193 | @classmethod 194 | def get_unreachable_ops(cls, graph, outputs): 195 | """Finds all of the tensors in graph that are unreachable from outputs.""" 196 | outputs = cls.flatten_recursive(outputs) 197 | output_to_op = collections.defaultdict(list) 198 | op_to_all = collections.defaultdict(list) 199 | assign_out_to_in = collections.defaultdict(list) 200 | 201 | for op in graph.get_operations(): 202 | for x in op.inputs: 203 | op_to_all[op.name].append(x.name) 204 | for y in op.outputs: 205 | output_to_op[y.name].append(op.name) 206 | op_to_all[op.name].append(y.name) 207 | if str(op.type) == "Assign": 208 | for y in op.outputs: 209 | for x in op.inputs: 210 | assign_out_to_in[y.name].append(x.name) 211 | 212 | assign_groups = collections.defaultdict(list) 213 | for out_name in assign_out_to_in.keys(): 214 | name_group = assign_out_to_in[out_name] 215 | for n1 in name_group: 216 | assign_groups[n1].append(out_name) 217 | for n2 in name_group: 218 | if n1 != n2: 219 | assign_groups[n1].append(n2) 220 | 221 | seen_tensors = {} 222 | stack = [x.name for x in outputs] 223 | while stack: 224 | name = stack.pop() 225 | if name in seen_tensors: 226 | continue 227 | seen_tensors[name] = True 228 | 229 | if name in output_to_op: 230 | for op_name in output_to_op[name]: 231 | if op_name in op_to_all: 232 | for input_name in op_to_all[op_name]: 233 | if input_name not in stack: 234 | stack.append(input_name) 235 | 236 | expanded_names = [] 237 | if name in assign_groups: 238 | for assign_name in assign_groups[name]: 239 | expanded_names.append(assign_name) 240 | 241 | for expanded_name in expanded_names: 242 | if expanded_name not in stack: 243 | stack.append(expanded_name) 244 | 245 | unreachable_ops = [] 246 | for op in graph.get_operations(): 247 | is_unreachable = False 248 | all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs] 249 | for name in all_names: 250 | if name not in seen_tensors: 251 | is_unreachable = True 252 | if is_unreachable: 253 | unreachable_ops.append(op) 254 | return unreachable_ops 255 | 256 | @classmethod 257 | def flatten_recursive(cls, item): 258 | """Flattens (potentially nested) a tuple/dictionary/list to a list.""" 259 | output = [] 260 | if isinstance(item, list): 261 | output.extend(item) 262 | elif isinstance(item, tuple): 263 | output.extend(list(item)) 264 | elif isinstance(item, dict): 265 | for (_, v) in six.iteritems(item): 266 | output.append(v) 267 | else: 268 | return [item] 269 | 270 | flat_output = [] 271 | for x in output: 272 | flat_output.extend(cls.flatten_recursive(x)) 273 | return flat_output 274 | 275 | 276 | if __name__ == "__main__": 277 | tf.test.main() 278 | -------------------------------------------------------------------------------- /bert/multilingual.md: -------------------------------------------------------------------------------- 1 | ## Models 2 | 3 | There are two multilingual models currently available. We do not plan to release 4 | more single-language models, but we may release `BERT-Large` versions of these 5 | two in the future: 6 | 7 | * **[`BERT-Base, Multilingual Cased (New, recommended)`](https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip)**: 8 | 104 languages, 12-layer, 768-hidden, 12-heads, 110M parameters 9 | * **[`BERT-Base, Multilingual Uncased (Orig, not recommended)`](https://storage.googleapis.com/bert_models/2018_11_03/multilingual_L-12_H-768_A-12.zip)**: 10 | 102 languages, 12-layer, 768-hidden, 12-heads, 110M parameters 11 | * **[`BERT-Base, Chinese`](https://storage.googleapis.com/bert_models/2018_11_03/chinese_L-12_H-768_A-12.zip)**: 12 | Chinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M 13 | parameters 14 | 15 | **The `Multilingual Cased (New)` model also fixes normalization issues in many 16 | languages, so it is recommended in languages with non-Latin alphabets (and is 17 | often better for most languages with Latin alphabets). When using this model, 18 | make sure to pass `--do_lower_case=false` to `run_pretraining.py` and other 19 | scripts.** 20 | 21 | See the [list of languages](#list-of-languages) that the Multilingual model 22 | supports. The Multilingual model does include Chinese (and English), but if your 23 | fine-tuning data is Chinese-only, then the Chinese model will likely produce 24 | better results. 25 | 26 | ## Results 27 | 28 | To evaluate these systems, we use the 29 | [XNLI dataset](https://github.com/facebookresearch/XNLI) dataset, which is a 30 | version of [MultiNLI](https://www.nyu.edu/projects/bowman/multinli/) where the 31 | dev and test sets have been translated (by humans) into 15 languages. Note that 32 | the training set was *machine* translated (we used the translations provided by 33 | XNLI, not Google NMT). For clarity, we only report on 6 languages below: 34 | 35 | 36 | 37 | | System | English | Chinese | Spanish | German | Arabic | Urdu | 38 | | --------------------------------- | -------- | -------- | -------- | -------- | -------- | -------- | 39 | | XNLI Baseline - Translate Train | 73.7 | 67.0 | 68.8 | 66.5 | 65.8 | 56.6 | 40 | | XNLI Baseline - Translate Test | 73.7 | 68.3 | 70.7 | 68.7 | 66.8 | 59.3 | 41 | | BERT - Translate Train Cased | **81.9** | **76.6** | **77.8** | **75.9** | **70.7** | 61.6 | 42 | | BERT - Translate Train Uncased | 81.4 | 74.2 | 77.3 | 75.2 | 70.5 | 61.7 | 43 | | BERT - Translate Test Uncased | 81.4 | 70.1 | 74.9 | 74.4 | 70.4 | **62.1** | 44 | | BERT - Zero Shot Uncased | 81.4 | 63.8 | 74.3 | 70.5 | 62.1 | 58.3 | 45 | 46 | 47 | 48 | The first two rows are baselines from the XNLI paper and the last three rows are 49 | our results with BERT. 50 | 51 | **Translate Train** means that the MultiNLI training set was machine translated 52 | from English into the foreign language. So training and evaluation were both 53 | done in the foreign language. Unfortunately, training was done on 54 | machine-translated data, so it is impossible to quantify how much of the lower 55 | accuracy (compared to English) is due to the quality of the machine translation 56 | vs. the quality of the pre-trained model. 57 | 58 | **Translate Test** means that the XNLI test set was machine translated from the 59 | foreign language into English. So training and evaluation were both done on 60 | English. However, test evaluation was done on machine-translated English, so the 61 | accuracy depends on the quality of the machine translation system. 62 | 63 | **Zero Shot** means that the Multilingual BERT system was fine-tuned on English 64 | MultiNLI, and then evaluated on the foreign language XNLI test. In this case, 65 | machine translation was not involved at all in either the pre-training or 66 | fine-tuning. 67 | 68 | Note that the English result is worse than the 84.2 MultiNLI baseline because 69 | this training used Multilingual BERT rather than English-only BERT. This implies 70 | that for high-resource languages, the Multilingual model is somewhat worse than 71 | a single-language model. However, it is not feasible for us to train and 72 | maintain dozens of single-language models. Therefore, if your goal is to maximize 73 | performance with a language other than English or Chinese, you might find it 74 | beneficial to run pre-training for additional steps starting from our 75 | Multilingual model on data from your language of interest. 76 | 77 | Here is a comparison of training Chinese models with the Multilingual 78 | `BERT-Base` and Chinese-only `BERT-Base`: 79 | 80 | System | Chinese 81 | ----------------------- | ------- 82 | XNLI Baseline | 67.0 83 | BERT Multilingual Model | 74.2 84 | BERT Chinese-only Model | 77.2 85 | 86 | Similar to English, the single-language model does 3% better than the 87 | Multilingual model. 88 | 89 | ## Fine-tuning Example 90 | 91 | The multilingual model does **not** require any special consideration or API 92 | changes. We did update the implementation of `BasicTokenizer` in 93 | `tokenization.py` to support Chinese character tokenization, so please update if 94 | you forked it. However, we did not change the tokenization API. 95 | 96 | To test the new models, we did modify `run_classifier.py` to add support for the 97 | [XNLI dataset](https://github.com/facebookresearch/XNLI). This is a 15-language 98 | version of MultiNLI where the dev/test sets have been human-translated, and the 99 | training set has been machine-translated. 100 | 101 | To run the fine-tuning code, please download the 102 | [XNLI dev/test set](https://www.nyu.edu/projects/bowman/xnli/XNLI-1.0.zip) and the 103 | [XNLI machine-translated training set](https://www.nyu.edu/projects/bowman/xnli/XNLI-MT-1.0.zip) 104 | and then unpack both .zip files into some directory `$XNLI_DIR`. 105 | 106 | To run fine-tuning on XNLI. The language is hard-coded into `run_classifier.py` 107 | (Chinese by default), so please modify `XnliProcessor` if you want to run on 108 | another language. 109 | 110 | This is a large dataset, so this will training will take a few hours on a GPU 111 | (or about 30 minutes on a Cloud TPU). To run an experiment quickly for 112 | debugging, just set `num_train_epochs` to a small value like `0.1`. 113 | 114 | ```shell 115 | export BERT_BASE_DIR=/path/to/bert/chinese_L-12_H-768_A-12 # or multilingual_L-12_H-768_A-12 116 | export XNLI_DIR=/path/to/xnli 117 | 118 | python run_classifier.py \ 119 | --task_name=XNLI \ 120 | --do_train=true \ 121 | --do_eval=true \ 122 | --data_dir=$XNLI_DIR \ 123 | --vocab_file=$BERT_BASE_DIR/vocab.txt \ 124 | --bert_config_file=$BERT_BASE_DIR/bert_config.json \ 125 | --init_checkpoint=$BERT_BASE_DIR/bert_model.ckpt \ 126 | --max_seq_length=128 \ 127 | --train_batch_size=32 \ 128 | --learning_rate=5e-5 \ 129 | --num_train_epochs=2.0 \ 130 | --output_dir=/tmp/xnli_output/ 131 | ``` 132 | 133 | With the Chinese-only model, the results should look something like this: 134 | 135 | ``` 136 | ***** Eval results ***** 137 | eval_accuracy = 0.774116 138 | eval_loss = 0.83554 139 | global_step = 24543 140 | loss = 0.74603 141 | ``` 142 | 143 | ## Details 144 | 145 | ### Data Source and Sampling 146 | 147 | The languages chosen were the 148 | [top 100 languages with the largest Wikipedias](https://meta.wikimedia.org/wiki/List_of_Wikipedias). 149 | The entire Wikipedia dump for each language (excluding user and talk pages) was 150 | taken as the training data for each language 151 | 152 | However, the size of the Wikipedia for a given language varies greatly, and 153 | therefore low-resource languages may be "under-represented" in terms of the 154 | neural network model (under the assumption that languages are "competing" for 155 | limited model capacity to some extent). At the same time, we also don't want 156 | to overfit the model by performing thousands of epochs over a tiny Wikipedia 157 | for a particular language. 158 | 159 | To balance these two factors, we performed exponentially smoothed weighting of 160 | the data during pre-training data creation (and WordPiece vocab creation). In 161 | other words, let's say that the probability of a language is *P(L)*, e.g., 162 | *P(English) = 0.21* means that after concatenating all of the Wikipedias 163 | together, 21% of our data is English. We exponentiate each probability by some 164 | factor *S* and then re-normalize, and sample from that distribution. In our case 165 | we use *S=0.7*. So, high-resource languages like English will be under-sampled, 166 | and low-resource languages like Icelandic will be over-sampled. E.g., in the 167 | original distribution English would be sampled 1000x more than Icelandic, but 168 | after smoothing it's only sampled 100x more. 169 | 170 | ### Tokenization 171 | 172 | For tokenization, we use a 110k shared WordPiece vocabulary. The word counts are 173 | weighted the same way as the data, so low-resource languages are upweighted by 174 | some factor. We intentionally do *not* use any marker to denote the input 175 | language (so that zero-shot training can work). 176 | 177 | Because Chinese (and Japanese Kanji and Korean Hanja) does not have whitespace 178 | characters, we add spaces around every character in the 179 | [CJK Unicode range](https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_\(Unicode_block\)) 180 | before applying WordPiece. This means that Chinese is effectively 181 | character-tokenized. Note that the CJK Unicode block only includes 182 | Chinese-origin characters and does *not* include Hangul Korean or 183 | Katakana/Hiragana Japanese, which are tokenized with whitespace+WordPiece like 184 | all other languages. 185 | 186 | For all other languages, we apply the 187 | [same recipe as English](https://github.com/google-research/bert#tokenization): 188 | (a) lower casing+accent removal, (b) punctuation splitting, (c) whitespace 189 | tokenization. We understand that accent markers have substantial meaning in some 190 | languages, but felt that the benefits of reducing the effective vocabulary make 191 | up for this. Generally the strong contextual models of BERT should make up for 192 | any ambiguity introduced by stripping accent markers. 193 | 194 | ### List of Languages 195 | 196 | The multilingual model supports the following languages. These languages were 197 | chosen because they are the top 100 languages with the largest Wikipedias: 198 | 199 | * Afrikaans 200 | * Albanian 201 | * Arabic 202 | * Aragonese 203 | * Armenian 204 | * Asturian 205 | * Azerbaijani 206 | * Bashkir 207 | * Basque 208 | * Bavarian 209 | * Belarusian 210 | * Bengali 211 | * Bishnupriya Manipuri 212 | * Bosnian 213 | * Breton 214 | * Bulgarian 215 | * Burmese 216 | * Catalan 217 | * Cebuano 218 | * Chechen 219 | * Chinese (Simplified) 220 | * Chinese (Traditional) 221 | * Chuvash 222 | * Croatian 223 | * Czech 224 | * Danish 225 | * Dutch 226 | * English 227 | * Estonian 228 | * Finnish 229 | * French 230 | * Galician 231 | * Georgian 232 | * German 233 | * Greek 234 | * Gujarati 235 | * Haitian 236 | * Hebrew 237 | * Hindi 238 | * Hungarian 239 | * Icelandic 240 | * Ido 241 | * Indonesian 242 | * Irish 243 | * Italian 244 | * Japanese 245 | * Javanese 246 | * Kannada 247 | * Kazakh 248 | * Kirghiz 249 | * Korean 250 | * Latin 251 | * Latvian 252 | * Lithuanian 253 | * Lombard 254 | * Low Saxon 255 | * Luxembourgish 256 | * Macedonian 257 | * Malagasy 258 | * Malay 259 | * Malayalam 260 | * Marathi 261 | * Minangkabau 262 | * Nepali 263 | * Newar 264 | * Norwegian (Bokmal) 265 | * Norwegian (Nynorsk) 266 | * Occitan 267 | * Persian (Farsi) 268 | * Piedmontese 269 | * Polish 270 | * Portuguese 271 | * Punjabi 272 | * Romanian 273 | * Russian 274 | * Scots 275 | * Serbian 276 | * Serbo-Croatian 277 | * Sicilian 278 | * Slovak 279 | * Slovenian 280 | * South Azerbaijani 281 | * Spanish 282 | * Sundanese 283 | * Swahili 284 | * Swedish 285 | * Tagalog 286 | * Tajik 287 | * Tamil 288 | * Tatar 289 | * Telugu 290 | * Turkish 291 | * Ukrainian 292 | * Urdu 293 | * Uzbek 294 | * Vietnamese 295 | * Volapük 296 | * Waray-Waray 297 | * Welsh 298 | * West Frisian 299 | * Western Punjabi 300 | * Yoruba 301 | 302 | The **Multilingual Cased (New)** release contains additionally **Thai** and 303 | **Mongolian**, which were not included in the original release. 304 | -------------------------------------------------------------------------------- /bert/optimization.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Functions and classes related to optimization (weight updates).""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import re 22 | import tensorflow as tf 23 | 24 | 25 | def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu): 26 | """Creates an optimizer training op.""" 27 | global_step = tf.train.get_or_create_global_step() 28 | 29 | learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32) 30 | 31 | # Implements linear decay of the learning rate. 32 | learning_rate = tf.train.polynomial_decay( 33 | learning_rate, 34 | global_step, 35 | num_train_steps, 36 | end_learning_rate=0.0, 37 | power=1.0, 38 | cycle=False) 39 | 40 | # Implements linear warmup. I.e., if global_step < num_warmup_steps, the 41 | # learning rate will be `global_step/num_warmup_steps * init_lr`. 42 | if num_warmup_steps: 43 | global_steps_int = tf.cast(global_step, tf.int32) 44 | warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32) 45 | 46 | global_steps_float = tf.cast(global_steps_int, tf.float32) 47 | warmup_steps_float = tf.cast(warmup_steps_int, tf.float32) 48 | 49 | warmup_percent_done = global_steps_float / warmup_steps_float 50 | warmup_learning_rate = init_lr * warmup_percent_done 51 | 52 | is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32) 53 | learning_rate = ( 54 | (1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate) 55 | 56 | # It is recommended that you use this optimizer for fine tuning, since this 57 | # is how the model was trained (note that the Adam m/v variables are NOT 58 | # loaded from init_checkpoint.) 59 | optimizer = AdamWeightDecayOptimizer( 60 | learning_rate=learning_rate, 61 | weight_decay_rate=0.01, 62 | beta_1=0.9, 63 | beta_2=0.999, 64 | epsilon=1e-6, 65 | exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]) 66 | 67 | if use_tpu: 68 | optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) 69 | 70 | tvars = tf.trainable_variables() 71 | grads = tf.gradients(loss, tvars) 72 | 73 | # This is how the model was pre-trained. 74 | (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0) 75 | 76 | train_op = optimizer.apply_gradients( 77 | zip(grads, tvars), global_step=global_step) 78 | 79 | # Normally the global step update is done inside of `apply_gradients`. 80 | # However, `AdamWeightDecayOptimizer` doesn't do this. But if you use 81 | # a different optimizer, you should probably take this line out. 82 | new_global_step = global_step + 1 83 | train_op = tf.group(train_op, [global_step.assign(new_global_step)]) 84 | return train_op 85 | 86 | 87 | class AdamWeightDecayOptimizer(tf.train.Optimizer): 88 | """A basic Adam optimizer that includes "correct" L2 weight decay.""" 89 | 90 | def __init__(self, 91 | learning_rate, 92 | weight_decay_rate=0.0, 93 | beta_1=0.9, 94 | beta_2=0.999, 95 | epsilon=1e-6, 96 | exclude_from_weight_decay=None, 97 | name="AdamWeightDecayOptimizer"): 98 | """Constructs a AdamWeightDecayOptimizer.""" 99 | super(AdamWeightDecayOptimizer, self).__init__(False, name) 100 | 101 | self.learning_rate = learning_rate 102 | self.weight_decay_rate = weight_decay_rate 103 | self.beta_1 = beta_1 104 | self.beta_2 = beta_2 105 | self.epsilon = epsilon 106 | self.exclude_from_weight_decay = exclude_from_weight_decay 107 | 108 | def apply_gradients(self, grads_and_vars, global_step=None, name=None): 109 | """See base class.""" 110 | assignments = [] 111 | for (grad, param) in grads_and_vars: 112 | if grad is None or param is None: 113 | continue 114 | 115 | param_name = self._get_variable_name(param.name) 116 | 117 | m = tf.get_variable( 118 | name=param_name + "/adam_m", 119 | shape=param.shape.as_list(), 120 | dtype=tf.float32, 121 | trainable=False, 122 | initializer=tf.zeros_initializer()) 123 | v = tf.get_variable( 124 | name=param_name + "/adam_v", 125 | shape=param.shape.as_list(), 126 | dtype=tf.float32, 127 | trainable=False, 128 | initializer=tf.zeros_initializer()) 129 | 130 | # Standard Adam update. 131 | next_m = ( 132 | tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad)) 133 | next_v = ( 134 | tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2, 135 | tf.square(grad))) 136 | 137 | update = next_m / (tf.sqrt(next_v) + self.epsilon) 138 | 139 | # Just adding the square of the weights to the loss function is *not* 140 | # the correct way of using L2 regularization/weight decay with Adam, 141 | # since that will interact with the m and v parameters in strange ways. 142 | # 143 | # Instead we want ot decay the weights in a manner that doesn't interact 144 | # with the m/v parameters. This is equivalent to adding the square 145 | # of the weights to the loss with plain (non-momentum) SGD. 146 | if self._do_use_weight_decay(param_name): 147 | update += self.weight_decay_rate * param 148 | 149 | update_with_lr = self.learning_rate * update 150 | 151 | next_param = param - update_with_lr 152 | 153 | assignments.extend( 154 | [param.assign(next_param), 155 | m.assign(next_m), 156 | v.assign(next_v)]) 157 | return tf.group(*assignments, name=name) 158 | 159 | def _do_use_weight_decay(self, param_name): 160 | """Whether to use L2 weight decay for `param_name`.""" 161 | if not self.weight_decay_rate: 162 | return False 163 | if self.exclude_from_weight_decay: 164 | for r in self.exclude_from_weight_decay: 165 | if re.search(r, param_name) is not None: 166 | return False 167 | return True 168 | 169 | def _get_variable_name(self, param_name): 170 | """Get the variable name from the tensor name.""" 171 | m = re.match("^(.*):\\d+$", param_name) 172 | if m is not None: 173 | param_name = m.group(1) 174 | return param_name 175 | -------------------------------------------------------------------------------- /bert/optimization_test.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import optimization 20 | import tensorflow as tf 21 | 22 | 23 | class OptimizationTest(tf.test.TestCase): 24 | 25 | def test_adam(self): 26 | with self.test_session() as sess: 27 | w = tf.get_variable( 28 | "w", 29 | shape=[3], 30 | initializer=tf.constant_initializer([0.1, -0.2, -0.1])) 31 | x = tf.constant([0.4, 0.2, -0.5]) 32 | loss = tf.reduce_mean(tf.square(x - w)) 33 | tvars = tf.trainable_variables() 34 | grads = tf.gradients(loss, tvars) 35 | global_step = tf.train.get_or_create_global_step() 36 | optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2) 37 | train_op = optimizer.apply_gradients(zip(grads, tvars), global_step) 38 | init_op = tf.group(tf.global_variables_initializer(), 39 | tf.local_variables_initializer()) 40 | sess.run(init_op) 41 | for _ in range(100): 42 | sess.run(train_op) 43 | w_np = sess.run(w) 44 | self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2) 45 | 46 | 47 | if __name__ == "__main__": 48 | tf.test.main() 49 | -------------------------------------------------------------------------------- /bert/requirements.txt: -------------------------------------------------------------------------------- 1 | tensorflow >= 1.11.0 # CPU Version of TensorFlow. 2 | # tensorflow-gpu >= 1.11.0 # GPU version of TensorFlow. 3 | -------------------------------------------------------------------------------- /bert/run_classifier_with_tfhub.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """BERT finetuning runner with TF-Hub.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import os 22 | import optimization 23 | import run_classifier 24 | import tokenization 25 | import tensorflow as tf 26 | import tensorflow_hub as hub 27 | 28 | flags = tf.flags 29 | 30 | FLAGS = flags.FLAGS 31 | 32 | flags.DEFINE_string( 33 | "bert_hub_module_handle", None, 34 | "Handle for the BERT TF-Hub module.") 35 | 36 | 37 | def create_model(is_training, input_ids, input_mask, segment_ids, labels, 38 | num_labels, bert_hub_module_handle): 39 | """Creates a classification model.""" 40 | tags = set() 41 | if is_training: 42 | tags.add("train") 43 | bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True) 44 | bert_inputs = dict( 45 | input_ids=input_ids, 46 | input_mask=input_mask, 47 | segment_ids=segment_ids) 48 | bert_outputs = bert_module( 49 | inputs=bert_inputs, 50 | signature="tokens", 51 | as_dict=True) 52 | 53 | # In the demo, we are doing a simple classification task on the entire 54 | # segment. 55 | # 56 | # If you want to use the token-level output, use 57 | # bert_outputs["sequence_output"] instead. 58 | output_layer = bert_outputs["pooled_output"] 59 | 60 | hidden_size = output_layer.shape[-1].value 61 | 62 | output_weights = tf.get_variable( 63 | "output_weights", [num_labels, hidden_size], 64 | initializer=tf.truncated_normal_initializer(stddev=0.02)) 65 | 66 | output_bias = tf.get_variable( 67 | "output_bias", [num_labels], initializer=tf.zeros_initializer()) 68 | 69 | with tf.variable_scope("loss"): 70 | if is_training: 71 | # I.e., 0.1 dropout 72 | output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) 73 | 74 | logits = tf.matmul(output_layer, output_weights, transpose_b=True) 75 | logits = tf.nn.bias_add(logits, output_bias) 76 | probabilities = tf.nn.softmax(logits, axis=-1) 77 | log_probs = tf.nn.log_softmax(logits, axis=-1) 78 | 79 | one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) 80 | 81 | per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) 82 | loss = tf.reduce_mean(per_example_loss) 83 | 84 | return (loss, per_example_loss, logits, probabilities) 85 | 86 | 87 | def model_fn_builder(num_labels, learning_rate, num_train_steps, 88 | num_warmup_steps, use_tpu, bert_hub_module_handle): 89 | """Returns `model_fn` closure for TPUEstimator.""" 90 | 91 | def model_fn(features, labels, mode, params): # pylint: disable=unused-argument 92 | """The `model_fn` for TPUEstimator.""" 93 | 94 | tf.logging.info("*** Features ***") 95 | for name in sorted(features.keys()): 96 | tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) 97 | 98 | input_ids = features["input_ids"] 99 | input_mask = features["input_mask"] 100 | segment_ids = features["segment_ids"] 101 | label_ids = features["label_ids"] 102 | 103 | is_training = (mode == tf.estimator.ModeKeys.TRAIN) 104 | 105 | (total_loss, per_example_loss, logits, probabilities) = create_model( 106 | is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, 107 | bert_hub_module_handle) 108 | 109 | output_spec = None 110 | if mode == tf.estimator.ModeKeys.TRAIN: 111 | train_op = optimization.create_optimizer( 112 | total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) 113 | 114 | output_spec = tf.contrib.tpu.TPUEstimatorSpec( 115 | mode=mode, 116 | loss=total_loss, 117 | train_op=train_op) 118 | elif mode == tf.estimator.ModeKeys.EVAL: 119 | 120 | def metric_fn(per_example_loss, label_ids, logits): 121 | predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) 122 | accuracy = tf.metrics.accuracy(label_ids, predictions) 123 | loss = tf.metrics.mean(per_example_loss) 124 | return { 125 | "eval_accuracy": accuracy, 126 | "eval_loss": loss, 127 | } 128 | 129 | eval_metrics = (metric_fn, [per_example_loss, label_ids, logits]) 130 | output_spec = tf.contrib.tpu.TPUEstimatorSpec( 131 | mode=mode, 132 | loss=total_loss, 133 | eval_metrics=eval_metrics) 134 | elif mode == tf.estimator.ModeKeys.PREDICT: 135 | output_spec = tf.contrib.tpu.TPUEstimatorSpec( 136 | mode=mode, predictions={"probabilities": probabilities}) 137 | else: 138 | raise ValueError( 139 | "Only TRAIN, EVAL and PREDICT modes are supported: %s" % (mode)) 140 | 141 | return output_spec 142 | 143 | return model_fn 144 | 145 | 146 | def create_tokenizer_from_hub_module(bert_hub_module_handle): 147 | """Get the vocab file and casing info from the Hub module.""" 148 | with tf.Graph().as_default(): 149 | bert_module = hub.Module(bert_hub_module_handle) 150 | tokenization_info = bert_module(signature="tokenization_info", as_dict=True) 151 | with tf.Session() as sess: 152 | vocab_file, do_lower_case = sess.run([tokenization_info["vocab_file"], 153 | tokenization_info["do_lower_case"]]) 154 | return tokenization.FullTokenizer( 155 | vocab_file=vocab_file, do_lower_case=do_lower_case) 156 | 157 | 158 | def main(_): 159 | tf.logging.set_verbosity(tf.logging.INFO) 160 | 161 | processors = { 162 | "cola": run_classifier.ColaProcessor, 163 | "mnli": run_classifier.MnliProcessor, 164 | "mrpc": run_classifier.MrpcProcessor, 165 | } 166 | 167 | if not FLAGS.do_train and not FLAGS.do_eval: 168 | raise ValueError("At least one of `do_train` or `do_eval` must be True.") 169 | 170 | tf.gfile.MakeDirs(FLAGS.output_dir) 171 | 172 | task_name = FLAGS.task_name.lower() 173 | 174 | if task_name not in processors: 175 | raise ValueError("Task not found: %s" % (task_name)) 176 | 177 | processor = processors[task_name]() 178 | 179 | label_list = processor.get_labels() 180 | 181 | tokenizer = create_tokenizer_from_hub_module(FLAGS.bert_hub_module_handle) 182 | 183 | tpu_cluster_resolver = None 184 | if FLAGS.use_tpu and FLAGS.tpu_name: 185 | tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( 186 | FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) 187 | 188 | is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 189 | run_config = tf.contrib.tpu.RunConfig( 190 | cluster=tpu_cluster_resolver, 191 | master=FLAGS.master, 192 | model_dir=FLAGS.output_dir, 193 | save_checkpoints_steps=FLAGS.save_checkpoints_steps, 194 | tpu_config=tf.contrib.tpu.TPUConfig( 195 | iterations_per_loop=FLAGS.iterations_per_loop, 196 | num_shards=FLAGS.num_tpu_cores, 197 | per_host_input_for_training=is_per_host)) 198 | 199 | train_examples = None 200 | num_train_steps = None 201 | num_warmup_steps = None 202 | if FLAGS.do_train: 203 | train_examples = processor.get_train_examples(FLAGS.data_dir) 204 | num_train_steps = int( 205 | len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs) 206 | num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) 207 | 208 | model_fn = model_fn_builder( 209 | num_labels=len(label_list), 210 | learning_rate=FLAGS.learning_rate, 211 | num_train_steps=num_train_steps, 212 | num_warmup_steps=num_warmup_steps, 213 | use_tpu=FLAGS.use_tpu, 214 | bert_hub_module_handle=FLAGS.bert_hub_module_handle) 215 | 216 | # If TPU is not available, this will fall back to normal Estimator on CPU 217 | # or GPU. 218 | estimator = tf.contrib.tpu.TPUEstimator( 219 | use_tpu=FLAGS.use_tpu, 220 | model_fn=model_fn, 221 | config=run_config, 222 | train_batch_size=FLAGS.train_batch_size, 223 | eval_batch_size=FLAGS.eval_batch_size, 224 | predict_batch_size=FLAGS.predict_batch_size) 225 | 226 | if FLAGS.do_train: 227 | train_features = run_classifier.convert_examples_to_features( 228 | train_examples, label_list, FLAGS.max_seq_length, tokenizer) 229 | tf.logging.info("***** Running training *****") 230 | tf.logging.info(" Num examples = %d", len(train_examples)) 231 | tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) 232 | tf.logging.info(" Num steps = %d", num_train_steps) 233 | train_input_fn = run_classifier.input_fn_builder( 234 | features=train_features, 235 | seq_length=FLAGS.max_seq_length, 236 | is_training=True, 237 | drop_remainder=True) 238 | estimator.train(input_fn=train_input_fn, max_steps=num_train_steps) 239 | 240 | if FLAGS.do_eval: 241 | eval_examples = processor.get_dev_examples(FLAGS.data_dir) 242 | eval_features = run_classifier.convert_examples_to_features( 243 | eval_examples, label_list, FLAGS.max_seq_length, tokenizer) 244 | 245 | tf.logging.info("***** Running evaluation *****") 246 | tf.logging.info(" Num examples = %d", len(eval_examples)) 247 | tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size) 248 | 249 | # This tells the estimator to run through the entire set. 250 | eval_steps = None 251 | # However, if running eval on the TPU, you will need to specify the 252 | # number of steps. 253 | if FLAGS.use_tpu: 254 | # Eval will be slightly WRONG on the TPU because it will truncate 255 | # the last batch. 256 | eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size) 257 | 258 | eval_drop_remainder = True if FLAGS.use_tpu else False 259 | eval_input_fn = run_classifier.input_fn_builder( 260 | features=eval_features, 261 | seq_length=FLAGS.max_seq_length, 262 | is_training=False, 263 | drop_remainder=eval_drop_remainder) 264 | 265 | result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps) 266 | 267 | output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") 268 | with tf.gfile.GFile(output_eval_file, "w") as writer: 269 | tf.logging.info("***** Eval results *****") 270 | for key in sorted(result.keys()): 271 | tf.logging.info(" %s = %s", key, str(result[key])) 272 | writer.write("%s = %s\n" % (key, str(result[key]))) 273 | 274 | if FLAGS.do_predict: 275 | predict_examples = processor.get_test_examples(FLAGS.data_dir) 276 | if FLAGS.use_tpu: 277 | # Discard batch remainder if running on TPU 278 | n = len(predict_examples) 279 | predict_examples = predict_examples[:(n - n % FLAGS.predict_batch_size)] 280 | 281 | predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record") 282 | run_classifier.file_based_convert_examples_to_features( 283 | predict_examples, label_list, FLAGS.max_seq_length, tokenizer, 284 | predict_file) 285 | 286 | tf.logging.info("***** Running prediction*****") 287 | tf.logging.info(" Num examples = %d", len(predict_examples)) 288 | tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size) 289 | 290 | predict_input_fn = run_classifier.file_based_input_fn_builder( 291 | input_file=predict_file, 292 | seq_length=FLAGS.max_seq_length, 293 | is_training=False, 294 | drop_remainder=FLAGS.use_tpu) 295 | 296 | result = estimator.predict(input_fn=predict_input_fn) 297 | 298 | output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv") 299 | with tf.gfile.GFile(output_predict_file, "w") as writer: 300 | tf.logging.info("***** Predict results *****") 301 | for prediction in result: 302 | probabilities = prediction["probabilities"] 303 | output_line = "\t".join( 304 | str(class_probability) 305 | for class_probability in probabilities) + "\n" 306 | writer.write(output_line) 307 | 308 | 309 | if __name__ == "__main__": 310 | flags.mark_flag_as_required("data_dir") 311 | flags.mark_flag_as_required("task_name") 312 | flags.mark_flag_as_required("bert_hub_module_handle") 313 | flags.mark_flag_as_required("output_dir") 314 | tf.app.run() 315 | -------------------------------------------------------------------------------- /bert/run_pretraining.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Run masked LM/next sentence masked_lm pre-training for BERT.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import os 22 | import modeling 23 | import optimization 24 | import tensorflow as tf 25 | 26 | flags = tf.flags 27 | 28 | FLAGS = flags.FLAGS 29 | 30 | ## Required parameters 31 | flags.DEFINE_string( 32 | "bert_config_file", None, 33 | "The config json file corresponding to the pre-trained BERT model. " 34 | "This specifies the model architecture.") 35 | 36 | flags.DEFINE_string( 37 | "input_file", None, 38 | "Input TF example files (can be a glob or comma separated).") 39 | 40 | flags.DEFINE_string( 41 | "output_dir", None, 42 | "The output directory where the model checkpoints will be written.") 43 | 44 | ## Other parameters 45 | flags.DEFINE_string( 46 | "init_checkpoint", None, 47 | "Initial checkpoint (usually from a pre-trained BERT model).") 48 | 49 | flags.DEFINE_integer( 50 | "max_seq_length", 128, 51 | "The maximum total input sequence length after WordPiece tokenization. " 52 | "Sequences longer than this will be truncated, and sequences shorter " 53 | "than this will be padded. Must match data generation.") 54 | 55 | flags.DEFINE_integer( 56 | "max_predictions_per_seq", 20, 57 | "Maximum number of masked LM predictions per sequence. " 58 | "Must match data generation.") 59 | 60 | flags.DEFINE_bool("do_train", False, "Whether to run training.") 61 | 62 | flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.") 63 | 64 | flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.") 65 | 66 | flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.") 67 | 68 | flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.") 69 | 70 | flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.") 71 | 72 | flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.") 73 | 74 | flags.DEFINE_integer("save_checkpoints_steps", 1000, 75 | "How often to save the model checkpoint.") 76 | 77 | flags.DEFINE_integer("iterations_per_loop", 1000, 78 | "How many steps to make in each estimator call.") 79 | 80 | flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.") 81 | 82 | flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") 83 | 84 | tf.flags.DEFINE_string( 85 | "tpu_name", None, 86 | "The Cloud TPU to use for training. This should be either the name " 87 | "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " 88 | "url.") 89 | 90 | tf.flags.DEFINE_string( 91 | "tpu_zone", None, 92 | "[Optional] GCE zone where the Cloud TPU is located in. If not " 93 | "specified, we will attempt to automatically detect the GCE project from " 94 | "metadata.") 95 | 96 | tf.flags.DEFINE_string( 97 | "gcp_project", None, 98 | "[Optional] Project name for the Cloud TPU-enabled project. If not " 99 | "specified, we will attempt to automatically detect the GCE project from " 100 | "metadata.") 101 | 102 | tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") 103 | 104 | flags.DEFINE_integer( 105 | "num_tpu_cores", 8, 106 | "Only used if `use_tpu` is True. Total number of TPU cores to use.") 107 | 108 | 109 | def model_fn_builder(bert_config, init_checkpoint, learning_rate, 110 | num_train_steps, num_warmup_steps, use_tpu, 111 | use_one_hot_embeddings): 112 | """Returns `model_fn` closure for TPUEstimator.""" 113 | 114 | def model_fn(features, labels, mode, params): # pylint: disable=unused-argument 115 | """The `model_fn` for TPUEstimator.""" 116 | 117 | tf.logging.info("*** Features ***") 118 | for name in sorted(features.keys()): 119 | tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) 120 | 121 | input_ids = features["input_ids"] 122 | input_mask = features["input_mask"] 123 | segment_ids = features["segment_ids"] 124 | masked_lm_positions = features["masked_lm_positions"] 125 | masked_lm_ids = features["masked_lm_ids"] 126 | masked_lm_weights = features["masked_lm_weights"] 127 | next_sentence_labels = features["next_sentence_labels"] 128 | 129 | is_training = (mode == tf.estimator.ModeKeys.TRAIN) 130 | 131 | model = modeling.BertModel( 132 | config=bert_config, 133 | is_training=is_training, 134 | input_ids=input_ids, 135 | input_mask=input_mask, 136 | token_type_ids=segment_ids, 137 | use_one_hot_embeddings=use_one_hot_embeddings) 138 | 139 | (masked_lm_loss, 140 | masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output( 141 | bert_config, model.get_sequence_output(), model.get_embedding_table(), 142 | masked_lm_positions, masked_lm_ids, masked_lm_weights) 143 | 144 | (next_sentence_loss, next_sentence_example_loss, 145 | next_sentence_log_probs) = get_next_sentence_output( 146 | bert_config, model.get_pooled_output(), next_sentence_labels) 147 | 148 | total_loss = masked_lm_loss + next_sentence_loss 149 | 150 | tvars = tf.trainable_variables() 151 | 152 | initialized_variable_names = {} 153 | scaffold_fn = None 154 | if init_checkpoint: 155 | (assignment_map, initialized_variable_names 156 | ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) 157 | if use_tpu: 158 | 159 | def tpu_scaffold(): 160 | tf.train.init_from_checkpoint(init_checkpoint, assignment_map) 161 | return tf.train.Scaffold() 162 | 163 | scaffold_fn = tpu_scaffold 164 | else: 165 | tf.train.init_from_checkpoint(init_checkpoint, assignment_map) 166 | 167 | tf.logging.info("**** Trainable Variables ****") 168 | for var in tvars: 169 | init_string = "" 170 | if var.name in initialized_variable_names: 171 | init_string = ", *INIT_FROM_CKPT*" 172 | tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, 173 | init_string) 174 | 175 | output_spec = None 176 | if mode == tf.estimator.ModeKeys.TRAIN: 177 | train_op = optimization.create_optimizer( 178 | total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) 179 | 180 | output_spec = tf.contrib.tpu.TPUEstimatorSpec( 181 | mode=mode, 182 | loss=total_loss, 183 | train_op=train_op, 184 | scaffold_fn=scaffold_fn) 185 | elif mode == tf.estimator.ModeKeys.EVAL: 186 | 187 | def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, 188 | masked_lm_weights, next_sentence_example_loss, 189 | next_sentence_log_probs, next_sentence_labels): 190 | """Computes the loss and accuracy of the model.""" 191 | masked_lm_log_probs = tf.reshape(masked_lm_log_probs, 192 | [-1, masked_lm_log_probs.shape[-1]]) 193 | masked_lm_predictions = tf.argmax( 194 | masked_lm_log_probs, axis=-1, output_type=tf.int32) 195 | masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1]) 196 | masked_lm_ids = tf.reshape(masked_lm_ids, [-1]) 197 | masked_lm_weights = tf.reshape(masked_lm_weights, [-1]) 198 | masked_lm_accuracy = tf.metrics.accuracy( 199 | labels=masked_lm_ids, 200 | predictions=masked_lm_predictions, 201 | weights=masked_lm_weights) 202 | masked_lm_mean_loss = tf.metrics.mean( 203 | values=masked_lm_example_loss, weights=masked_lm_weights) 204 | 205 | next_sentence_log_probs = tf.reshape( 206 | next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]]) 207 | next_sentence_predictions = tf.argmax( 208 | next_sentence_log_probs, axis=-1, output_type=tf.int32) 209 | next_sentence_labels = tf.reshape(next_sentence_labels, [-1]) 210 | next_sentence_accuracy = tf.metrics.accuracy( 211 | labels=next_sentence_labels, predictions=next_sentence_predictions) 212 | next_sentence_mean_loss = tf.metrics.mean( 213 | values=next_sentence_example_loss) 214 | 215 | return { 216 | "masked_lm_accuracy": masked_lm_accuracy, 217 | "masked_lm_loss": masked_lm_mean_loss, 218 | "next_sentence_accuracy": next_sentence_accuracy, 219 | "next_sentence_loss": next_sentence_mean_loss, 220 | } 221 | 222 | eval_metrics = (metric_fn, [ 223 | masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, 224 | masked_lm_weights, next_sentence_example_loss, 225 | next_sentence_log_probs, next_sentence_labels 226 | ]) 227 | output_spec = tf.contrib.tpu.TPUEstimatorSpec( 228 | mode=mode, 229 | loss=total_loss, 230 | eval_metrics=eval_metrics, 231 | scaffold_fn=scaffold_fn) 232 | else: 233 | raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode)) 234 | 235 | return output_spec 236 | 237 | return model_fn 238 | 239 | 240 | def get_masked_lm_output(bert_config, input_tensor, output_weights, positions, 241 | label_ids, label_weights): 242 | """Get loss and log probs for the masked LM.""" 243 | input_tensor = gather_indexes(input_tensor, positions) 244 | 245 | with tf.variable_scope("cls/predictions"): 246 | # We apply one more non-linear transformation before the output layer. 247 | # This matrix is not used after pre-training. 248 | with tf.variable_scope("transform"): 249 | input_tensor = tf.layers.dense( 250 | input_tensor, 251 | units=bert_config.hidden_size, 252 | activation=modeling.get_activation(bert_config.hidden_act), 253 | kernel_initializer=modeling.create_initializer( 254 | bert_config.initializer_range)) 255 | input_tensor = modeling.layer_norm(input_tensor) 256 | 257 | # The output weights are the same as the input embeddings, but there is 258 | # an output-only bias for each token. 259 | output_bias = tf.get_variable( 260 | "output_bias", 261 | shape=[bert_config.vocab_size], 262 | initializer=tf.zeros_initializer()) 263 | logits = tf.matmul(input_tensor, output_weights, transpose_b=True) 264 | logits = tf.nn.bias_add(logits, output_bias) 265 | log_probs = tf.nn.log_softmax(logits, axis=-1) 266 | 267 | label_ids = tf.reshape(label_ids, [-1]) 268 | label_weights = tf.reshape(label_weights, [-1]) 269 | 270 | one_hot_labels = tf.one_hot( 271 | label_ids, depth=bert_config.vocab_size, dtype=tf.float32) 272 | 273 | # The `positions` tensor might be zero-padded (if the sequence is too 274 | # short to have the maximum number of predictions). The `label_weights` 275 | # tensor has a value of 1.0 for every real prediction and 0.0 for the 276 | # padding predictions. 277 | per_example_loss = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1]) 278 | numerator = tf.reduce_sum(label_weights * per_example_loss) 279 | denominator = tf.reduce_sum(label_weights) + 1e-5 280 | loss = numerator / denominator 281 | 282 | return (loss, per_example_loss, log_probs) 283 | 284 | 285 | def get_next_sentence_output(bert_config, input_tensor, labels): 286 | """Get loss and log probs for the next sentence prediction.""" 287 | 288 | # Simple binary classification. Note that 0 is "next sentence" and 1 is 289 | # "random sentence". This weight matrix is not used after pre-training. 290 | with tf.variable_scope("cls/seq_relationship"): 291 | output_weights = tf.get_variable( 292 | "output_weights", 293 | shape=[2, bert_config.hidden_size], 294 | initializer=modeling.create_initializer(bert_config.initializer_range)) 295 | output_bias = tf.get_variable( 296 | "output_bias", shape=[2], initializer=tf.zeros_initializer()) 297 | 298 | logits = tf.matmul(input_tensor, output_weights, transpose_b=True) 299 | logits = tf.nn.bias_add(logits, output_bias) 300 | log_probs = tf.nn.log_softmax(logits, axis=-1) 301 | labels = tf.reshape(labels, [-1]) 302 | one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32) 303 | per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) 304 | loss = tf.reduce_mean(per_example_loss) 305 | return (loss, per_example_loss, log_probs) 306 | 307 | 308 | def gather_indexes(sequence_tensor, positions): 309 | """Gathers the vectors at the specific positions over a minibatch.""" 310 | sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3) 311 | batch_size = sequence_shape[0] 312 | seq_length = sequence_shape[1] 313 | width = sequence_shape[2] 314 | 315 | flat_offsets = tf.reshape( 316 | tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1]) 317 | flat_positions = tf.reshape(positions + flat_offsets, [-1]) 318 | flat_sequence_tensor = tf.reshape(sequence_tensor, 319 | [batch_size * seq_length, width]) 320 | output_tensor = tf.gather(flat_sequence_tensor, flat_positions) 321 | return output_tensor 322 | 323 | 324 | def input_fn_builder(input_files, 325 | max_seq_length, 326 | max_predictions_per_seq, 327 | is_training, 328 | num_cpu_threads=4): 329 | """Creates an `input_fn` closure to be passed to TPUEstimator.""" 330 | 331 | def input_fn(params): 332 | """The actual input function.""" 333 | batch_size = params["batch_size"] 334 | 335 | name_to_features = { 336 | "input_ids": 337 | tf.FixedLenFeature([max_seq_length], tf.int64), 338 | "input_mask": 339 | tf.FixedLenFeature([max_seq_length], tf.int64), 340 | "segment_ids": 341 | tf.FixedLenFeature([max_seq_length], tf.int64), 342 | "masked_lm_positions": 343 | tf.FixedLenFeature([max_predictions_per_seq], tf.int64), 344 | "masked_lm_ids": 345 | tf.FixedLenFeature([max_predictions_per_seq], tf.int64), 346 | "masked_lm_weights": 347 | tf.FixedLenFeature([max_predictions_per_seq], tf.float32), 348 | "next_sentence_labels": 349 | tf.FixedLenFeature([1], tf.int64), 350 | } 351 | 352 | # For training, we want a lot of parallel reading and shuffling. 353 | # For eval, we want no shuffling and parallel reading doesn't matter. 354 | if is_training: 355 | d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files)) 356 | d = d.repeat() 357 | d = d.shuffle(buffer_size=len(input_files)) 358 | 359 | # `cycle_length` is the number of parallel files that get read. 360 | cycle_length = min(num_cpu_threads, len(input_files)) 361 | 362 | # `sloppy` mode means that the interleaving is not exact. This adds 363 | # even more randomness to the training pipeline. 364 | d = d.apply( 365 | tf.contrib.data.parallel_interleave( 366 | tf.data.TFRecordDataset, 367 | sloppy=is_training, 368 | cycle_length=cycle_length)) 369 | d = d.shuffle(buffer_size=100) 370 | else: 371 | d = tf.data.TFRecordDataset(input_files) 372 | # Since we evaluate for a fixed number of steps we don't want to encounter 373 | # out-of-range exceptions. 374 | d = d.repeat() 375 | 376 | # We must `drop_remainder` on training because the TPU requires fixed 377 | # size dimensions. For eval, we assume we are evaluating on the CPU or GPU 378 | # and we *don't* want to drop the remainder, otherwise we wont cover 379 | # every sample. 380 | d = d.apply( 381 | tf.contrib.data.map_and_batch( 382 | lambda record: _decode_record(record, name_to_features), 383 | batch_size=batch_size, 384 | num_parallel_batches=num_cpu_threads, 385 | drop_remainder=True)) 386 | return d 387 | 388 | return input_fn 389 | 390 | 391 | def _decode_record(record, name_to_features): 392 | """Decodes a record to a TensorFlow example.""" 393 | example = tf.parse_single_example(record, name_to_features) 394 | 395 | # tf.Example only supports tf.int64, but the TPU only supports tf.int32. 396 | # So cast all int64 to int32. 397 | for name in list(example.keys()): 398 | t = example[name] 399 | if t.dtype == tf.int64: 400 | t = tf.to_int32(t) 401 | example[name] = t 402 | 403 | return example 404 | 405 | 406 | def main(_): 407 | tf.logging.set_verbosity(tf.logging.INFO) 408 | 409 | if not FLAGS.do_train and not FLAGS.do_eval: 410 | raise ValueError("At least one of `do_train` or `do_eval` must be True.") 411 | 412 | bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) 413 | 414 | tf.gfile.MakeDirs(FLAGS.output_dir) 415 | 416 | input_files = [] 417 | for input_pattern in FLAGS.input_file.split(","): 418 | input_files.extend(tf.gfile.Glob(input_pattern)) 419 | 420 | tf.logging.info("*** Input Files ***") 421 | for input_file in input_files: 422 | tf.logging.info(" %s" % input_file) 423 | 424 | tpu_cluster_resolver = None 425 | if FLAGS.use_tpu and FLAGS.tpu_name: 426 | tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver( 427 | FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) 428 | 429 | is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 430 | run_config = tf.contrib.tpu.RunConfig( 431 | cluster=tpu_cluster_resolver, 432 | master=FLAGS.master, 433 | model_dir=FLAGS.output_dir, 434 | save_checkpoints_steps=FLAGS.save_checkpoints_steps, 435 | tpu_config=tf.contrib.tpu.TPUConfig( 436 | iterations_per_loop=FLAGS.iterations_per_loop, 437 | num_shards=FLAGS.num_tpu_cores, 438 | per_host_input_for_training=is_per_host)) 439 | 440 | model_fn = model_fn_builder( 441 | bert_config=bert_config, 442 | init_checkpoint=FLAGS.init_checkpoint, 443 | learning_rate=FLAGS.learning_rate, 444 | num_train_steps=FLAGS.num_train_steps, 445 | num_warmup_steps=FLAGS.num_warmup_steps, 446 | use_tpu=FLAGS.use_tpu, 447 | use_one_hot_embeddings=FLAGS.use_tpu) 448 | 449 | # If TPU is not available, this will fall back to normal Estimator on CPU 450 | # or GPU. 451 | estimator = tf.contrib.tpu.TPUEstimator( 452 | use_tpu=FLAGS.use_tpu, 453 | model_fn=model_fn, 454 | config=run_config, 455 | train_batch_size=FLAGS.train_batch_size, 456 | eval_batch_size=FLAGS.eval_batch_size) 457 | 458 | if FLAGS.do_train: 459 | tf.logging.info("***** Running training *****") 460 | tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) 461 | train_input_fn = input_fn_builder( 462 | input_files=input_files, 463 | max_seq_length=FLAGS.max_seq_length, 464 | max_predictions_per_seq=FLAGS.max_predictions_per_seq, 465 | is_training=True) 466 | estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps) 467 | 468 | if FLAGS.do_eval: 469 | tf.logging.info("***** Running evaluation *****") 470 | tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size) 471 | 472 | eval_input_fn = input_fn_builder( 473 | input_files=input_files, 474 | max_seq_length=FLAGS.max_seq_length, 475 | max_predictions_per_seq=FLAGS.max_predictions_per_seq, 476 | is_training=False) 477 | 478 | result = estimator.evaluate( 479 | input_fn=eval_input_fn, steps=FLAGS.max_eval_steps) 480 | 481 | output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") 482 | with tf.gfile.GFile(output_eval_file, "w") as writer: 483 | tf.logging.info("***** Eval results *****") 484 | for key in sorted(result.keys()): 485 | tf.logging.info(" %s = %s", key, str(result[key])) 486 | writer.write("%s = %s\n" % (key, str(result[key]))) 487 | 488 | 489 | if __name__ == "__main__": 490 | flags.mark_flag_as_required("input_file") 491 | flags.mark_flag_as_required("bert_config_file") 492 | flags.mark_flag_as_required("output_dir") 493 | tf.app.run() 494 | -------------------------------------------------------------------------------- /bert/sample_text.txt: -------------------------------------------------------------------------------- 1 | This text is included to make sure Unicode is handled properly: 力加勝北区ᴵᴺᵀᵃছজটডণত 2 | Text should be one-sentence-per-line, with empty lines between documents. 3 | This sample text is public domain and was randomly selected from Project Guttenberg. 4 | 5 | The rain had only ceased with the gray streaks of morning at Blazing Star, and the settlement awoke to a moral sense of cleanliness, and the finding of forgotten knives, tin cups, and smaller camp utensils, where the heavy showers had washed away the debris and dust heaps before the cabin doors. 6 | Indeed, it was recorded in Blazing Star that a fortunate early riser had once picked up on the highway a solid chunk of gold quartz which the rain had freed from its incumbering soil, and washed into immediate and glittering popularity. 7 | Possibly this may have been the reason why early risers in that locality, during the rainy season, adopted a thoughtful habit of body, and seldom lifted their eyes to the rifted or india-ink washed skies above them. 8 | "Cass" Beard had risen early that morning, but not with a view to discovery. 9 | A leak in his cabin roof,--quite consistent with his careless, improvident habits,--had roused him at 4 A. M., with a flooded "bunk" and wet blankets. 10 | The chips from his wood pile refused to kindle a fire to dry his bed-clothes, and he had recourse to a more provident neighbor's to supply the deficiency. 11 | This was nearly opposite. 12 | Mr. Cassius crossed the highway, and stopped suddenly. 13 | Something glittered in the nearest red pool before him. 14 | Gold, surely! 15 | But, wonderful to relate, not an irregular, shapeless fragment of crude ore, fresh from Nature's crucible, but a bit of jeweler's handicraft in the form of a plain gold ring. 16 | Looking at it more attentively, he saw that it bore the inscription, "May to Cass." 17 | Like most of his fellow gold-seekers, Cass was superstitious. 18 | 19 | The fountain of classic wisdom, Hypatia herself. 20 | As the ancient sage--the name is unimportant to a monk--pumped water nightly that he might study by day, so I, the guardian of cloaks and parasols, at the sacred doors of her lecture-room, imbibe celestial knowledge. 21 | From my youth I felt in me a soul above the matter-entangled herd. 22 | She revealed to me the glorious fact, that I am a spark of Divinity itself. 23 | A fallen star, I am, sir!' continued he, pensively, stroking his lean stomach--'a fallen star!--fallen, if the dignity of philosophy will allow of the simile, among the hogs of the lower world--indeed, even into the hog-bucket itself. Well, after all, I will show you the way to the Archbishop's. 24 | There is a philosophic pleasure in opening one's treasures to the modest young. 25 | Perhaps you will assist me by carrying this basket of fruit?' And the little man jumped up, put his basket on Philammon's head, and trotted off up a neighbouring street. 26 | Philammon followed, half contemptuous, half wondering at what this philosophy might be, which could feed the self-conceit of anything so abject as his ragged little apish guide; 27 | but the novel roar and whirl of the street, the perpetual stream of busy faces, the line of curricles, palanquins, laden asses, camels, elephants, which met and passed him, and squeezed him up steps and into doorways, as they threaded their way through the great Moon-gate into the ample street beyond, drove everything from his mind but wondering curiosity, and a vague, helpless dread of that great living wilderness, more terrible than any dead wilderness of sand which he had left behind. 28 | Already he longed for the repose, the silence of the Laura--for faces which knew him and smiled upon him; but it was too late to turn back now. 29 | His guide held on for more than a mile up the great main street, crossed in the centre of the city, at right angles, by one equally magnificent, at each end of which, miles away, appeared, dim and distant over the heads of the living stream of passengers, the yellow sand-hills of the desert; 30 | while at the end of the vista in front of them gleamed the blue harbour, through a network of countless masts. 31 | At last they reached the quay at the opposite end of the street; 32 | and there burst on Philammon's astonished eyes a vast semicircle of blue sea, ringed with palaces and towers. 33 | He stopped involuntarily; and his little guide stopped also, and looked askance at the young monk, to watch the effect which that grand panorama should produce on him. 34 | -------------------------------------------------------------------------------- /bert/tokenization.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | """Tokenization classes.""" 16 | 17 | from __future__ import absolute_import 18 | from __future__ import division 19 | from __future__ import print_function 20 | 21 | import collections 22 | import re 23 | import unicodedata 24 | import six 25 | import tensorflow as tf 26 | 27 | 28 | def validate_case_matches_checkpoint(do_lower_case, init_checkpoint): 29 | """Checks whether the casing config is consistent with the checkpoint name.""" 30 | 31 | # The casing has to be passed in by the user and there is no explicit check 32 | # as to whether it matches the checkpoint. The casing information probably 33 | # should have been stored in the bert_config.json file, but it's not, so 34 | # we have to heuristically detect it to validate. 35 | 36 | if not init_checkpoint: 37 | return 38 | 39 | m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint) 40 | if m is None: 41 | return 42 | 43 | model_name = m.group(1) 44 | 45 | lower_models = [ 46 | "uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12", 47 | "multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12" 48 | ] 49 | 50 | cased_models = [ 51 | "cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16", 52 | "multi_cased_L-12_H-768_A-12" 53 | ] 54 | 55 | is_bad_config = False 56 | if model_name in lower_models and not do_lower_case: 57 | is_bad_config = True 58 | actual_flag = "False" 59 | case_name = "lowercased" 60 | opposite_flag = "True" 61 | 62 | if model_name in cased_models and do_lower_case: 63 | is_bad_config = True 64 | actual_flag = "True" 65 | case_name = "cased" 66 | opposite_flag = "False" 67 | 68 | if is_bad_config: 69 | raise ValueError( 70 | "You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. " 71 | "However, `%s` seems to be a %s model, so you " 72 | "should pass in `--do_lower_case=%s` so that the fine-tuning matches " 73 | "how the model was pre-training. If this error is wrong, please " 74 | "just comment out this check." % (actual_flag, init_checkpoint, 75 | model_name, case_name, opposite_flag)) 76 | 77 | 78 | def convert_to_unicode(text): 79 | """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" 80 | if six.PY3: 81 | if isinstance(text, str): 82 | return text 83 | elif isinstance(text, bytes): 84 | return text.decode("utf-8", "ignore") 85 | else: 86 | raise ValueError("Unsupported string type: %s" % (type(text))) 87 | elif six.PY2: 88 | if isinstance(text, str): 89 | return text.decode("utf-8", "ignore") 90 | elif isinstance(text, unicode): 91 | return text 92 | else: 93 | raise ValueError("Unsupported string type: %s" % (type(text))) 94 | else: 95 | raise ValueError("Not running on Python2 or Python 3?") 96 | 97 | 98 | def printable_text(text): 99 | """Returns text encoded in a way suitable for print or `tf.logging`.""" 100 | 101 | # These functions want `str` for both Python2 and Python3, but in one case 102 | # it's a Unicode string and in the other it's a byte string. 103 | if six.PY3: 104 | if isinstance(text, str): 105 | return text 106 | elif isinstance(text, bytes): 107 | return text.decode("utf-8", "ignore") 108 | else: 109 | raise ValueError("Unsupported string type: %s" % (type(text))) 110 | elif six.PY2: 111 | if isinstance(text, str): 112 | return text 113 | elif isinstance(text, unicode): 114 | return text.encode("utf-8") 115 | else: 116 | raise ValueError("Unsupported string type: %s" % (type(text))) 117 | else: 118 | raise ValueError("Not running on Python2 or Python 3?") 119 | 120 | 121 | def load_vocab(vocab_file): 122 | """Loads a vocabulary file into a dictionary.""" 123 | vocab = collections.OrderedDict() 124 | index = 0 125 | with tf.gfile.GFile(vocab_file, "r") as reader: 126 | while True: 127 | token = convert_to_unicode(reader.readline()) 128 | if not token: 129 | break 130 | token = token.strip() 131 | vocab[token] = index 132 | index += 1 133 | return vocab 134 | 135 | 136 | def convert_by_vocab(vocab, items): 137 | """Converts a sequence of [tokens|ids] using the vocab.""" 138 | output = [] 139 | for item in items: 140 | output.append(vocab[item]) 141 | return output 142 | 143 | 144 | def convert_tokens_to_ids(vocab, tokens): 145 | return convert_by_vocab(vocab, tokens) 146 | 147 | 148 | def convert_ids_to_tokens(inv_vocab, ids): 149 | return convert_by_vocab(inv_vocab, ids) 150 | 151 | 152 | def whitespace_tokenize(text): 153 | """Runs basic whitespace cleaning and splitting on a piece of text.""" 154 | text = text.strip() 155 | if not text: 156 | return [] 157 | tokens = text.split() 158 | return tokens 159 | 160 | 161 | class FullTokenizer(object): 162 | """Runs end-to-end tokenziation.""" 163 | 164 | def __init__(self, vocab_file, do_lower_case=True): 165 | self.vocab = load_vocab(vocab_file) 166 | self.inv_vocab = {v: k for k, v in self.vocab.items()} 167 | self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) 168 | self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) 169 | 170 | def tokenize(self, text): 171 | split_tokens = [] 172 | for token in self.basic_tokenizer.tokenize(text): 173 | for sub_token in self.wordpiece_tokenizer.tokenize(token): 174 | split_tokens.append(sub_token) 175 | 176 | return split_tokens 177 | 178 | def convert_tokens_to_ids(self, tokens): 179 | return convert_by_vocab(self.vocab, tokens) 180 | 181 | def convert_ids_to_tokens(self, ids): 182 | return convert_by_vocab(self.inv_vocab, ids) 183 | 184 | 185 | class BasicTokenizer(object): 186 | """Runs basic tokenization (punctuation splitting, lower casing, etc.).""" 187 | 188 | def __init__(self, do_lower_case=True): 189 | """Constructs a BasicTokenizer. 190 | 191 | Args: 192 | do_lower_case: Whether to lower case the input. 193 | """ 194 | self.do_lower_case = do_lower_case 195 | 196 | def tokenize(self, text): 197 | """Tokenizes a piece of text.""" 198 | text = convert_to_unicode(text) 199 | text = self._clean_text(text) 200 | 201 | # This was added on November 1st, 2018 for the multilingual and Chinese 202 | # models. This is also applied to the English models now, but it doesn't 203 | # matter since the English models were not trained on any Chinese data 204 | # and generally don't have any Chinese data in them (there are Chinese 205 | # characters in the vocabulary because Wikipedia does have some Chinese 206 | # words in the English Wikipedia.). 207 | text = self._tokenize_chinese_chars(text) 208 | 209 | orig_tokens = whitespace_tokenize(text) 210 | split_tokens = [] 211 | for token in orig_tokens: 212 | if self.do_lower_case: 213 | token = token.lower() 214 | token = self._run_strip_accents(token) 215 | split_tokens.extend(self._run_split_on_punc(token)) 216 | 217 | output_tokens = whitespace_tokenize(" ".join(split_tokens)) 218 | return output_tokens 219 | 220 | def _run_strip_accents(self, text): 221 | """Strips accents from a piece of text.""" 222 | text = unicodedata.normalize("NFD", text) 223 | output = [] 224 | for char in text: 225 | cat = unicodedata.category(char) 226 | if cat == "Mn": 227 | continue 228 | output.append(char) 229 | return "".join(output) 230 | 231 | def _run_split_on_punc(self, text): 232 | """Splits punctuation on a piece of text.""" 233 | chars = list(text) 234 | i = 0 235 | start_new_word = True 236 | output = [] 237 | while i < len(chars): 238 | char = chars[i] 239 | if _is_punctuation(char): 240 | output.append([char]) 241 | start_new_word = True 242 | else: 243 | if start_new_word: 244 | output.append([]) 245 | start_new_word = False 246 | output[-1].append(char) 247 | i += 1 248 | 249 | return ["".join(x) for x in output] 250 | 251 | def _tokenize_chinese_chars(self, text): 252 | """Adds whitespace around any CJK character.""" 253 | output = [] 254 | for char in text: 255 | cp = ord(char) 256 | if self._is_chinese_char(cp): 257 | output.append(" ") 258 | output.append(char) 259 | output.append(" ") 260 | else: 261 | output.append(char) 262 | return "".join(output) 263 | 264 | def _is_chinese_char(self, cp): 265 | """Checks whether CP is the codepoint of a CJK character.""" 266 | # This defines a "chinese character" as anything in the CJK Unicode block: 267 | # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) 268 | # 269 | # Note that the CJK Unicode block is NOT all Japanese and Korean characters, 270 | # despite its name. The modern Korean Hangul alphabet is a different block, 271 | # as is Japanese Hiragana and Katakana. Those alphabets are used to write 272 | # space-separated words, so they are not treated specially and handled 273 | # like the all of the other languages. 274 | if ((cp >= 0x4E00 and cp <= 0x9FFF) or # 275 | (cp >= 0x3400 and cp <= 0x4DBF) or # 276 | (cp >= 0x20000 and cp <= 0x2A6DF) or # 277 | (cp >= 0x2A700 and cp <= 0x2B73F) or # 278 | (cp >= 0x2B740 and cp <= 0x2B81F) or # 279 | (cp >= 0x2B820 and cp <= 0x2CEAF) or 280 | (cp >= 0xF900 and cp <= 0xFAFF) or # 281 | (cp >= 0x2F800 and cp <= 0x2FA1F)): # 282 | return True 283 | 284 | return False 285 | 286 | def _clean_text(self, text): 287 | """Performs invalid character removal and whitespace cleanup on text.""" 288 | output = [] 289 | for char in text: 290 | cp = ord(char) 291 | if cp == 0 or cp == 0xfffd or _is_control(char): 292 | continue 293 | if _is_whitespace(char): 294 | output.append(" ") 295 | else: 296 | output.append(char) 297 | return "".join(output) 298 | 299 | 300 | class WordpieceTokenizer(object): 301 | """Runs WordPiece tokenziation.""" 302 | 303 | def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200): 304 | self.vocab = vocab 305 | self.unk_token = unk_token 306 | self.max_input_chars_per_word = max_input_chars_per_word 307 | 308 | def tokenize(self, text): 309 | """Tokenizes a piece of text into its word pieces. 310 | 311 | This uses a greedy longest-match-first algorithm to perform tokenization 312 | using the given vocabulary. 313 | 314 | For example: 315 | input = "unaffable" 316 | output = ["un", "##aff", "##able"] 317 | 318 | Args: 319 | text: A single token or whitespace separated tokens. This should have 320 | already been passed through `BasicTokenizer. 321 | 322 | Returns: 323 | A list of wordpiece tokens. 324 | """ 325 | 326 | text = convert_to_unicode(text) 327 | 328 | output_tokens = [] 329 | for token in whitespace_tokenize(text): 330 | chars = list(token) 331 | if len(chars) > self.max_input_chars_per_word: 332 | output_tokens.append(self.unk_token) 333 | continue 334 | 335 | is_bad = False 336 | start = 0 337 | sub_tokens = [] 338 | while start < len(chars): 339 | end = len(chars) 340 | cur_substr = None 341 | while start < end: 342 | substr = "".join(chars[start:end]) 343 | if start > 0: 344 | substr = "##" + substr 345 | if substr in self.vocab: 346 | cur_substr = substr 347 | break 348 | end -= 1 349 | if cur_substr is None: 350 | is_bad = True 351 | break 352 | sub_tokens.append(cur_substr) 353 | start = end 354 | 355 | if is_bad: 356 | output_tokens.append(self.unk_token) 357 | else: 358 | output_tokens.extend(sub_tokens) 359 | return output_tokens 360 | 361 | 362 | def _is_whitespace(char): 363 | """Checks whether `chars` is a whitespace character.""" 364 | # \t, \n, and \r are technically contorl characters but we treat them 365 | # as whitespace since they are generally considered as such. 366 | if char == " " or char == "\t" or char == "\n" or char == "\r": 367 | return True 368 | cat = unicodedata.category(char) 369 | if cat == "Zs": 370 | return True 371 | return False 372 | 373 | 374 | def _is_control(char): 375 | """Checks whether `chars` is a control character.""" 376 | # These are technically control characters but we count them as whitespace 377 | # characters. 378 | if char == "\t" or char == "\n" or char == "\r": 379 | return False 380 | cat = unicodedata.category(char) 381 | if cat in ("Cc", "Cf"): 382 | return True 383 | return False 384 | 385 | 386 | def _is_punctuation(char): 387 | """Checks whether `chars` is a punctuation character.""" 388 | cp = ord(char) 389 | # We treat all non-letter/number ASCII as punctuation. 390 | # Characters such as "^", "$", and "`" are not in the Unicode 391 | # Punctuation class but we treat them as punctuation anyways, for 392 | # consistency. 393 | if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or 394 | (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): 395 | return True 396 | cat = unicodedata.category(char) 397 | if cat.startswith("P"): 398 | return True 399 | return False 400 | -------------------------------------------------------------------------------- /bert/tokenization_test.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | # Copyright 2018 The Google AI Language Team Authors. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | from __future__ import absolute_import 16 | from __future__ import division 17 | from __future__ import print_function 18 | 19 | import os 20 | import tempfile 21 | import tokenization 22 | import six 23 | import tensorflow as tf 24 | 25 | 26 | class TokenizationTest(tf.test.TestCase): 27 | 28 | def test_full_tokenizer(self): 29 | vocab_tokens = [ 30 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 31 | "##ing", "," 32 | ] 33 | with tempfile.NamedTemporaryFile(delete=False) as vocab_writer: 34 | if six.PY2: 35 | vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) 36 | else: 37 | vocab_writer.write("".join( 38 | [x + "\n" for x in vocab_tokens]).encode("utf-8")) 39 | 40 | vocab_file = vocab_writer.name 41 | 42 | tokenizer = tokenization.FullTokenizer(vocab_file) 43 | os.unlink(vocab_file) 44 | 45 | tokens = tokenizer.tokenize(u"UNwant\u00E9d,running") 46 | self.assertAllEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) 47 | 48 | self.assertAllEqual( 49 | tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9]) 50 | 51 | def test_chinese(self): 52 | tokenizer = tokenization.BasicTokenizer() 53 | 54 | self.assertAllEqual( 55 | tokenizer.tokenize(u"ah\u535A\u63A8zz"), 56 | [u"ah", u"\u535A", u"\u63A8", u"zz"]) 57 | 58 | def test_basic_tokenizer_lower(self): 59 | tokenizer = tokenization.BasicTokenizer(do_lower_case=True) 60 | 61 | self.assertAllEqual( 62 | tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "), 63 | ["hello", "!", "how", "are", "you", "?"]) 64 | self.assertAllEqual(tokenizer.tokenize(u"H\u00E9llo"), ["hello"]) 65 | 66 | def test_basic_tokenizer_no_lower(self): 67 | tokenizer = tokenization.BasicTokenizer(do_lower_case=False) 68 | 69 | self.assertAllEqual( 70 | tokenizer.tokenize(u" \tHeLLo!how \n Are yoU? "), 71 | ["HeLLo", "!", "how", "Are", "yoU", "?"]) 72 | 73 | def test_wordpiece_tokenizer(self): 74 | vocab_tokens = [ 75 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 76 | "##ing" 77 | ] 78 | 79 | vocab = {} 80 | for (i, token) in enumerate(vocab_tokens): 81 | vocab[token] = i 82 | tokenizer = tokenization.WordpieceTokenizer(vocab=vocab) 83 | 84 | self.assertAllEqual(tokenizer.tokenize(""), []) 85 | 86 | self.assertAllEqual( 87 | tokenizer.tokenize("unwanted running"), 88 | ["un", "##want", "##ed", "runn", "##ing"]) 89 | 90 | self.assertAllEqual( 91 | tokenizer.tokenize("unwantedX running"), ["[UNK]", "runn", "##ing"]) 92 | 93 | def test_convert_tokens_to_ids(self): 94 | vocab_tokens = [ 95 | "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", 96 | "##ing" 97 | ] 98 | 99 | vocab = {} 100 | for (i, token) in enumerate(vocab_tokens): 101 | vocab[token] = i 102 | 103 | self.assertAllEqual( 104 | tokenization.convert_tokens_to_ids( 105 | vocab, ["un", "##want", "##ed", "runn", "##ing"]), [7, 4, 5, 8, 9]) 106 | 107 | def test_is_whitespace(self): 108 | self.assertTrue(tokenization._is_whitespace(u" ")) 109 | self.assertTrue(tokenization._is_whitespace(u"\t")) 110 | self.assertTrue(tokenization._is_whitespace(u"\r")) 111 | self.assertTrue(tokenization._is_whitespace(u"\n")) 112 | self.assertTrue(tokenization._is_whitespace(u"\u00A0")) 113 | 114 | self.assertFalse(tokenization._is_whitespace(u"A")) 115 | self.assertFalse(tokenization._is_whitespace(u"-")) 116 | 117 | def test_is_control(self): 118 | self.assertTrue(tokenization._is_control(u"\u0005")) 119 | 120 | self.assertFalse(tokenization._is_control(u"A")) 121 | self.assertFalse(tokenization._is_control(u" ")) 122 | self.assertFalse(tokenization._is_control(u"\t")) 123 | self.assertFalse(tokenization._is_control(u"\r")) 124 | self.assertFalse(tokenization._is_control(u"\U0001F4A9")) 125 | 126 | def test_is_punctuation(self): 127 | self.assertTrue(tokenization._is_punctuation(u"-")) 128 | self.assertTrue(tokenization._is_punctuation(u"$")) 129 | self.assertTrue(tokenization._is_punctuation(u"`")) 130 | self.assertTrue(tokenization._is_punctuation(u".")) 131 | 132 | self.assertFalse(tokenization._is_punctuation(u"A")) 133 | self.assertFalse(tokenization._is_punctuation(u" ")) 134 | 135 | 136 | if __name__ == "__main__": 137 | tf.test.main() 138 | -------------------------------------------------------------------------------- /checkrules.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import numpy as np 3 | 4 | def parse_condition(rule): 5 | ret = [] 6 | for r in rule.split("^"): 7 | d = r.split(':') 8 | ret.append((int(d[0]), int(d[1]))) 9 | return ret 10 | 11 | class CheckRules(): 12 | def __init__(self, filename): 13 | self.rule_list = [] 14 | if filename is None: 15 | return 16 | with open(filename) as fin: 17 | for rule in fin: 18 | rule = rule.strip().replace(" ", "").split('#') 19 | left, right, p = rule 20 | left = parse_condition(left) 21 | right = parse_condition(right) 22 | self.rule_list.append((left, right, float(p))) 23 | 24 | def __satisfied(self, status, rule): 25 | for r in rule: 26 | if status[r[0]] != r[1]: 27 | return False 28 | return True 29 | 30 | def fix(self, status): 31 | ret = [] 32 | for rule in self.rule_list: 33 | left, right, p = rule 34 | if (not self.__satisfied(status, left)): 35 | continue 36 | new_status = copy.deepcopy(status) 37 | for r in right: 38 | new_status[r[0]] = r[1] 39 | ret.append((new_status, p)) 40 | return ret 41 | 42 | def judge(self, status): 43 | total_p = 1 44 | for rule in self.rule_list: 45 | left, right, p = rule 46 | if self.__satisfied(status, left): 47 | if self.__satisfied(status, right): 48 | total_p *= p 49 | else: 50 | total_p *= (1 - p) 51 | if total_p < 1e-6: 52 | return total_p 53 | return total_p 54 | 55 | if __name__ == "__main__": 56 | check = CheckRules("rule_file.txt") 57 | status = np.array([1,1,1,0,0,1,1,0,0]) 58 | print(check.judge(status)) 59 | -------------------------------------------------------------------------------- /data/data_utils.py: -------------------------------------------------------------------------------- 1 | import csv 2 | from sklearn.utils import shuffle 3 | import json 4 | 5 | def read_data_from_csv(csv_file): 6 | with open(csv_file, 'r', encoding="utf-8") as f: 7 | data = [] 8 | labels = [] 9 | filenames = [] 10 | ahs = [] 11 | attrs = [] 12 | 13 | # Read csv and prepare data 14 | reader = csv.reader(f) 15 | next(reader, None) 16 | for row in reader: 17 | [filename, ah, money, damage, attitude, surrender, again, young, forgive, tool, room, theft, year_num, probation, money_num] = row 18 | #print(row) 19 | if float(money) < 0.1: 20 | continue 21 | if int(year_num) == 0: 22 | continue 23 | if float(money) >= 30000: 24 | continue 25 | money = process_money(float(money), 1000) 26 | 27 | data.append([money]) 28 | attrs.append([int(damage), int(attitude), int(surrender), int(again), int(young), int(forgive), int(tool), int(room), int(theft)]) 29 | labels.append(int(year_num)) 30 | filenames.append(filename) 31 | ahs.append(ah) 32 | 33 | # Shuffle 34 | filenames, ahs, data, labels, attrs = shuffle(filenames, ahs, data, labels, attrs, random_state=5) 35 | return filenames, ahs, data, labels, attrs 36 | 37 | def read_csv_rawdata(csv_file): 38 | data_list = [] 39 | with open(csv_file, "r", encoding="utf-8") as fin: 40 | reader = csv.reader(fin) 41 | next(reader, None) 42 | for row in reader: 43 | data_list.append(row) 44 | return data_list 45 | 46 | def read_csv_header(csv_file): 47 | data_list = [] 48 | with open(csv_file, "r", encoding="utf-8") as fin: 49 | reader = csv.reader(fin) 50 | header = list(reader)[0] 51 | return header 52 | 53 | def write_csv(data_list, header, proportions): 54 | shuffle(data_list) 55 | datafile_list = [] 56 | begin = 0 57 | for idx, probation in enumerate(proportions): 58 | num = int(probation * len(data_list)) 59 | end = min(begin + num, len(data_list)) 60 | csv_filename = "%d_%.2f.csv" % (idx, probation) 61 | datafile_list.append(csv_filename) 62 | with open(csv_filename, "w", encoding="utf-8") as fout: 63 | writer = csv.writer(fout) 64 | writer.writerow(header) 65 | for row in data_list[begin:end]: 66 | writer.writerow(row) 67 | return datafile_list 68 | 69 | 70 | def save_json(JsonPath, data): 71 | with open(JsonPath, "w", encoding="utf-8") as f: 72 | for line in data: 73 | f.write(json.dumps(line, ensure_ascii=False) + '\n') 74 | 75 | def load_json(file_path): 76 | ret = [] 77 | with open(file_path, "r", encoding = "utf-8") as fin: 78 | for data in fin: 79 | ret.append(json.loads(data.strip())) 80 | return ret 81 | 82 | if __name__ == "__main__": 83 | print("Read 40.csv and 50.csv") 84 | data_list = read_csv_rawdata("40.csv") + read_csv_rawdata("50.csv") 85 | header = read_csv_header("40.csv") 86 | attr_datafile_list = write_csv(data_list, header, [0.1, 0.9]) 87 | print("Generated files : ", attr_datafile_list) 88 | 89 | all_json_data = load_json("label_data_safe.json") 90 | csv_list = ["10.csv", "40.csv" , "50.csv"] 91 | csv_list = attr_datafile_list 92 | 93 | for csv_file in csv_list: 94 | filenames, ahs, _, _, _ = read_data_from_csv(csv_file) 95 | json_file = ".".join(csv_file.split(".")[:-1]) + ".json" 96 | save_data_list = [] 97 | for json_data in all_json_data: 98 | if json_data[0]["ah"] in ahs: 99 | filename = filenames[ahs.index(json_data[0]["ah"])] 100 | json_data[0]["file"] = filename 101 | save_data_list.append(json_data) 102 | #print(filename) 103 | save_json(json_file, save_data_list) 104 | print("save_json", json_file) 105 | 106 | -------------------------------------------------------------------------------- /data/dataset.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbductiveLearning/SS-ABL/57429b68edc5cc5ad4ccfe9b0616dbc2c53c2820/data/dataset.zip -------------------------------------------------------------------------------- /data_utils.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | import csv 4 | from sklearn.utils import shuffle 5 | import json 6 | 7 | def process_money(money, seg): 8 | if money >= seg: 9 | m = (money+seg/2)//seg*seg 10 | elif money <= 499: 11 | m = 499 12 | elif money <= 999: 13 | m = 999 14 | else: 15 | m = money 16 | return m 17 | 18 | def read_csv(csv_file): 19 | with open(csv_file, 'r', encoding="utf-8") as f: 20 | data = [] 21 | labels = [] 22 | filenames = [] 23 | ahs = [] 24 | attrs = [] 25 | 26 | reader = csv.reader(f) 27 | next(reader, None) 28 | for row in reader: 29 | [filename, ah, money, damage, attitude, surrender, again, young, forgive, tool, room, theft, year_num, probation, money_num] = row 30 | if float(money) < 0.1: 31 | continue 32 | if int(year_num) == 0: 33 | continue 34 | if float(money) >= 30000: 35 | continue 36 | money = process_money(float(money), 1000) 37 | data.append([money]) 38 | attrs.append([int(damage), int(attitude), int(surrender), int(again), int(young), int(forgive), int(tool), int(room), int(theft)]) 39 | labels.append(int(year_num)) 40 | filenames.append(filename) 41 | ahs.append(ah) 42 | 43 | filenames, ahs, data, labels, attrs = shuffle(filenames, ahs, data, labels, attrs, random_state=5) 44 | return filenames, ahs, data, labels, attrs 45 | 46 | def getJson(JsonPath, ah): 47 | fin = open(JsonPath, 'r', encoding='utf-8') 48 | for line in fin.readlines(): 49 | judgement = json.loads(line) 50 | if ah == judgement[0]["ah"]: 51 | return judgement 52 | print("Not find judgement in json file according to ah") 53 | return None 54 | 55 | def save_json(JsonPath, data): 56 | with open(JsonPath, "w", encoding="utf-8") as f: 57 | for line in data: 58 | f.write(json.dumps(line, ensure_ascii=False) + '\n') 59 | 60 | def load_json(file_path): 61 | ret = [] 62 | with open(file_path, "r", encoding = "utf-8") as fin: 63 | for data in fin: 64 | ret.append(json.loads(data.strip())) 65 | return ret 66 | -------------------------------------------------------------------------------- /judger.py: -------------------------------------------------------------------------------- 1 | import json 2 | class Judger: 3 | # Initialize Judger, with the path of tag list 4 | def __init__(self, tag_path): 5 | self.tag_dic = {} 6 | f = open(tag_path, "r", encoding='utf-8') 7 | self.task_cnt = 0 8 | for line in f: 9 | # print(line) 10 | self.task_cnt += 1 11 | self.tag_dic[line[:-1]] = self.task_cnt 12 | # print(self.tag_dic) 13 | 14 | # Format the result generated by the Predictor class 15 | @staticmethod 16 | def format_result(result): 17 | rex = {"tags": []} 18 | res_art = [] 19 | for x in result["tags"]: 20 | if not (x is None): 21 | res_art.append(int(x)) 22 | rex["tags"] = res_art 23 | 24 | return rex 25 | 26 | # Gen new results according to the truth and users output 27 | def gen_new_result(self, result, truth, label): 28 | s1 = set() 29 | for tag in label: 30 | s1.add(self.tag_dic.setdefault(tag.replace(' ', ''), None)) 31 | s2 = set() 32 | for name in truth: 33 | s2.add(self.tag_dic.setdefault(name.replace(' ', ''), None)) 34 | 35 | for a in range(0, self.task_cnt): 36 | in1 = (a + 1) in s1 37 | in2 = (a + 1) in s2 38 | if in1: 39 | if in2: 40 | result[0][a]["TP"] += 1 41 | else: 42 | result[0][a]["FP"] += 1 43 | else: 44 | if in2: 45 | result[0][a]["FN"] += 1 46 | else: 47 | result[0][a]["TN"] += 1 48 | 49 | return result 50 | 51 | # Calculate precision, recall and f1 value 52 | # According to https://github.com/dice-group/gerbil/wiki/Precision,-Recall-and-F1-measure 53 | @staticmethod 54 | def get_value(res): 55 | if res["TP"] == 0: 56 | if res["FP"] == 0 and res["FN"] == 0: 57 | precision = 1.0 58 | recall = 1.0 59 | f1 = 1.0 60 | else: 61 | precision = 0.0 62 | recall = 0.0 63 | f1 = 0.0 64 | else: 65 | precision = 1.0 * res["TP"] / (res["TP"] + res["FP"]) 66 | recall = 1.0 * res["TP"] / (res["TP"] + res["FN"]) 67 | f1 = 2 * precision * recall / (precision + recall) 68 | 69 | return precision, recall, f1 70 | 71 | # Generate score 72 | def gen_score(self, arr): 73 | sumf = 0 74 | y = {"TP": 0, "FP": 0, "FN": 0, "TN": 0} 75 | for x in arr[0]: 76 | p, r, f = self.get_value(x) 77 | sumf += f 78 | for z in x.keys(): 79 | y[z] += x[z] 80 | 81 | _, __, f_ = self.get_value(y) 82 | macro_f = sumf * 1.0 / len(arr[0]) 83 | micro_f = f_ 84 | 85 | return {"macro" : macro_f, "micro" : micro_f} 86 | 87 | # Test with ground truth path and the user's output path 88 | def test(self, truth_path, output_path): 89 | cnt = 0 90 | result = [[]] 91 | for a in range(0, self.task_cnt): 92 | result[0].append({"TP": 0, "FP": 0, "TN": 0, "FN": 0}) 93 | 94 | # with open(truth_path, "r", encoding='utf-8') as inf, open(output_path, "r", encoding='utf-8') as ouf: 95 | ground_doc_dict = {} 96 | with open(truth_path, "r", encoding='utf-8') as inf: 97 | for line in inf: 98 | ground_doc = json.loads(line) 99 | ah = ground_doc[0]['ah'] 100 | ground_doc_dict[ah] = ground_doc 101 | 102 | with open(output_path, "r", encoding='utf-8') as inf: 103 | for line in inf: 104 | user_doc = json.loads(line) 105 | ah = user_doc[0]['ah'] 106 | if ah in ground_doc_dict: 107 | ground_doc = ground_doc_dict[ah] 108 | else: 109 | print("WARNING: ah", ah, "is not in ground truth file") 110 | continue 111 | for ind in range(len(ground_doc)): 112 | ground_truth = ground_doc[ind]['label'] 113 | try: 114 | user_output = user_doc[ind]['label'] 115 | except: 116 | print(user_doc[ind]) 117 | cnt += 1 118 | result = self.gen_new_result(result, ground_truth, user_output) 119 | 120 | return result 121 | 122 | # Generatue final_score 123 | def get_score(truth_path_labor, output_path_labor, tag_path_labor): 124 | def ret_operate_helper(info, ret, tag, score): 125 | if tag == "total": 126 | for flag in ["macro", "micro"]: 127 | name = "%s_%s_f1" % (tag, flag) 128 | info += "%14s : %10f\n" % (name, score[flag]) 129 | ret.append((name, score[flag])) 130 | else: 131 | flag = "macro" 132 | name = "%s_f1" % (tag) 133 | info += "%14s : %10f\n" % (name, score[flag]) 134 | ret.append((name, score[flag])) 135 | return info, ret 136 | 137 | judger_labor = Judger(tag_path=tag_path_labor) 138 | reslt_labor = judger_labor.test(truth_path=truth_path_labor, 139 | output_path=output_path_labor) 140 | tag_dic = list(judger_labor.tag_dic) 141 | ret = [] 142 | ret_str = "" 143 | for idx, d in enumerate(reslt_labor[0]): 144 | f1 = judger_labor.gen_score([[d]]) 145 | ret_str, ret = ret_operate_helper(ret_str, ret, tag_dic[idx], f1) 146 | 147 | total_f1 = judger_labor.gen_score(reslt_labor) 148 | ret_str, ret = ret_operate_helper(ret_str, ret, "total", total_f1) 149 | 150 | return ret, ret_str[:-1] 151 | 152 | if __name__ == '__main__': 153 | final_score = get_score(truth_path_labor='test_data/10_new.json', 154 | output_path_labor='test_data/abl_predict_0.json', 155 | tag_path_labor='test_data/tags_for_test.txt') 156 | print(final_score) 157 | print(final_score[1]) 158 | -------------------------------------------------------------------------------- /pk_files/this is the result's pickle files folder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbductiveLearning/SS-ABL/57429b68edc5cc5ad4ccfe9b0616dbc2c53c2820/pk_files/this is the result's pickle files folder -------------------------------------------------------------------------------- /result/this is the result folder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbductiveLearning/SS-ABL/57429b68edc5cc5ad4ccfe9b0616dbc2c53c2820/result/this is the result folder -------------------------------------------------------------------------------- /result_utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import pickle as pk 3 | 4 | log_name = "log.txt" 5 | logging.basicConfig(level=logging.INFO, 6 | filename=log_name, 7 | filemode='a', 8 | format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') 9 | 10 | class ResultRecorder: 11 | def __init__(self): 12 | self.result = {} 13 | logging.info("=========================================================") 14 | logging.info("====================== Begin ===========================") 15 | logging.info("=========================================================\n") 16 | pass 17 | 18 | def print(self, *argv): 19 | info = "" 20 | for data in argv: 21 | info += str(data) 22 | print(info) 23 | logging.info(info) 24 | 25 | def print_result(self, *argv): 26 | info = "" 27 | for data in argv: 28 | info += "#Result{%s}" % str(data) 29 | print(info) 30 | logging.info(info) 31 | 32 | def store(self, *argv): 33 | for data in argv: 34 | if data.find(":") < 0: 35 | continue 36 | label, data = data.split(":") 37 | self.store_pair(label, data) 38 | 39 | def write_result(self, *argv): 40 | self.print_result(*argv) 41 | self.store(*argv) 42 | 43 | def store_pair(self, label, data): 44 | if label not in self.result: 45 | self.result[label] = [] 46 | self.result[label].append(data) 47 | 48 | def write_pair(self, label, data): 49 | self.print_result(label + ":" + str(data)) 50 | self.store_pair(label, data) 51 | 52 | def dump(self, f): 53 | pk.dump(self.result, f) 54 | 55 | -------------------------------------------------------------------------------- /rule_file.txt: -------------------------------------------------------------------------------- 1 | 7 : 1 # 8 : 0 # 1 2 | 5 : 1 # 0 : 1 # 1 3 | 2 : 1 # 1 : 1 # 1 4 | 3 : 1 # 4 : 0 # 0.988920 -------------------------------------------------------------------------------- /sentence_model.py: -------------------------------------------------------------------------------- 1 | from sklearn import linear_model 2 | import numpy as np 3 | import json 4 | from itertools import combinations 5 | 6 | is_debug = False 7 | 8 | def debug_print(*args): 9 | if is_debug: 10 | print(*args) 11 | 12 | class SentenceModel: 13 | def __init__(self): 14 | self.LARGE = 1000 15 | self.HUGE = 30000 16 | self.EXTRA_HUGE = 300000 17 | 18 | self.baseline_model = linear_model.LinearRegression() 19 | self.rate_model = linear_model.LinearRegression(fit_intercept=False) 20 | 21 | def fit_baseline(self, moneys, months): 22 | self.baseline_model.fit(moneys, months) 23 | 24 | def predict_baseline(self, moneys): 25 | return self.baseline_model.predict(moneys) 26 | 27 | def fit_rate(self, moneys, attrs, months): 28 | rates = [] 29 | for money, month in zip(moneys, months): 30 | baseline = self.predict_baseline([money]) 31 | rates.append((month - baseline) / baseline) 32 | self.rate_model.fit(attrs, rates) 33 | 34 | def predict_rate(self, attrs): 35 | return self.rate_model.predict(attrs) 36 | 37 | def predict(self, moneys, attrs): 38 | baseline = self.predict_baseline(moneys) 39 | rate = self.predict_rate(attrs).flatten() 40 | months_hat = np.multiply(baseline, (rate + 1)) 41 | return months_hat 42 | 43 | def test(self, moneys, attrs, months, filenames_test = None, ahs_test = None): 44 | assert len(moneys) == len(attrs) 45 | assert len(attrs) == len(months) 46 | test_num = float(len(moneys)) 47 | 48 | err_less_month = [1, 2, 3, 6] 49 | err_less_than_num = [0] * (max(err_less_month) + 1) 50 | perc_cnt = [0] * 11 51 | percent = 0 52 | mae = 0 53 | mse = 0 54 | 55 | for idx, (money, attr, month) in enumerate(zip(moneys, attrs, months)): 56 | month_hat = self.predict([money], [attr]) 57 | 58 | if abs(month - month_hat) > 5: 59 | if filenames_test != None: 60 | debug_print("\nFilename:", filenames_test[idx]) 61 | 62 | if ahs_test != None: 63 | debug_print("ah:", ahs_test[idx]) 64 | 65 | debug_print("Money:", money) 66 | debug_print("Attrs:", attr) 67 | debug_print("Predict:", month_hat) 68 | debug_print("Actual:", month) 69 | 70 | absolutly_error = abs(month - month_hat) 71 | for month in err_less_month: 72 | if absolutly_error <= month: 73 | err_less_than_num[month] += 1 74 | 75 | mae += (absolutly_error) / test_num 76 | mse += (absolutly_error * absolutly_error) / test_num 77 | 78 | percentage = absolutly_error / month 79 | percent += (percentage) / test_num 80 | perc_cnt[min(int(percentage * 100 / 5), 10)] += 1 81 | 82 | for month in err_less_month: 83 | print("Error <= %d month percentage:" % (month), err_less_than_num[month] / test_num * 100) 84 | 85 | print('MSE:', mse) 86 | print('MAE:', mae) 87 | print('Average error percent: ', percent) 88 | print('Percentage distribution: ', perc_cnt) 89 | return mae, mse, percent, perc_cnt 90 | 91 | def fit(self, moneys, attrs, labels, times = 1): 92 | punish_adjust = np.array([0] * len(moneys)) 93 | for j in range(times): 94 | self.fit_baseline(moneys, np.array(labels) - punish_adjust) 95 | self.fit_rate(moneys, attrs, labels) 96 | 97 | baseline = self.predict_baseline(moneys) 98 | rate = self.predict_rate(attrs).flatten() 99 | punish_adjust = np.multiply(baseline, rate) 100 | 101 | def show_param(self): 102 | print("Baseline predictor") 103 | print(self.baseline_model.coef_) 104 | print(self.baseline_model.intercept_) 105 | print("Adapt rate predictor") 106 | print(self.rate_model.coef_) 107 | print(self.rate_model.intercept_) 108 | 109 | def get_param(self): 110 | baseline_param = "coef: " + ", ".join(str(d) for d in self.baseline_model.coef_) + " intercept: " + str(self.baseline_model.intercept_) 111 | rate_param = "coef: " + ", ".join(str(d) for d in self.rate_model.coef_) + " intercept: " + str(self.rate_model.intercept_) 112 | return baseline_param, rate_param 113 | 114 | 115 | def threshold_judge(self, pred, y, threshold, case): 116 | if case == 0: 117 | return abs(pred - y) / y < threshold 118 | if case > 0: 119 | return (pred - y) / y >= threshold 120 | if case < 0: 121 | return (y - pred) / y >= threshold 122 | 123 | def split_data(self, moneys, attrs, months, filenames = None, ahs = None, threshold = 0.2): 124 | ret_moneys = [[] for _ in range(3)] 125 | ret_months = [[] for _ in range(3)] 126 | ret_attrs = [[] for _ in range(3)] 127 | ret_filenames = [[] for _ in range(3)] 128 | ret_ahs = [[] for _ in range(3)] 129 | ret_errors = [[] for _ in range(3)] 130 | 131 | for idx, (money, attr, month) in enumerate(zip(moneys, attrs, months)): 132 | month_hat = self.predict([money], [attr]) 133 | for case in range(3): 134 | if self.threshold_judge(month_hat, month, threshold, case - 1): 135 | ret_moneys[case].append(money) 136 | ret_months[case].append(month) 137 | ret_attrs[case].append(attr) 138 | ret_filenames[case].append(filenames[idx]) 139 | ret_ahs[case].append(ahs[idx]) 140 | ret_errors[case].append((abs(month - month_hat) / month, month, money, attr, month_hat)) 141 | 142 | return ret_moneys, ret_attrs, ret_months, ret_filenames, ret_ahs, ret_errors 143 | -------------------------------------------------------------------------------- /ss_abl_model.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | 3 | import os 4 | os.environ["CUDA_VISIBLE_DEVICES"] = "0" 5 | import pickle as pk 6 | 7 | import sys 8 | import csv 9 | from sklearn import tree 10 | from sklearn.utils import shuffle 11 | import pandas as pd 12 | from sklearn import linear_model 13 | import numpy as np 14 | from itertools import combinations 15 | from sklearn.cluster import KMeans 16 | import json 17 | 18 | from data_utils import read_csv, process_money, save_json, load_json, getJson 19 | from tools import getVecFromJson 20 | 21 | from bert_class import BERT, get_lastest_ckpt 22 | from sentence_model import SentenceModel 23 | 24 | import shutil 25 | import argparse 26 | 27 | from abduction_model import SentenceAbduction 28 | from result_utils import ResultRecorder 29 | from judger import get_score 30 | 31 | import time 32 | import tensorflow as tf 33 | 34 | config = tf.ConfigProto() 35 | config.gpu_options.allow_growth = True 36 | session = tf.Session(config=config) 37 | 38 | is_debug = False 39 | 40 | def debug_print(*args): 41 | if is_debug: 42 | print(*args) 43 | 44 | def my_parse(): 45 | parser = argparse.ArgumentParser(description = 'ABL Tuned Parameters!') 46 | parser.add_argument('-pretrain_bert_train_epochs', dest='pretrain_bert_train_epochs', \ 47 | type=int, default=4, help='-pretrain_bert_train_epochs: an integer') 48 | parser.add_argument('-pretrain_sentence_model_times', dest='pretrain_sentence_model_times', \ 49 | type=int, default=3, help='-pretrain_sentence_model_times: an integer') 50 | parser.add_argument('-abl_bert_train_epochs', dest='abl_bert_train_epochs', \ 51 | type=int, default=1, help='-abl_bert_train_epochs: an integer') 52 | parser.add_argument('-abl_sentence_model_times', dest='abl_sentence_model_times', \ 53 | type=int, default=3, help='abl_sentence_model_times: an integer') 54 | parser.add_argument('-abl_max_change_num', dest='abl_max_change_num', \ 55 | type=int, default=2, help='abl_max_change_num: an integer') 56 | parser.add_argument('-rule_file_path', dest='rule_file_path', \ 57 | type=str, default="rule_file.txt") 58 | parser.add_argument('-log_dump_file', dest='log_dump_file', \ 59 | type=str, default="default_log.pk") 60 | parser.add_argument('-abl_times', dest='abl_times', \ 61 | type=int, default=1) 62 | return parser.parse_args() 63 | 64 | def selectJson(JsonPath, ahs, JsonOutputPath): 65 | fout = open(JsonOutputPath, 'w', encoding='utf-8') 66 | for ah in ahs: 67 | judgement = getJson(JsonPath, ah) 68 | json_dicts = json.dumps(judgement, ensure_ascii=False) 69 | if judgement != None: 70 | fout.writelines(json_dicts) 71 | fout.writelines("\n") 72 | fout.close() 73 | 74 | def splitJson(JsonPath, ahs, infile, not_infile): 75 | fout1 = open(infile, 'w', encoding='utf-8') 76 | fout2 = open(not_infile, 'w', encoding='utf-8') 77 | 78 | fin = open(JsonPath, 'r', encoding='utf-8') 79 | for line in fin.readlines(): 80 | judgement = json.loads(line) 81 | json_dicts = json.dumps(judgement, ensure_ascii=False) 82 | if judgement[0]["ah"] in ahs: 83 | fout1.writelines(json_dicts) 84 | fout1.writelines("\n") 85 | else: 86 | fout2.writelines(json_dicts) 87 | fout2.writelines("\n") 88 | 89 | fout1.close() 90 | fout2.close() 91 | 92 | def split_csv(csv_path, ah_list, in_file, not_in_file): 93 | df = pd.read_csv(csv_path, encoding='gbk') 94 | data = df[["filename", "ah", "sum", "no_damage_bool", "attitude_bool", "surrender_bool", "again_bool", "young_bool", "forgive_bool", 95 | "tool_bool", "indoor_bool", "theft_bool", "year_num", "probation", "money_num"]] 96 | data = np.array(data) 97 | data = data.tolist() 98 | 99 | rowname = ["filename", "ah", "sum", "no_damage_bool", "attitude_bool", "surrender_bool", "again_bool", "young_bool", "forgive_bool", 100 | "tool_bool", "indoor_bool", "theft_bool", "year_num", "probation", "money_num"] 101 | great_file = open(in_file, 'w', newline='') 102 | other = open(not_in_file, 'w', newline='') 103 | great_file_csv = csv.writer(great_file) 104 | great_file_csv.writerow(rowname) 105 | 106 | other_csv = csv.writer(other) 107 | other_csv.writerow(rowname) 108 | for row in data: 109 | if row[1] in ah_list: 110 | great_file_csv.writerow(row) 111 | else: 112 | other_csv.writerow(row) 113 | great_file.close() 114 | other.close() 115 | 116 | def getDic(): 117 | tags_list = [] 118 | with open('./tags.txt', 'r', encoding='utf-8') as tagf: 119 | for line in tagf.readlines(): 120 | tags_list.append(line.strip()) 121 | 122 | transToDic = dict() 123 | for key, value in enumerate(tags_list): 124 | transToDic[value] = key 125 | return transToDic,tags_list 126 | 127 | def get_nlp_label(csv_file, json_file): 128 | attr_vecs = getVecFromJson(json_file,) 129 | filenames30, ahs30, data30, labels30, attrs30 = read_csv(csv_file) 130 | count = 0 131 | filenames_new, ahs_new, data_new, labels_new, attrs_new = [],[],[],[],[] 132 | 133 | for dic in attr_vecs: 134 | for idx, value in enumerate(zip(filenames30, ahs30)): 135 | name = value[0] + "&" + value[-1] 136 | for k,v in dic.items(): 137 | if k == name: 138 | orig_vec = attrs30[idx] 139 | if v != orig_vec: 140 | count += 1 141 | attrs30[idx] = v 142 | 143 | attrs30[idx] = v 144 | filenames_new.append(value[0]) 145 | ahs_new.append(value[-1]) 146 | data_new.append(data30[idx]) 147 | labels_new.append(labels30[idx]) 148 | attrs_new.append(v) 149 | 150 | return ahs_new, data_new, labels_new, attrs_new 151 | 152 | def get_nlp_result(json_file, filenames, ahs, money, labels): 153 | attr_vecs = getVecFromJson(json_file,) 154 | filenames_new, ahs_new, data_new, labels_new, attrs_new = [],[],[],[],[] 155 | 156 | for dic in attr_vecs: 157 | for idx, value in enumerate(zip(filenames, ahs)): 158 | name = value[0] + "&" + value[-1] 159 | for k, v in dic.items(): 160 | if k == name: 161 | filenames_new.append(value[0]) 162 | ahs_new.append(value[-1]) 163 | data_new.append(money[idx]) 164 | labels_new.append(labels[idx]) 165 | attrs_new.append(v) 166 | 167 | return filenames_new, ahs_new, data_new, labels_new, attrs_new 168 | 169 | def get_bert_generate_label(model, context_filename, money_filename, tmp_json_path, tags_list): 170 | lastest_ckpt = get_lastest_ckpt(model.output_dir + "/checkpoint") 171 | pred_labels, result_prob = model.predict(context_filename, model.output_dir + "/" + lastest_ckpt) 172 | model.generate_pred_file(tags_list, context_filename, tmp_json_path, pred_labels, result_prob) 173 | filenames, ahs, money, labels, _ = read_csv(model.data_dir + '/' + money_filename) 174 | filenames_new, ahs_new, money_new, labels_new, attrs_new = get_nlp_result(tmp_json_path, filenames, ahs, money, labels) 175 | return filenames_new, ahs_new, money_new, labels_new, attrs_new 176 | 177 | def rmdir(dir_path): 178 | if os.path.exists(dir_path) and os.path.isdir(dir_path): 179 | shutil.rmtree(dir_path) 180 | 181 | if __name__ == "__main__": 182 | recorder = ResultRecorder() 183 | 184 | for arg in sys.argv: 185 | recorder.write_pair("args", arg) 186 | 187 | tags_list = [] 188 | with open('data/tags.txt', 'r', encoding='utf-8') as tagf: 189 | for line in tagf.readlines(): 190 | tags_list.append(line.strip()) 191 | 192 | args = my_parse() 193 | for arg in args.__dict__: 194 | recorder.write_pair(arg + "@arg", args.__dict__[arg]) 195 | pretrain_bert_train_epochs = args.pretrain_bert_train_epochs 196 | pretrain_sentence_model_times = args.pretrain_sentence_model_times 197 | abl_bert_train_epochs = args.abl_bert_train_epochs 198 | abl_sentence_model_times = args.abl_sentence_model_times 199 | abl_max_change_num = args.abl_max_change_num 200 | rule_file_path = args.rule_file_path 201 | log_dump_file = args.log_dump_file 202 | abl_times = args.abl_times 203 | 204 | print("Rule file is :", rule_file_path) 205 | if rule_file_path == "None": 206 | rule_file_path = None 207 | 208 | pretrain_filename = "0_0.10.json" 209 | pretrain_money_filename = "./data/0_0.10.csv" 210 | abl_train_filename = "1_0.90.json" 211 | abl_train_money_filename = "1_0.90.csv" 212 | test_filename = "10.json" 213 | test_money_filename = "10.csv" 214 | 215 | recorder.write_pair("Method", "ABL") 216 | 217 | pretrain_filenames, pretrain_ahs, pretrain_money, pretrain_labels, pretrain_attrs = read_csv(pretrain_money_filename) 218 | 219 | perception = BERT(bert_path = "./chinese_L-12_H-768_A-12", data_dir = "./data", output_dir = "./abl_model_0", num_train_epochs = pretrain_bert_train_epochs) 220 | sentence = SentenceModel() 221 | abductor = SentenceAbduction(sentence, rule_file_path, True) 222 | 223 | perception.train(pretrain_filename) 224 | lastest_ckpt = get_lastest_ckpt(perception.output_dir + "/checkpoint") 225 | print("Test BERT:") 226 | bert_eval_info = perception.eval(test_filename, perception.output_dir + "/" + lastest_ckpt) 227 | for info in bert_eval_info: 228 | recorder.write_pair("init_" + info[0], info[1]) 229 | 230 | sentence.fit(pretrain_money, pretrain_attrs, pretrain_labels, pretrain_sentence_model_times) 231 | sentence.show_param() 232 | baseline, rate = sentence.get_param() 233 | recorder.write_pair("init_baseline", baseline) 234 | recorder.write_pair("init_rate", rate) 235 | 236 | tmp_json_path = "tmp/abl_predict_%d.json" % (0) 237 | filenames_new, ahs_new, money_new, labels_new, attrs_new = \ 238 | get_bert_generate_label(perception, test_filename, test_money_filename, tmp_json_path, tags_list) 239 | 240 | best_mae, best_mse, _, _ = sentence.test(money_new, attrs_new, labels_new, filenames_new, ahs_new) 241 | ret_raw, ret_str = get_score("data/" + test_filename, tmp_json_path, "data/tags_for_test.txt") 242 | recorder.write_pair("init_MAE", best_mae) 243 | recorder.write_pair("init_MSE", best_mse) 244 | recorder.write_pair("init_f1_score", ret_str) 245 | 246 | pretrain_bert_train_data = load_json(perception.data_dir + "/" + pretrain_filename) 247 | 248 | 249 | model_idx = 0 250 | for t in range(abl_times): 251 | print("abduction times %d" % t, "model idx %d" % (model_idx)) 252 | 253 | tmp_json_path = "tmp/abl_train_%d.json" % (t) 254 | filenames_new, ahs_new, money_new, labels_new, attrs_new = \ 255 | get_bert_generate_label(perception, abl_train_filename, abl_train_money_filename, tmp_json_path, tags_list) 256 | 257 | t_b = time.time() 258 | abductor.set_predict_model(sentence) 259 | attrs_abduced, labels_abduced, judgement_jsons = abductor.abduce_batch(tmp_json_path, ahs_new, money_new, attrs_new, labels_new, abl_max_change_num) 260 | t_e = time.time() 261 | print("Abduce all time cost is : ", t_e - t_b) 262 | 263 | json_save_filename = "abl_retrain_%d.json" % (t + 1) 264 | save_json(perception.data_dir + "/" + json_save_filename, judgement_jsons + pretrain_bert_train_data) 265 | 266 | perception.output_dir = "./abl_model_%d" % ((model_idx % 10) + 1) 267 | perception.num_train_epochs = abl_bert_train_epochs 268 | rmdir(perception.output_dir) 269 | perception.read_config() 270 | perception.train(json_save_filename) 271 | lastest_ckpt = get_lastest_ckpt(perception.output_dir + "/checkpoint") 272 | 273 | print("Test BERT:") 274 | bert_eval_info = perception.eval(test_filename, perception.output_dir + "/" + lastest_ckpt) 275 | for info in bert_eval_info: 276 | recorder.write_pair(info[0], info[1]) 277 | 278 | filenames_new, ahs_new, money_new, labels_new, attrs_new = \ 279 | get_bert_generate_label(perception, abl_train_filename, abl_train_money_filename, tmp_json_path, tags_list) 280 | sentence.fit(money_new + pretrain_money, attrs_new + pretrain_attrs, labels_new + pretrain_labels, abl_sentence_model_times) 281 | sentence.show_param() 282 | baseline, rate = sentence.get_param() 283 | recorder.write_pair("baseline", baseline) 284 | recorder.write_pair("rate", rate) 285 | 286 | tmp_json_path = "tmp/abl_predict_%d.json" % (t + 1) 287 | filenames_new, ahs_new, money_new, labels_new, attrs_new = \ 288 | get_bert_generate_label(perception, test_filename, test_money_filename, tmp_json_path, tags_list) 289 | 290 | tmp_mae, tmp_mse, _, _ = sentence.test(money_new, attrs_new, labels_new, filenames_new, ahs_new) 291 | ret_raw, ret_str = get_score("data/" + test_filename, tmp_json_path, "data/tags_for_test.txt") 292 | recorder.write_pair("tmp_f1_score", ret_str) 293 | recorder.write_pair("tmp_MAE", tmp_mae) 294 | recorder.write_pair("tmp_MSE", tmp_mse) 295 | 296 | model_idx += 1 297 | ''' 298 | if (tmp_mae <= best_mae): 299 | model_idx += 1 300 | best_mae = tmp_mae 301 | print("Model be better!") 302 | else: 303 | checkpoint_dir = "./abl_model_%d" % (((model_idx - 1) % 5) + 1) 304 | lastest_ckpt = get_lastest_ckpt(checkpoint_dir + "/checkpoint") 305 | perception.output_dir = checkpoint_dir 306 | perception.init_checkpoint = checkpoint_dir + "/" + lastest_ckpt 307 | perception.read_config() 308 | print("Model be worse! Need retrain!") 309 | ''' 310 | 311 | recorder.write_pair("best_MAE", best_mae) 312 | recorder.write_pair("best_MSE", best_mse) 313 | 314 | print("training times %d" % t) 315 | 316 | recorder.dump(open(log_dump_file, "wb")) 317 | 318 | -------------------------------------------------------------------------------- /tmp/this is the tmp folder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AbductiveLearning/SS-ABL/57429b68edc5cc5ad4ccfe9b0616dbc2c53c2820/tmp/this is the tmp folder -------------------------------------------------------------------------------- /tools.py: -------------------------------------------------------------------------------- 1 | import json 2 | import random 3 | 4 | def splitWithPro(pro = 0.25): 5 | fin = open(u'./data_4_5/40.json', 'r', encoding='utf-8') 6 | lines = [] 7 | for line in fin.readlines(): 8 | line = json.loads(line) 9 | lines.append(line) 10 | random.shuffle(lines) 11 | test_set_size = int(len(lines) * pro) 12 | test1 = lines[:test_set_size] 13 | test2 = lines[test_set_size:2 * test_set_size] 14 | test3 = lines[test_set_size*2:test_set_size*3] 15 | test4 = lines[test_set_size*3:] 16 | 17 | with open('./data/all_data/train_1.json', 'w', encoding='utf-8') as f: 18 | for line in test1: 19 | json.dump(line, f, ensure_ascii=False) 20 | f.write("\n") 21 | 22 | with open('./data/all_data/train_2.json', 'w', encoding='utf-8') as f: 23 | for line in test2: 24 | json.dump(line, f, ensure_ascii=False) 25 | f.write("\n") 26 | 27 | with open('./data/all_data/train_3.json', 'w', encoding='utf-8') as f: 28 | for line in test3: 29 | json.dump(line, f, ensure_ascii=False) 30 | f.write("\n") 31 | 32 | with open('./data/all_data/train_4.json', 'w', encoding='utf-8') as f: 33 | for line in test4: 34 | json.dump(line, f, ensure_ascii=False) 35 | f.write("\n") 36 | 37 | def getDic(): 38 | tags_list = [] 39 | with open('data/all_data/tags.txt', 'r', encoding='utf-8') as tagf: 40 | for line in tagf.readlines(): 41 | tags_list.append(line.strip()) 42 | 43 | transToDic = dict() 44 | for key, value in enumerate(tags_list): 45 | transToDic[value] = key 46 | return transToDic,tags_list 47 | 48 | 49 | def getVecFromJson(fromPath,toPath = u'./data/all_data/pre_vecs.json'): 50 | tags_list = [] 51 | with open(u'./data/tags.txt', 'r', encoding='utf-8') as tagf: 52 | for line in tagf.readlines(): 53 | tags_list.append(line.strip()) 54 | 55 | transToDic = dict() 56 | for key,value in enumerate(tags_list): 57 | transToDic[value] = key 58 | vecs = [] 59 | yaoshu = [] 60 | fin = open(fromPath, 'r', encoding='utf-8') 61 | 62 | for line in fin.readlines(): 63 | file_vec = dict() 64 | vec = [0] * len(tags_list) 65 | line = json.loads(line) 66 | crnt_dic = line[0] 67 | file_name = str(crnt_dic['file'])+"&"+str(crnt_dic['ah']) 68 | file_vec[file_name] = [] 69 | 70 | for dic in line: 71 | for lb in dic["label"]: 72 | idx = transToDic[lb] 73 | vec[idx] = 1 74 | yaoshu.append(lb) 75 | file_vec[file_name] = vec 76 | vecs.append(file_vec) 77 | 78 | return vecs 79 | 80 | 81 | def calaAcc(pre_path=u'./data/all_data/vecs.json',true_path=u'./data/all_data/test_true_vecs.json',tags=None): 82 | preLbs = [] 83 | fin = open(pre_path, 'r', encoding='utf-8') 84 | for line in fin.readlines(): 85 | line = json.loads(line) 86 | preLbs.append(line) 87 | 88 | trueLbs = [] 89 | fin = open(true_path, 'r', encoding='utf-8') 90 | for line in fin.readlines(): 91 | line = json.loads(line) 92 | trueLbs.append(line) 93 | 94 | import numpy as np 95 | preLbs = np.array(preLbs) 96 | trueLbs = np.array(trueLbs) 97 | for i in range(len(preLbs[0])): 98 | if tags != None: 99 | print(tags[i]) 100 | col_pre = preLbs[:,i] 101 | col_true = trueLbs[:,i] 102 | print(np.mean(col_pre == col_true)) 103 | 104 | print("============================") 105 | 106 | def getDifferToFile(truePath = u'./data/all_data/10_new.json',bertPath = u'./tmp/newoutput/output_22453_10_new.json' ): 107 | vec_bert = getVecFromJson(bertPath) 108 | vec_true = getVecFromJson(truePath) 109 | differ_idxs = [] 110 | for idx in range(len(vec_bert)): 111 | if vec_bert[idx] != vec_true[idx]: 112 | differ_idxs.append(idx) 113 | print(len(differ_idxs)) 114 | fin_true = open(truePath, 'r', encoding='utf-8') 115 | fin_bert = open(bertPath,'r',encoding='utf8') 116 | 117 | diff_arr = [] 118 | for idx,value in enumerate(zip(fin_true.readlines(),fin_bert.readlines())): 119 | if idx in differ_idxs: 120 | print("true_attrs") 121 | print(vec_true[idx]) 122 | print("bert_attrs") 123 | print(vec_bert[idx]) 124 | temp_arr = [] 125 | value_true = json.loads(value[0]) 126 | value_bert = json.loads(value[-1]) 127 | for dic_true,dic_bert in zip(value_true,value_bert): 128 | set_bert = set(dic_bert['label']) 129 | set_true = set(dic_true['label']) 130 | if set_bert != set_true: 131 | output_diff = dict() 132 | output_diff['file'] = dic_true['file'] 133 | output_diff['ah'] = dic_true['ah'] 134 | output_diff['sentence'] = dic_true['sentence'] 135 | output_diff['bert_label'] = dic_bert['label'] 136 | output_diff['true_label'] = dic_true['label'] 137 | output_diff['bert_pro'] = dic_bert['pro'] 138 | temp_arr.append(output_diff) 139 | print('sentence:'+output_diff['sentence']) 140 | print('true_label') 141 | print(output_diff['true_label']) 142 | pri_vec_1 = [] 143 | for label in output_diff['true_label']: 144 | a, _ = getDic() 145 | i = a[label] 146 | pri_vec_1.append(output_diff['bert_pro'][i]) 147 | print('true_label_bert_pro') 148 | print(pri_vec_1) 149 | print('bert_label') 150 | print(output_diff['bert_label']) 151 | pri_vec = [] 152 | for label in output_diff['bert_label']: 153 | a,_ = getDic() 154 | i = a[label] 155 | pri_vec.append(output_diff['bert_pro'][i]) 156 | print('bert_pro') 157 | print(pri_vec) 158 | 159 | diff_arr.append(temp_arr) 160 | with open(u'./data/all_data/differ.json', 'w', encoding='utf-8') as f: 161 | for line in diff_arr: 162 | json.dump(line, f, ensure_ascii=False) 163 | f.write("\n") 164 | 165 | 166 | def find3PosMax(nums): 167 | max1, max2, max3 = None, None, None 168 | for num in nums: 169 | if num < 0: 170 | continue 171 | if max1 is None or max1 < num: 172 | max1, num = num, max1 173 | if num is None: 174 | continue 175 | if max2 is None or num > max2: 176 | max2, num = num, max2 177 | if num is None: 178 | continue 179 | if max3 is None or num > max3: 180 | max3 = num 181 | return max1, max2, max3 182 | 183 | 184 | --------------------------------------------------------------------------------