├── .gitignore ├── LICENSE ├── README.md ├── main.py ├── model.py ├── mydatasets.py └── train.py /.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 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Mac 92 | .DS_Store 93 | 94 | # model cache 95 | *.pt 96 | 97 | # dataset 98 | rt-polaritydata 99 | trees 100 | *.tar 101 | *.zip 102 | 103 | # pycharm 104 | .idea 105 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Introduction 2 | This is the implementation of Kim's [Convolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1408.5882) paper in PyTorch. 3 | 4 | 1. Kim's implementation of the model in Theano: 5 | [https://github.com/yoonkim/CNN_sentence](https://github.com/yoonkim/CNN_sentence) 6 | 2. Denny Britz has an implementation in Tensorflow: 7 | [https://github.com/dennybritz/cnn-text-classification-tf](https://github.com/dennybritz/cnn-text-classification-tf) 8 | 3. Alexander Rakhlin's implementation in Keras; 9 | [https://github.com/alexander-rakhlin/CNN-for-Sentence-Classification-in-Keras](https://github.com/alexander-rakhlin/CNN-for-Sentence-Classification-in-Keras) 10 | 11 | ## Requirement 12 | * python 3 13 | * pytorch > 0.1 14 | * torchtext > 0.1 15 | * numpy 16 | 17 | ## Result 18 | I just tried two dataset, MR and SST. 19 | 20 | |Dataset|Class Size|Best Result|Kim's Paper Result| 21 | |---|---|---|---| 22 | |MR|2|77.5%(CNN-rand-static)|76.1%(CNN-rand-nostatic)| 23 | |SST|5|37.2%(CNN-rand-static)|45.0%(CNN-rand-nostatic)| 24 | 25 | I haven't adjusted the hyper-parameters for SST seriously. 26 | 27 | ## Usage 28 | ``` 29 | ./main.py -h 30 | ``` 31 | or 32 | 33 | ``` 34 | python3 main.py -h 35 | ``` 36 | 37 | You will get: 38 | 39 | ``` 40 | CNN text classificer 41 | 42 | optional arguments: 43 | -h, --help show this help message and exit 44 | -batch-size N batch size for training [default: 50] 45 | -lr LR initial learning rate [default: 0.01] 46 | -epochs N number of epochs for train [default: 10] 47 | -dropout the probability for dropout [default: 0.5] 48 | -max_norm MAX_NORM l2 constraint of parameters 49 | -cpu disable the gpu 50 | -device DEVICE device to use for iterate data 51 | -embed-dim EMBED_DIM 52 | -static fix the embedding 53 | -kernel-sizes KERNEL_SIZES 54 | Comma-separated kernel size to use for convolution 55 | -kernel-num KERNEL_NUM 56 | number of each kind of kernel 57 | -class-num CLASS_NUM number of class 58 | -shuffle shuffle the data every epoch 59 | -num-workers NUM_WORKERS 60 | how many subprocesses to use for data loading 61 | [default: 0] 62 | -log-interval LOG_INTERVAL 63 | how many batches to wait before logging training 64 | status 65 | -test-interval TEST_INTERVAL 66 | how many epochs to wait before testing 67 | -save-interval SAVE_INTERVAL 68 | how many epochs to wait before saving 69 | -predict PREDICT predict the sentence given 70 | -snapshot SNAPSHOT filename of model snapshot [default: None] 71 | -save-dir SAVE_DIR where to save the checkpoint 72 | ``` 73 | 74 | ## Train 75 | ``` 76 | ./main.py 77 | ``` 78 | You will get: 79 | 80 | ``` 81 | Batch[100] - loss: 0.655424 acc: 59.3750% 82 | Evaluation - loss: 0.672396 acc: 57.6923%(615/1066) 83 | ``` 84 | 85 | ## Test 86 | If you has construct you test set, you make testing like: 87 | 88 | ``` 89 | /main.py -test -snapshot="./snapshot/2017-02-11_15-50-53/snapshot_steps1500.pt 90 | ``` 91 | The snapshot option means where your model load from. If you don't assign it, the model will start from scratch. 92 | 93 | ## Predict 94 | * **Example1** 95 | 96 | ``` 97 | ./main.py -predict="Hello my dear , I love you so much ." \ 98 | -snapshot="./snapshot/2017-02-11_15-50-53/snapshot_steps1500.pt" 99 | ``` 100 | You will get: 101 | 102 | ``` 103 | Loading model from [./snapshot/2017-02-11_15-50-53/snapshot_steps1500.pt]... 104 | 105 | [Text] Hello my dear , I love you so much . 106 | [Label] positive 107 | ``` 108 | * **Example2** 109 | 110 | ``` 111 | ./main.py -predict="You just make me so sad and I have to leave you ."\ 112 | -snapshot="./snapshot/2017-02-11_15-50-53/snapshot_steps1500.pt" 113 | ``` 114 | You will get: 115 | 116 | ``` 117 | Loading model from [./snapshot/2017-02-11_15-50-53/snapshot_steps1500.pt]... 118 | 119 | [Text] You just make me so sad and I have to leave you . 120 | [Label] negative 121 | ``` 122 | 123 | Your text must be separated by space, even punctuation.And, your text should longer then the max kernel size. 124 | 125 | ## Reference 126 | * [Convolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1408.5882) 127 | 128 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | import os 3 | import argparse 4 | import datetime 5 | import torch 6 | import torchtext.data as data 7 | import torchtext.datasets as datasets 8 | import model 9 | import train 10 | import mydatasets 11 | 12 | 13 | parser = argparse.ArgumentParser(description='CNN text classificer') 14 | # learning 15 | parser.add_argument('-lr', type=float, default=0.001, help='initial learning rate [default: 0.001]') 16 | parser.add_argument('-epochs', type=int, default=256, help='number of epochs for train [default: 256]') 17 | parser.add_argument('-batch-size', type=int, default=64, help='batch size for training [default: 64]') 18 | parser.add_argument('-log-interval', type=int, default=1, help='how many steps to wait before logging training status [default: 1]') 19 | parser.add_argument('-test-interval', type=int, default=100, help='how many steps to wait before testing [default: 100]') 20 | parser.add_argument('-save-interval', type=int, default=500, help='how many steps to wait before saving [default:500]') 21 | parser.add_argument('-save-dir', type=str, default='snapshot', help='where to save the snapshot') 22 | parser.add_argument('-early-stop', type=int, default=1000, help='iteration numbers to stop without performance increasing') 23 | parser.add_argument('-save-best', type=bool, default=True, help='whether to save when get best performance') 24 | # data 25 | parser.add_argument('-shuffle', action='store_true', default=False, help='shuffle the data every epoch') 26 | # model 27 | parser.add_argument('-dropout', type=float, default=0.5, help='the probability for dropout [default: 0.5]') 28 | parser.add_argument('-max-norm', type=float, default=3.0, help='l2 constraint of parameters [default: 3.0]') 29 | parser.add_argument('-embed-dim', type=int, default=128, help='number of embedding dimension [default: 128]') 30 | parser.add_argument('-kernel-num', type=int, default=100, help='number of each kind of kernel') 31 | parser.add_argument('-kernel-sizes', type=str, default='3,4,5', help='comma-separated kernel size to use for convolution') 32 | parser.add_argument('-static', action='store_true', default=False, help='fix the embedding') 33 | # device 34 | parser.add_argument('-device', type=int, default=-1, help='device to use for iterate data, -1 mean cpu [default: -1]') 35 | parser.add_argument('-no-cuda', action='store_true', default=False, help='disable the gpu') 36 | # option 37 | parser.add_argument('-snapshot', type=str, default=None, help='filename of model snapshot [default: None]') 38 | parser.add_argument('-predict', type=str, default=None, help='predict the sentence given') 39 | parser.add_argument('-test', action='store_true', default=False, help='train or test') 40 | args = parser.parse_args() 41 | 42 | 43 | # load SST dataset 44 | def sst(text_field, label_field, **kargs): 45 | train_data, dev_data, test_data = datasets.SST.splits(text_field, label_field, fine_grained=True) 46 | text_field.build_vocab(train_data, dev_data, test_data) 47 | label_field.build_vocab(train_data, dev_data, test_data) 48 | train_iter, dev_iter, test_iter = data.BucketIterator.splits( 49 | (train_data, dev_data, test_data), 50 | batch_sizes=(args.batch_size, 51 | len(dev_data), 52 | len(test_data)), 53 | **kargs) 54 | return train_iter, dev_iter, test_iter 55 | 56 | 57 | # load MR dataset 58 | def mr(text_field, label_field, **kargs): 59 | train_data, dev_data = mydatasets.MR.splits(text_field, label_field) 60 | text_field.build_vocab(train_data, dev_data) 61 | label_field.build_vocab(train_data, dev_data) 62 | train_iter, dev_iter = data.Iterator.splits( 63 | (train_data, dev_data), 64 | batch_sizes=(args.batch_size, len(dev_data)), 65 | **kargs) 66 | return train_iter, dev_iter 67 | 68 | 69 | # load data 70 | print("\nLoading data...") 71 | text_field = data.Field(lower=True) 72 | label_field = data.Field(sequential=False) 73 | train_iter, dev_iter = mr(text_field, label_field, device=-1, repeat=False) 74 | # train_iter, dev_iter, test_iter = sst(text_field, label_field, device=-1, repeat=False) 75 | 76 | 77 | # update args and print 78 | args.embed_num = len(text_field.vocab) 79 | args.class_num = len(label_field.vocab) - 1 80 | args.cuda = (not args.no_cuda) and torch.cuda.is_available(); del args.no_cuda 81 | args.kernel_sizes = [int(k) for k in args.kernel_sizes.split(',')] 82 | args.save_dir = os.path.join(args.save_dir, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')) 83 | 84 | print("\nParameters:") 85 | for attr, value in sorted(args.__dict__.items()): 86 | print("\t{}={}".format(attr.upper(), value)) 87 | 88 | 89 | # model 90 | cnn = model.CNN_Text(args) 91 | if args.snapshot is not None: 92 | print('\nLoading model from {}...'.format(args.snapshot)) 93 | cnn.load_state_dict(torch.load(args.snapshot)) 94 | 95 | if args.cuda: 96 | torch.cuda.set_device(args.device) 97 | cnn = cnn.cuda() 98 | 99 | 100 | # train or predict 101 | if args.predict is not None: 102 | label = train.predict(args.predict, cnn, text_field, label_field, args.cuda) 103 | print('\n[Text] {}\n[Label] {}\n'.format(args.predict, label)) 104 | elif args.test: 105 | try: 106 | train.eval(test_iter, cnn, args) 107 | except Exception as e: 108 | print("\nSorry. The test dataset doesn't exist.\n") 109 | else: 110 | print() 111 | try: 112 | train.train(train_iter, dev_iter, cnn, args) 113 | except KeyboardInterrupt: 114 | print('\n' + '-' * 89) 115 | print('Exiting from training early') 116 | 117 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from torch.autograd import Variable 5 | 6 | 7 | class CNN_Text(nn.Module): 8 | 9 | def __init__(self, args): 10 | super(CNN_Text, self).__init__() 11 | self.args = args 12 | 13 | V = args.embed_num 14 | D = args.embed_dim 15 | C = args.class_num 16 | Ci = 1 17 | Co = args.kernel_num 18 | Ks = args.kernel_sizes 19 | 20 | self.embed = nn.Embedding(V, D) 21 | self.convs = nn.ModuleList([nn.Conv2d(Ci, Co, (K, D)) for K in Ks]) 22 | self.dropout = nn.Dropout(args.dropout) 23 | self.fc1 = nn.Linear(len(Ks) * Co, C) 24 | 25 | if self.args.static: 26 | self.embed.weight.requires_grad = False 27 | 28 | def forward(self, x): 29 | x = self.embed(x) # (N, W, D) 30 | 31 | x = x.unsqueeze(1) # (N, Ci, W, D) 32 | 33 | x = [F.relu(conv(x)).squeeze(3) for conv in self.convs] # [(N, Co, W), ...]*len(Ks) 34 | 35 | x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # [(N, Co), ...]*len(Ks) 36 | 37 | x = torch.cat(x, 1) 38 | 39 | x = self.dropout(x) # (N, len(Ks)*Co) 40 | logit = self.fc1(x) # (N, C) 41 | return logit 42 | -------------------------------------------------------------------------------- /mydatasets.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import random 4 | import tarfile 5 | import urllib 6 | from torchtext import data 7 | 8 | 9 | class TarDataset(data.Dataset): 10 | """Defines a Dataset loaded from a downloadable tar archive. 11 | 12 | Attributes: 13 | url: URL where the tar archive can be downloaded. 14 | filename: Filename of the downloaded tar archive. 15 | dirname: Name of the top-level directory within the zip archive that 16 | contains the data files. 17 | """ 18 | 19 | @classmethod 20 | def download_or_unzip(cls, root): 21 | path = os.path.join(root, cls.dirname) 22 | if not os.path.isdir(path): 23 | tpath = os.path.join(root, cls.filename) 24 | if not os.path.isfile(tpath): 25 | print('downloading') 26 | urllib.request.urlretrieve(cls.url, tpath) 27 | with tarfile.open(tpath, 'r') as tfile: 28 | print('extracting') 29 | def is_within_directory(directory, target): 30 | 31 | abs_directory = os.path.abspath(directory) 32 | abs_target = os.path.abspath(target) 33 | 34 | prefix = os.path.commonprefix([abs_directory, abs_target]) 35 | 36 | return prefix == abs_directory 37 | 38 | def safe_extract(tar, path=".", members=None, *, numeric_owner=False): 39 | 40 | for member in tar.getmembers(): 41 | member_path = os.path.join(path, member.name) 42 | if not is_within_directory(path, member_path): 43 | raise Exception("Attempted Path Traversal in Tar File") 44 | 45 | tar.extractall(path, members, numeric_owner=numeric_owner) 46 | 47 | 48 | safe_extract(tfile, root) 49 | return os.path.join(path, '') 50 | 51 | 52 | class MR(TarDataset): 53 | 54 | url = 'https://www.cs.cornell.edu/people/pabo/movie-review-data/rt-polaritydata.tar.gz' 55 | filename = 'rt-polaritydata.tar.gz' 56 | dirname = 'rt-polaritydata' 57 | 58 | @staticmethod 59 | def sort_key(ex): 60 | return len(ex.text) 61 | 62 | def __init__(self, text_field, label_field, path=None, examples=None, **kwargs): 63 | """Create an MR dataset instance given a path and fields. 64 | 65 | Arguments: 66 | text_field: The field that will be used for text data. 67 | label_field: The field that will be used for label data. 68 | path: Path to the data file. 69 | examples: The examples contain all the data. 70 | Remaining keyword arguments: Passed to the constructor of 71 | data.Dataset. 72 | """ 73 | def clean_str(string): 74 | """ 75 | Tokenization/string cleaning for all datasets except for SST. 76 | Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py 77 | """ 78 | string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) 79 | string = re.sub(r"\'s", " \'s", string) 80 | string = re.sub(r"\'ve", " \'ve", string) 81 | string = re.sub(r"n\'t", " n\'t", string) 82 | string = re.sub(r"\'re", " \'re", string) 83 | string = re.sub(r"\'d", " \'d", string) 84 | string = re.sub(r"\'ll", " \'ll", string) 85 | string = re.sub(r",", " , ", string) 86 | string = re.sub(r"!", " ! ", string) 87 | string = re.sub(r"\(", " \( ", string) 88 | string = re.sub(r"\)", " \) ", string) 89 | string = re.sub(r"\?", " \? ", string) 90 | string = re.sub(r"\s{2,}", " ", string) 91 | return string.strip() 92 | 93 | text_field.tokenize = lambda x: clean_str(x).split() 94 | fields = [('text', text_field), ('label', label_field)] 95 | 96 | if examples is None: 97 | path = self.dirname if path is None else path 98 | examples = [] 99 | with open(os.path.join(path, 'rt-polarity.neg'), errors='ignore') as f: 100 | examples += [ 101 | data.Example.fromlist([line, 'negative'], fields) for line in f] 102 | with open(os.path.join(path, 'rt-polarity.pos'), errors='ignore') as f: 103 | examples += [ 104 | data.Example.fromlist([line, 'positive'], fields) for line in f] 105 | super(MR, self).__init__(examples, fields, **kwargs) 106 | 107 | @classmethod 108 | def splits(cls, text_field, label_field, dev_ratio=.1, shuffle=True, root='.', **kwargs): 109 | """Create dataset objects for splits of the MR dataset. 110 | 111 | Arguments: 112 | text_field: The field that will be used for the sentence. 113 | label_field: The field that will be used for label data. 114 | dev_ratio: The ratio that will be used to get split validation dataset. 115 | shuffle: Whether to shuffle the data before split. 116 | root: The root directory that the dataset's zip archive will be 117 | expanded into; therefore the directory in whose trees 118 | subdirectory the data files will be stored. 119 | train: The filename of the train data. Default: 'train.txt'. 120 | Remaining keyword arguments: Passed to the splits method of 121 | Dataset. 122 | """ 123 | path = cls.download_or_unzip(root) 124 | examples = cls(text_field, label_field, path=path, **kwargs).examples 125 | if shuffle: random.shuffle(examples) 126 | dev_index = -1 * int(dev_ratio*len(examples)) 127 | 128 | return (cls(text_field, label_field, examples=examples[:dev_index]), 129 | cls(text_field, label_field, examples=examples[dev_index:])) 130 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import torch 4 | import torch.autograd as autograd 5 | import torch.nn.functional as F 6 | 7 | 8 | def train(train_iter, dev_iter, model, args): 9 | if args.cuda: 10 | model.cuda() 11 | 12 | optimizer = torch.optim.Adam(model.parameters(), lr=args.lr) 13 | 14 | steps = 0 15 | best_acc = 0 16 | last_step = 0 17 | for epoch in range(1, args.epochs+1): 18 | for batch in train_iter: 19 | model.train() 20 | feature, target = batch.text, batch.label 21 | feature.t_(), target.sub_(1) # batch first, index align 22 | if args.cuda: 23 | feature, target = feature.cuda(), target.cuda() 24 | 25 | optimizer.zero_grad() 26 | logit = model(feature) 27 | loss = F.cross_entropy(logit, target) 28 | loss.backward() 29 | optimizer.step() 30 | 31 | steps += 1 32 | if steps % args.log_interval == 0: 33 | corrects = (torch.max(logit, 1)[1].view(target.size()).data == target.data).sum() 34 | accuracy = 100.0 * corrects/batch.batch_size 35 | sys.stdout.write( 36 | '\rBatch[{}] - loss: {:.6f} acc: {:.4f}%({}/{})'.format(steps, 37 | loss.item(), 38 | accuracy.item(), 39 | corrects.item(), 40 | batch.batch_size)) 41 | if steps % args.test_interval == 0: 42 | dev_acc = eval(dev_iter, model, args) 43 | if dev_acc > best_acc: 44 | best_acc = dev_acc 45 | last_step = steps 46 | if args.save_best: 47 | save(model, args.save_dir, 'best', steps) 48 | else: 49 | if steps - last_step >= args.early_stop: 50 | print('early stop by {} steps.'.format(args.early_stop)) 51 | elif steps % args.save_interval == 0: 52 | save(model, args.save_dir, 'snapshot', steps) 53 | 54 | 55 | def eval(data_iter, model, args): 56 | model.eval() 57 | corrects, avg_loss = 0, 0 58 | for batch in data_iter: 59 | feature, target = batch.text, batch.label 60 | feature.t_(), target.sub_(1) # batch first, index align 61 | if args.cuda: 62 | feature, target = feature.cuda(), target.cuda() 63 | 64 | logit = model(feature) 65 | loss = F.cross_entropy(logit, target, size_average=False) 66 | 67 | avg_loss += loss.item() 68 | corrects += (torch.max(logit, 1) 69 | [1].view(target.size()).data == target.data).sum() 70 | 71 | size = len(data_iter.dataset) 72 | avg_loss /= size 73 | accuracy = 100.0 * corrects/size 74 | print('\nEvaluation - loss: {:.6f} acc: {:.4f}%({}/{}) \n'.format(avg_loss, 75 | accuracy, 76 | corrects, 77 | size)) 78 | return accuracy 79 | 80 | 81 | def predict(text, model, text_field, label_feild, cuda_flag): 82 | assert isinstance(text, str) 83 | model.eval() 84 | # text = text_field.tokenize(text) 85 | text = text_field.preprocess(text) 86 | text = [[text_field.vocab.stoi[x] for x in text]] 87 | x = torch.tensor(text) 88 | x = autograd.Variable(x) 89 | if cuda_flag: 90 | x = x.cuda() 91 | print(x) 92 | output = model(x) 93 | _, predicted = torch.max(output, 1) 94 | return label_feild.vocab.itos[predicted.item()+1] 95 | 96 | 97 | def save(model, save_dir, save_prefix, steps): 98 | if not os.path.isdir(save_dir): 99 | os.makedirs(save_dir) 100 | save_prefix = os.path.join(save_dir, save_prefix) 101 | save_path = '{}_steps_{}.pt'.format(save_prefix, steps) 102 | torch.save(model.state_dict(), save_path) 103 | --------------------------------------------------------------------------------