├── README.md ├── 手写AI.jpg ├── .gitignore ├── my_ner.py ├── 11_16_myner.py ├── LICENSE └── my_ner+crf.py /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shouxieai/nlp-bilstm_crf-ner/HEAD/README.md -------------------------------------------------------------------------------- /手写AI.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shouxieai/nlp-bilstm_crf-ner/HEAD/手写AI.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-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 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /my_ner.py: -------------------------------------------------------------------------------- 1 | import os 2 | from torch.utils.data import Dataset,DataLoader 3 | import torch 4 | import torch.nn as nn 5 | from sklearn.metrics import f1_score 6 | 7 | def build_corpus(split, make_vocab=True, data_dir="data"): 8 | """读取数据""" 9 | assert split in ['train', 'dev', 'test'] 10 | 11 | word_lists = [] 12 | tag_lists = [] 13 | with open(os.path.join(data_dir, split+".char.bmes"), 'r', encoding='utf-8') as f: 14 | word_list = [] 15 | tag_list = [] 16 | for line in f: 17 | if line != '\n': 18 | word, tag = line.strip('\n').split() 19 | word_list.append(word) 20 | tag_list.append(tag) 21 | else: 22 | word_lists.append(word_list) 23 | tag_lists.append(tag_list) 24 | word_list = [] 25 | tag_list = [] 26 | 27 | word_lists = sorted(word_lists, key=lambda x: len(x), reverse=True) 28 | tag_lists = sorted(tag_lists, key=lambda x: len(x), reverse=True) 29 | 30 | # 如果make_vocab为True,还需要返回word2id和tag2id 31 | if make_vocab: 32 | word2id = build_map(word_lists) 33 | tag2id = build_map(tag_lists) 34 | word2id[''] = len(word2id) 35 | word2id[''] = len(word2id) 36 | 37 | tag2id[''] = len(tag2id) 38 | return word_lists, tag_lists, word2id, tag2id 39 | else: 40 | return word_lists, tag_lists 41 | 42 | 43 | def build_map(lists): 44 | maps = {} 45 | for list_ in lists: 46 | for e in list_: 47 | if e not in maps: 48 | maps[e] = len(maps) 49 | 50 | return maps 51 | 52 | 53 | class MyDataset(Dataset): 54 | def __init__(self,datas,tags,word_2_index,tag_2_index): 55 | self.datas = datas 56 | self.tags = tags 57 | self.word_2_index = word_2_index 58 | self.tag_2_index = tag_2_index 59 | 60 | def __getitem__(self,index): 61 | data = self.datas[index] 62 | tag = self.tags[index] 63 | 64 | data_index = [self.word_2_index.get(i,self.word_2_index[""]) for i in data] 65 | tag_index = [self.tag_2_index[i] for i in tag] 66 | 67 | return data_index,tag_index 68 | 69 | 70 | def __len__(self): 71 | assert len(self.datas) == len(self.tags) 72 | return len(self.datas) 73 | 74 | def batch_data_pro(self,batch_datas): 75 | global device 76 | data , tag = [],[] 77 | da_len = [] 78 | for da,ta in batch_datas: 79 | data.append(da) 80 | tag.append(ta) 81 | da_len.append(len(da)) 82 | max_len = max(da_len) 83 | 84 | data = [i + [self.word_2_index[""]] * (max_len - len(i)) for i in data] 85 | tag = [i + [self.tag_2_index[""]] * (max_len - len(i)) for i in tag] 86 | 87 | data = torch.tensor(data,dtype=torch.long,device = device) 88 | tag = torch.tensor(tag,dtype=torch.long,device = device) 89 | return data , tag, da_len 90 | 91 | 92 | class MyModel(nn.Module): 93 | def __init__(self,embedding_num,hidden_num,corpus_num,bi,class_num,pad_index): 94 | super().__init__() 95 | self.embedding_num = embedding_num 96 | self.hidden_num = hidden_num 97 | self.corpus_num = corpus_num 98 | self.bi = bi 99 | 100 | self.embedding = nn.Embedding(corpus_num,embedding_num) 101 | self.lstm = nn.LSTM(embedding_num,hidden_num,batch_first=True,bidirectional=bi) 102 | 103 | if bi: 104 | self.classifier = nn.Linear(hidden_num*2,class_num) 105 | else: 106 | self.classifier = nn.Linear(hidden_num, class_num) 107 | 108 | self.cross_loss = nn.CrossEntropyLoss(ignore_index=pad_index) 109 | 110 | def forward(self,data_index,data_len , tag_index=None): 111 | em = self.embedding(data_index) 112 | pack = nn.utils.rnn.pack_padded_sequence(em,data_len,batch_first=True) 113 | output,_ = self.lstm(pack) 114 | output,lens = nn.utils.rnn.pad_packed_sequence(output,batch_first=True) 115 | 116 | pre = self.classifier(output) 117 | 118 | self.pre = torch.argmax(pre, dim=-1).reshape(-1) 119 | 120 | if tag_index is not None: 121 | loss = self.cross_loss(pre.reshape(-1,pre.shape[-1]),tag_index.reshape(-1)) 122 | return loss 123 | 124 | 125 | if __name__ == "__main__": 126 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 127 | 128 | train_word_lists, train_tag_lists, word_2_index, tag_2_index = build_corpus("train") 129 | dev_word_lists, dev_tag_lists = build_corpus("dev", make_vocab=False) 130 | test_word_lists, test_tag_lists = build_corpus("test", make_vocab=False) 131 | 132 | corpus_num = len(word_2_index) 133 | class_num = len(tag_2_index) 134 | 135 | train_batch_size = 5 136 | dev_batch_size = len(dev_word_lists) 137 | epoch = 100 138 | lr = 0.001 139 | embedding_num = 128 140 | hidden_num = 129 141 | 142 | bi = True 143 | 144 | train_dataset = MyDataset(train_word_lists,train_tag_lists,word_2_index, tag_2_index) 145 | train_dataloader = DataLoader(train_dataset,batch_size=train_batch_size,shuffle=False,collate_fn=train_dataset.batch_data_pro) 146 | 147 | dev_dataset = MyDataset(dev_word_lists, dev_tag_lists, word_2_index, tag_2_index) 148 | dev_dataloader = DataLoader(dev_dataset, batch_size=dev_batch_size, shuffle=False,collate_fn=dev_dataset.batch_data_pro) 149 | 150 | 151 | model = MyModel(embedding_num,hidden_num,corpus_num,bi,class_num,word_2_index[""]) 152 | model = model.to(device) 153 | 154 | opt = torch.optim.Adam(model.parameters(),lr = lr) 155 | 156 | for e in range(epoch): 157 | model.train() 158 | for data , tag, da_len in train_dataloader: 159 | loss = model.forward(data,da_len,tag) 160 | loss.backward() 161 | opt.step() 162 | opt.zero_grad() 163 | 164 | model.eval() # F1,准确率,精确率,召回率 165 | for dev_data , dev_tag, dev_da_len in dev_dataloader: 166 | test_loss = model.forward(dev_data,dev_da_len,dev_tag) 167 | score = f1_score(dev_tag.reshape(-1).cpu().numpy(),model.pre.cpu().numpy(),average="micro") 168 | print(score) 169 | break 170 | -------------------------------------------------------------------------------- /11_16_myner.py: -------------------------------------------------------------------------------- 1 | import os 2 | from torch.utils.data import Dataset,DataLoader 3 | import torch 4 | import torch.nn as nn 5 | from sklearn.metrics import f1_score 6 | 7 | 8 | def build_corpus(split, make_vocab=True, data_dir="data"): 9 | """读取数据""" 10 | assert split in ['train', 'dev', 'test'] 11 | 12 | word_lists = [] 13 | tag_lists = [] 14 | with open(os.path.join(data_dir, split+".char.bmes"), 'r', encoding='utf-8') as f: 15 | word_list = [] 16 | tag_list = [] 17 | for line in f: 18 | if line != '\n': 19 | word, tag = line.strip('\n').split() 20 | word_list.append(word) 21 | tag_list.append(tag) 22 | else: 23 | word_lists.append(word_list) 24 | tag_lists.append(tag_list) 25 | word_list = [] 26 | tag_list = [] 27 | 28 | word_lists = sorted(word_lists, key=lambda x: len(x), reverse=False) 29 | tag_lists = sorted(tag_lists, key=lambda x: len(x), reverse=False) 30 | 31 | # 如果make_vocab为True,还需要返回word2id和tag2id 32 | if make_vocab: 33 | word2id = build_map(word_lists) 34 | tag2id = build_map(tag_lists) 35 | word2id[''] = len(word2id) 36 | word2id[''] = len(word2id) 37 | 38 | tag2id[''] = len(tag2id) 39 | return word_lists, tag_lists, word2id, tag2id 40 | else: 41 | return word_lists, tag_lists 42 | 43 | def build_map(lists): 44 | maps = {} 45 | for list_ in lists: 46 | for e in list_: 47 | if e not in maps: 48 | maps[e] = len(maps) 49 | 50 | return maps 51 | 52 | class MyDataset(Dataset): 53 | def __init__(self,datas,tags,word_2_index,tag_2_index): 54 | self.datas = datas 55 | self.tags = tags 56 | self.word_2_index = word_2_index 57 | self.tag_2_index = tag_2_index 58 | 59 | def __getitem__(self,index): 60 | data = self.datas[index] 61 | tag = self.tags[index] 62 | 63 | data_index = [self.word_2_index.get(i,self.word_2_index[""]) for i in data] 64 | tag_index = [self.tag_2_index[i] for i in tag] 65 | 66 | return data_index,tag_index 67 | 68 | def __len__(self): 69 | assert len(self.datas) == len(self.tags) 70 | return len(self.tags) 71 | 72 | def pro_batch_data(self,batch_datas): 73 | global device 74 | datas = [] 75 | tags = [] 76 | batch_lens = [] 77 | 78 | for data,tag in batch_datas: 79 | datas.append(data) 80 | tags.append(tag) 81 | batch_lens.append(len(data)) 82 | batch_max_len = max(batch_lens) 83 | 84 | datas = [i + [self.word_2_index[""]] * (batch_max_len - len(i)) for i in datas] 85 | tags = [i + [self.tag_2_index[""]] * (batch_max_len - len(i)) for i in tags] 86 | 87 | return torch.tensor(datas,dtype=torch.int64,device=device),torch.tensor(tags,dtype=torch.long,device=device) 88 | 89 | 90 | 91 | class Mymodel(nn.Module): 92 | def __init__(self,corpus_num,embedding_num,hidden_num,class_num,bi=True): 93 | super().__init__() 94 | 95 | self.embedding = nn.Embedding(corpus_num,embedding_num) 96 | self.lstm = nn.LSTM(embedding_num,hidden_num,batch_first=True,bidirectional=bi) 97 | 98 | if bi : 99 | self.classifier = nn.Linear(hidden_num * 2,class_num) 100 | else: 101 | self.classifier = nn.Linear(hidden_num, class_num) 102 | 103 | self.cross_loss = nn.CrossEntropyLoss() 104 | 105 | 106 | 107 | def forward(self,batch_data,batch_tag=None): 108 | embedding = self.embedding(batch_data) 109 | out,_ = self.lstm(embedding) 110 | 111 | pre = self.classifier(out) 112 | self.pre = torch.argmax(pre, dim=-1).reshape(-1) 113 | if batch_tag is not None: 114 | loss = self.cross_loss(pre.reshape(-1,pre.shape[-1]),batch_tag.reshape(-1)) 115 | return loss 116 | 117 | 118 | 119 | 120 | def test(): 121 | global word_2_index,model,index_2_tag,device 122 | while True: 123 | text = input("请输入:") 124 | text_index = [[word_2_index.get(i,word_2_index[""]) for i in text]] 125 | text_index = torch.tensor(text_index,dtype=torch.int64,device=device) 126 | model.forward(text_index) 127 | pre = [index_2_tag[i] for i in model.pre] 128 | 129 | print([f'{w}_{s}' for w,s in zip(text,pre)]) 130 | 131 | 132 | 133 | 134 | if __name__ == "__main__": 135 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 136 | 137 | train_data,train_tag,word_2_index,tag_2_index = build_corpus("train",make_vocab=True) 138 | dev_data,dev_tag = build_corpus("dev",make_vocab=False) 139 | index_2_tag = [i for i in tag_2_index] 140 | 141 | corpus_num = len(word_2_index) 142 | class_num = len(tag_2_index) 143 | 144 | epoch = 10 145 | train_batch_size = 50 146 | dev_batch_size = 100 147 | embedding_num = 101 148 | hidden_num = 107 149 | bi = True 150 | lr = 0.001 151 | 152 | train_dataset = MyDataset(train_data,train_tag,word_2_index,tag_2_index) 153 | train_dataloader = DataLoader(train_dataset,train_batch_size,shuffle=False,collate_fn=train_dataset.pro_batch_data) 154 | 155 | dev_dataset = MyDataset(dev_data, dev_tag, word_2_index, tag_2_index) 156 | dev_dataloader = DataLoader(dev_dataset, dev_batch_size, shuffle=False,collate_fn=dev_dataset.pro_batch_data) 157 | 158 | model = Mymodel(corpus_num,embedding_num,hidden_num,class_num,bi) 159 | opt = torch.optim.Adam(model.parameters(),lr = lr) 160 | model = model.to(device) 161 | 162 | for e in range(epoch): 163 | model.train() 164 | for batch_data,batch_tag in train_dataloader: 165 | train_loss = model.forward(batch_data,batch_tag) 166 | train_loss.backward() 167 | opt.step() 168 | opt.zero_grad() 169 | 170 | model.eval() 171 | all_pre = [] 172 | all_tag = [] 173 | for dev_batch_data,dev_batch_tag in dev_dataloader: 174 | dev_loss = model.forward(dev_batch_data,dev_batch_tag) 175 | all_pre.extend(model.pre.detach().cpu().numpy().tolist()) 176 | all_tag.extend(dev_batch_tag.detach().cpu().numpy().reshape(-1).tolist()) 177 | score = f1_score(all_tag,all_pre,average="micro") 178 | print(f"{e},f1_score:{score:.3f},dev_loss:{dev_loss:.3f},train_loss:{train_loss:.3f}") 179 | test() 180 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /my_ner+crf.py: -------------------------------------------------------------------------------- 1 | import os 2 | from itertools import zip_longest 3 | from torch.utils.data import Dataset,DataLoader 4 | import torch 5 | import torch.nn as nn 6 | from sklearn.metrics import f1_score 7 | # from seqeval.metrics import f1_score 8 | 9 | def build_corpus(split, make_vocab=True, data_dir="data"): 10 | """读取数据""" 11 | assert split in ['train', 'dev', 'test'] 12 | 13 | word_lists = [] 14 | tag_lists = [] 15 | with open(os.path.join(data_dir, split+".char.bmes"), 'r', encoding='utf-8') as f: 16 | word_list = [] 17 | tag_list = [] 18 | for line in f: 19 | if line != '\n': 20 | word, tag = line.strip('\n').split() 21 | word_list.append(word) 22 | tag_list.append(tag) 23 | else: 24 | word_lists.append(word_list+[""]) 25 | 26 | tag_lists.append(tag_list+[""]) 27 | 28 | word_list = [] 29 | tag_list = [] 30 | 31 | word_lists = sorted(word_lists, key=lambda x: len(x), reverse=True) 32 | tag_lists = sorted(tag_lists, key=lambda x: len(x), reverse=True) 33 | 34 | # 如果make_vocab为True,还需要返回word2id和tag_2_index 35 | if make_vocab: 36 | word2id = build_map(word_lists) 37 | tag_2_index = build_map(tag_lists) 38 | word2id[''] = len(word2id) 39 | word2id[''] = len(word2id) 40 | word2id[""] = len(word2id) 41 | # word2id[""] = len(word2id) 42 | 43 | tag_2_index[''] = len(tag_2_index) 44 | tag_2_index[""] = len(tag_2_index) 45 | # tag_2_index[""] = len(tag_2_index) 46 | return word_lists, tag_lists, word2id, tag_2_index 47 | else: 48 | return word_lists, tag_lists 49 | 50 | def build_map(lists): 51 | maps = {} 52 | for list_ in lists: 53 | for e in list_: 54 | if e not in maps: 55 | maps[e] = len(maps) 56 | 57 | return maps 58 | 59 | class MyDataset(Dataset): 60 | def __init__(self,datas,tags,word_2_index,tag_2_index): 61 | self.datas = datas 62 | self.tags = tags 63 | self.word_2_index = word_2_index 64 | self.tag_2_index = tag_2_index 65 | 66 | def __getitem__(self,index): 67 | data = self.datas[index] 68 | tag = self.tags[index] 69 | 70 | data_index = [self.word_2_index.get(i,self.word_2_index[""]) for i in data] 71 | tag_index = [self.tag_2_index[i] for i in tag] 72 | 73 | return data_index,tag_index 74 | 75 | def __len__(self): 76 | assert len(self.datas) == len(self.tags) 77 | return len(self.tags) 78 | 79 | def pro_batch_data(self,batch_datas): 80 | global device 81 | datas = [] 82 | tags = [] 83 | batch_lens = [] 84 | 85 | for data,tag in batch_datas: 86 | datas.append(data) 87 | tags.append(tag) 88 | batch_lens.append(len(data)) 89 | batch_max_len = max(batch_lens) 90 | 91 | datas = [i + [self.word_2_index[""]] * (batch_max_len - len(i)) for i in datas] 92 | tags = [i + [self.tag_2_index[""]] * (batch_max_len - len(i)) for i in tags] 93 | 94 | return torch.tensor(datas,dtype=torch.int64,device=device),torch.tensor(tags,dtype=torch.long,device=device),batch_lens 95 | 96 | 97 | class Mymodel(nn.Module): 98 | def __init__(self,corpus_num,embedding_num,hidden_num,class_num,bi=True): 99 | super().__init__() 100 | 101 | self.embedding = nn.Embedding(corpus_num,embedding_num) 102 | self.lstm = nn.LSTM(embedding_num,hidden_num,batch_first=True,bidirectional=bi) 103 | 104 | if bi : 105 | self.classifier = nn.Linear(hidden_num * 2,class_num) 106 | else: 107 | self.classifier = nn.Linear(hidden_num, class_num) 108 | 109 | self.transition = nn.Parameter(torch.ones(class_num, class_num) * 1 / class_num) 110 | 111 | self.loss_fun = self.cal_lstm_crf_loss 112 | 113 | def cal_lstm_crf_loss(self,crf_scores, targets): 114 | """计算双向LSTM-CRF模型的损失 115 | 该损失函数的计算可以参考:https://arxiv.org/pdf/1603.01360.pdf 116 | """ 117 | global tag_2_index 118 | pad_id = tag_2_index.get('') 119 | start_id = tag_2_index.get('') 120 | end_id = tag_2_index.get('') 121 | 122 | device = crf_scores.device 123 | 124 | # targets:[B, L] crf_scores:[B, L, T, T] 125 | batch_size, max_len = targets.size() 126 | target_size = len(tag_2_index) 127 | 128 | # mask = 1 - ((targets == pad_id) + (targets == end_id)) # [B, L] 129 | mask = (targets != pad_id) 130 | lengths = mask.sum(dim=1) 131 | targets = self.indexed(targets, target_size, start_id) 132 | 133 | # # 计算Golden scores方法1 134 | # import pdb 135 | # pdb.set_trace() 136 | targets = targets.masked_select(mask) # [real_L] 137 | 138 | flatten_scores = crf_scores.masked_select(mask.view(batch_size, max_len, 1, 1).expand_as(crf_scores)).view(-1,target_size * target_size).contiguous() 139 | 140 | golden_scores = flatten_scores.gather(dim=1, index=targets.unsqueeze(1)).sum() 141 | 142 | # 计算golden_scores方法2:利用pack_padded_sequence函数 143 | # targets[targets == end_id] = pad_id 144 | # scores_at_targets = torch.gather( 145 | # crf_scores.view(batch_size, max_len, -1), 2, targets.unsqueeze(2)).squeeze(2) 146 | # scores_at_targets, _ = pack_padded_sequence( 147 | # scores_at_targets, lengths-1, batch_first=True 148 | # ) 149 | # golden_scores = scores_at_targets.sum() 150 | 151 | # 计算all path scores 152 | # scores_upto_t[i, j]表示第i个句子的第t个词被标注为j标记的所有t时刻事前的所有子路径的分数之和 153 | scores_upto_t = torch.zeros(batch_size, target_size).to(device) 154 | for t in range(max_len): 155 | # 当前时刻 有效的batch_size(因为有些序列比较短) 156 | batch_size_t = (lengths > t).sum().item() 157 | if t == 0: 158 | scores_upto_t[:batch_size_t] = crf_scores[:batch_size_t,t, start_id, :] 159 | else: 160 | # We add scores at current timestep to scores accumulated up to previous 161 | # timestep, and log-sum-exp Remember, the cur_tag of the previous 162 | # timestep is the prev_tag of this timestep 163 | # So, broadcast prev. timestep's cur_tag scores 164 | # along cur. timestep's cur_tag dimension 165 | scores_upto_t[:batch_size_t] = torch.logsumexp( 166 | crf_scores[:batch_size_t, t, :, :] + 167 | scores_upto_t[:batch_size_t].unsqueeze(2), 168 | dim=1 169 | ) 170 | all_path_scores = scores_upto_t[:, end_id].sum() 171 | 172 | # 训练大约两个epoch loss变成负数,从数学的角度上来说,loss = -logP 173 | loss = (all_path_scores - golden_scores) / batch_size 174 | return loss 175 | 176 | def indexed(self,targets, tagset_size, start_id): 177 | """将targets中的数转化为在[T*T]大小序列中的索引,T是标注的种类""" 178 | batch_size, max_len = targets.size() 179 | for col in range(max_len - 1, 0, -1): 180 | targets[:, col] += (targets[:, col - 1] * tagset_size) 181 | targets[:, 0] += (start_id * tagset_size) 182 | return targets 183 | 184 | def forward(self,batch_data,batch_tag=None): 185 | embedding = self.embedding(batch_data) 186 | out,_ = self.lstm(embedding) 187 | 188 | emission = self.classifier(out) 189 | batch_size, max_len, out_size = emission.size() 190 | 191 | crf_scores = emission.unsqueeze(2).expand(-1, -1, out_size, -1) + self.transition 192 | 193 | if batch_tag is not None: 194 | loss = self.cal_lstm_crf_loss(crf_scores,batch_tag) 195 | return loss 196 | else: 197 | return crf_scores 198 | 199 | def test(self, test_sents_tensor, lengths): 200 | """使用维特比算法进行解码""" 201 | global tag_2_index 202 | start_id = tag_2_index[''] 203 | end_id = tag_2_index[''] 204 | pad = tag_2_index[''] 205 | tagset_size = len(tag_2_index) 206 | 207 | crf_scores = self.forward(test_sents_tensor) 208 | device = crf_scores.device 209 | # B:batch_size, L:max_len, T:target set size 210 | B, L, T, _ = crf_scores.size() 211 | # viterbi[i, j, k]表示第i个句子,第j个字对应第k个标记的最大分数 212 | viterbi = torch.zeros(B, L, T).to(device) 213 | # backpointer[i, j, k]表示第i个句子,第j个字对应第k个标记时前一个标记的id,用于回溯 214 | backpointer = (torch.zeros(B, L, T).long() * end_id).to(device) 215 | lengths = torch.LongTensor(lengths).to(device) 216 | # 向前递推 217 | for step in range(L): 218 | batch_size_t = (lengths > step).sum().item() 219 | if step == 0: 220 | # 第一个字它的前一个标记只能是start_id 221 | viterbi[:batch_size_t, step, 222 | :] = crf_scores[: batch_size_t, step, start_id, :] 223 | backpointer[: batch_size_t, step, :] = start_id 224 | else: 225 | max_scores, prev_tags = torch.max( 226 | viterbi[:batch_size_t, step-1, :].unsqueeze(2) + 227 | crf_scores[:batch_size_t, step, :, :], # [B, T, T] 228 | dim=1 229 | ) 230 | viterbi[:batch_size_t, step, :] = max_scores 231 | backpointer[:batch_size_t, step, :] = prev_tags 232 | 233 | # 在回溯的时候我们只需要用到backpointer矩阵 234 | backpointer = backpointer.view(B, -1) # [B, L * T] 235 | tagids = [] # 存放结果 236 | tags_t = None 237 | for step in range(L-1, 0, -1): 238 | batch_size_t = (lengths > step).sum().item() 239 | if step == L-1: 240 | index = torch.ones(batch_size_t).long() * (step * tagset_size) 241 | index = index.to(device) 242 | index += end_id 243 | else: 244 | prev_batch_size_t = len(tags_t) 245 | 246 | new_in_batch = torch.LongTensor( 247 | [end_id] * (batch_size_t - prev_batch_size_t)).to(device) 248 | offset = torch.cat( 249 | [tags_t, new_in_batch], 250 | dim=0 251 | ) # 这个offset实际上就是前一时刻的 252 | index = torch.ones(batch_size_t).long() * (step * tagset_size) 253 | index = index.to(device) 254 | index += offset.long() 255 | 256 | try: 257 | tags_t = backpointer[:batch_size_t].gather( 258 | dim=1, index=index.unsqueeze(1).long()) 259 | except RuntimeError: 260 | import pdb 261 | pdb.set_trace() 262 | tags_t = tags_t.squeeze(1) 263 | tagids.append(tags_t.tolist()) 264 | 265 | tagids = list(zip_longest(*reversed(tagids), fillvalue=pad)) 266 | tagids = torch.Tensor(tagids).long() 267 | 268 | # 返回解码的结果 269 | return tagids.reshape(-1) 270 | 271 | def test(): 272 | global word_2_index,model,index_2_tag,device 273 | while True: 274 | text = input("请输入:") 275 | text_index = [[word_2_index.get(i,word_2_index[""]) for i in text] + [word_2_index[""]]] 276 | 277 | text_index = torch.tensor(text_index,dtype=torch.int64,device=device) 278 | pre = model.test(text_index,[len(text)+1]) 279 | pre = [index_2_tag[i] for i in pre] 280 | print([f'{w}_{s}' for w,s in zip(text,pre)]) 281 | 282 | 283 | 284 | 285 | if __name__ == "__main__": 286 | device = "cuda:0" if torch.cuda.is_available() else "cpu" 287 | 288 | train_data,train_tag,word_2_index,tag_2_index = build_corpus("train",make_vocab=True) 289 | dev_data,dev_tag = build_corpus("dev",make_vocab=False) 290 | index_2_tag = [i for i in tag_2_index] 291 | 292 | corpus_num = len(word_2_index) 293 | class_num = len(tag_2_index) 294 | 295 | epoch = 15 296 | train_batch_size = 30 297 | dev_batch_size = 100 298 | embedding_num = 101 299 | hidden_num = 107 300 | bi = True 301 | lr = 0.001 302 | 303 | train_dataset = MyDataset(train_data,train_tag,word_2_index,tag_2_index) 304 | train_dataloader = DataLoader(train_dataset,train_batch_size,shuffle=False,collate_fn=train_dataset.pro_batch_data) 305 | 306 | dev_dataset = MyDataset(dev_data, dev_tag, word_2_index, tag_2_index) 307 | dev_dataloader = DataLoader(dev_dataset, dev_batch_size, shuffle=False,collate_fn=dev_dataset.pro_batch_data) 308 | 309 | model = Mymodel(corpus_num,embedding_num,hidden_num,class_num,bi) 310 | opt = torch.optim.AdamW(model.parameters(),lr = lr) 311 | model = model.to(device) 312 | 313 | for e in range(epoch): 314 | model.train() 315 | for batch_data,batch_tag,batch_len in train_dataloader: 316 | train_loss = model.forward(batch_data,batch_tag) 317 | train_loss.backward() 318 | opt.step() 319 | opt.zero_grad() 320 | # print(f"train_loss:{train_loss:.3f}") 321 | model.eval() 322 | all_pre = [] 323 | all_tag = [] 324 | for dev_batch_data,dev_batch_tag,batch_len in dev_dataloader: 325 | pre_tag = model.test(dev_batch_data,batch_len) 326 | all_pre.extend(pre_tag.detach().cpu().numpy().tolist()) 327 | all_tag.extend(dev_batch_tag[:,:-1].detach().cpu().numpy().reshape(-1).tolist()) 328 | score = f1_score(all_tag,all_pre,average="micro") 329 | print(f"{e},f1_score:{score:.3f},train_loss:{train_loss:.3f}") 330 | test() 331 | --------------------------------------------------------------------------------