├── .gitignore ├── LICENSE ├── README.md ├── data └── rt-polaritydata │ ├── rt-polarity.neg │ └── rt-polarity.pos ├── data_helpers.py ├── eval.py ├── text_cnn.py └── train.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.npy 2 | runs/ 3 | 4 | # Created by https://www.gitignore.io/api/python,ipythonnotebook 5 | 6 | ### Python ### 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | env/ 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *,cover 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | 60 | # Sphinx documentation 61 | docs/_build/ 62 | 63 | # PyBuilder 64 | target/ 65 | 66 | 67 | ### IPythonNotebook ### 68 | # Temporary data 69 | .ipynb_checkpoints/ 70 | -------------------------------------------------------------------------------- /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 | **[This code belongs to the "Implementing a CNN for Text Classification in Tensorflow" blog post.](http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/)** 2 | 3 | It is slightly simplified implementation of Kim's [Convolutional Neural Networks for Sentence Classification](http://arxiv.org/abs/1408.5882) paper in Tensorflow. 4 | 5 | ## Requirements 6 | 7 | - Python 3 8 | - Tensorflow > 0.12 9 | - Numpy 10 | 11 | ## Training 12 | 13 | Print parameters: 14 | 15 | ```bash 16 | ./train.py --help 17 | ``` 18 | 19 | ``` 20 | optional arguments: 21 | -h, --help show this help message and exit 22 | --embedding_dim EMBEDDING_DIM 23 | Dimensionality of character embedding (default: 128) 24 | --filter_sizes FILTER_SIZES 25 | Comma-separated filter sizes (default: '3,4,5') 26 | --num_filters NUM_FILTERS 27 | Number of filters per filter size (default: 128) 28 | --l2_reg_lambda L2_REG_LAMBDA 29 | L2 regularizaion lambda (default: 0.0) 30 | --dropout_keep_prob DROPOUT_KEEP_PROB 31 | Dropout keep probability (default: 0.5) 32 | --batch_size BATCH_SIZE 33 | Batch Size (default: 64) 34 | --num_epochs NUM_EPOCHS 35 | Number of training epochs (default: 100) 36 | --evaluate_every EVALUATE_EVERY 37 | Evaluate model on dev set after this many steps 38 | (default: 100) 39 | --checkpoint_every CHECKPOINT_EVERY 40 | Save model after this many steps (default: 100) 41 | --allow_soft_placement ALLOW_SOFT_PLACEMENT 42 | Allow device soft device placement 43 | --noallow_soft_placement 44 | --log_device_placement LOG_DEVICE_PLACEMENT 45 | Log placement of ops on devices 46 | --nolog_device_placement 47 | 48 | ``` 49 | 50 | Train: 51 | 52 | ```bash 53 | ./train.py 54 | ``` 55 | 56 | ## Evaluating 57 | 58 | ```bash 59 | ./eval.py --eval_train --checkpoint_dir="./runs/1459637919/checkpoints/" 60 | ``` 61 | 62 | Replace the checkpoint dir with the output from the training. To use your own data, change the `eval.py` script to load your data. 63 | 64 | 65 | ## References 66 | 67 | - [Convolutional Neural Networks for Sentence Classification](http://arxiv.org/abs/1408.5882) 68 | - [A Sensitivity Analysis of (and Practitioners' Guide to) Convolutional Neural Networks for Sentence Classification](http://arxiv.org/abs/1510.03820) 69 | -------------------------------------------------------------------------------- /data_helpers.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import re 3 | 4 | 5 | def clean_str(string): 6 | """ 7 | Tokenization/string cleaning for all datasets except for SST. 8 | Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py 9 | """ 10 | string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) 11 | string = re.sub(r"\'s", " \'s", string) 12 | string = re.sub(r"\'ve", " \'ve", string) 13 | string = re.sub(r"n\'t", " n\'t", string) 14 | string = re.sub(r"\'re", " \'re", string) 15 | string = re.sub(r"\'d", " \'d", string) 16 | string = re.sub(r"\'ll", " \'ll", string) 17 | string = re.sub(r",", " , ", string) 18 | string = re.sub(r"!", " ! ", string) 19 | string = re.sub(r"\(", " \( ", string) 20 | string = re.sub(r"\)", " \) ", string) 21 | string = re.sub(r"\?", " \? ", string) 22 | string = re.sub(r"\s{2,}", " ", string) 23 | return string.strip().lower() 24 | 25 | 26 | def load_data_and_labels(positive_data_file, negative_data_file): 27 | """ 28 | Loads MR polarity data from files, splits the data into words and generates labels. 29 | Returns split sentences and labels. 30 | """ 31 | # Load data from files 32 | positive_examples = list(open(positive_data_file, "r", encoding='utf-8').readlines()) 33 | positive_examples = [s.strip() for s in positive_examples] 34 | negative_examples = list(open(negative_data_file, "r", encoding='utf-8').readlines()) 35 | negative_examples = [s.strip() for s in negative_examples] 36 | # Split by words 37 | x_text = positive_examples + negative_examples 38 | x_text = [clean_str(sent) for sent in x_text] 39 | # Generate labels 40 | positive_labels = [[0, 1] for _ in positive_examples] 41 | negative_labels = [[1, 0] for _ in negative_examples] 42 | y = np.concatenate([positive_labels, negative_labels], 0) 43 | return [x_text, y] 44 | 45 | 46 | def batch_iter(data, batch_size, num_epochs, shuffle=True): 47 | """ 48 | Generates a batch iterator for a dataset. 49 | """ 50 | data = np.array(data) 51 | data_size = len(data) 52 | num_batches_per_epoch = int((len(data)-1)/batch_size) + 1 53 | for epoch in range(num_epochs): 54 | # Shuffle the data at each epoch 55 | if shuffle: 56 | shuffle_indices = np.random.permutation(np.arange(data_size)) 57 | shuffled_data = data[shuffle_indices] 58 | else: 59 | shuffled_data = data 60 | for batch_num in range(num_batches_per_epoch): 61 | start_index = batch_num * batch_size 62 | end_index = min((batch_num + 1) * batch_size, data_size) 63 | yield shuffled_data[start_index:end_index] 64 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | import os 6 | import time 7 | import datetime 8 | import data_helpers 9 | from text_cnn import TextCNN 10 | from tensorflow.contrib import learn 11 | import csv 12 | 13 | # Parameters 14 | # ================================================== 15 | 16 | # Data Parameters 17 | tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.") 18 | tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the negative data.") 19 | 20 | # Eval Parameters 21 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 22 | tf.flags.DEFINE_string("checkpoint_dir", "", "Checkpoint directory from training run") 23 | tf.flags.DEFINE_boolean("eval_train", False, "Evaluate on all training data") 24 | 25 | # Misc Parameters 26 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 27 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 28 | 29 | 30 | FLAGS = tf.flags.FLAGS 31 | FLAGS._parse_flags() 32 | print("\nParameters:") 33 | for attr, value in sorted(FLAGS.__flags.items()): 34 | print("{}={}".format(attr.upper(), value)) 35 | print("") 36 | 37 | # CHANGE THIS: Load data. Load your own data here 38 | if FLAGS.eval_train: 39 | x_raw, y_test = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file) 40 | y_test = np.argmax(y_test, axis=1) 41 | else: 42 | x_raw = ["a masterpiece four years in the making", "everything is off."] 43 | y_test = [1, 0] 44 | 45 | # Map data into vocabulary 46 | vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab") 47 | vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) 48 | x_test = np.array(list(vocab_processor.transform(x_raw))) 49 | 50 | print("\nEvaluating...\n") 51 | 52 | # Evaluation 53 | # ================================================== 54 | checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) 55 | graph = tf.Graph() 56 | with graph.as_default(): 57 | session_conf = tf.ConfigProto( 58 | allow_soft_placement=FLAGS.allow_soft_placement, 59 | log_device_placement=FLAGS.log_device_placement) 60 | sess = tf.Session(config=session_conf) 61 | with sess.as_default(): 62 | # Load the saved meta graph and restore variables 63 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 64 | saver.restore(sess, checkpoint_file) 65 | 66 | # Get the placeholders from the graph by name 67 | input_x = graph.get_operation_by_name("input_x").outputs[0] 68 | # input_y = graph.get_operation_by_name("input_y").outputs[0] 69 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 70 | 71 | # Tensors we want to evaluate 72 | predictions = graph.get_operation_by_name("output/predictions").outputs[0] 73 | 74 | # Generate batches for one epoch 75 | batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False) 76 | 77 | # Collect the predictions here 78 | all_predictions = [] 79 | 80 | for x_test_batch in batches: 81 | batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0}) 82 | all_predictions = np.concatenate([all_predictions, batch_predictions]) 83 | 84 | # Print accuracy if y_test is defined 85 | if y_test is not None: 86 | correct_predictions = float(sum(all_predictions == y_test)) 87 | print("Total number of test examples: {}".format(len(y_test))) 88 | print("Accuracy: {:g}".format(correct_predictions/float(len(y_test)))) 89 | 90 | # Save the evaluation to a csv 91 | predictions_human_readable = np.column_stack((np.array(x_raw), all_predictions)) 92 | out_path = os.path.join(FLAGS.checkpoint_dir, "..", "prediction.csv") 93 | print("Saving evaluation to {0}".format(out_path)) 94 | with open(out_path, 'w') as f: 95 | csv.writer(f).writerows(predictions_human_readable) 96 | -------------------------------------------------------------------------------- /text_cnn.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | 4 | 5 | class TextCNN(object): 6 | """ 7 | A CNN for text classification. 8 | Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. 9 | """ 10 | def __init__( 11 | self, sequence_length, num_classes, vocab_size, 12 | embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0): 13 | 14 | # Placeholders for input, output and dropout 15 | self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x") 16 | self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y") 17 | self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob") 18 | 19 | # Keeping track of l2 regularization loss (optional) 20 | l2_loss = tf.constant(0.0) 21 | 22 | # Embedding layer 23 | with tf.device('/cpu:0'), tf.name_scope("embedding"): 24 | self.W = tf.Variable( 25 | tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), 26 | name="W") 27 | self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x) 28 | self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1) 29 | 30 | # Create a convolution + maxpool layer for each filter size 31 | pooled_outputs = [] 32 | for i, filter_size in enumerate(filter_sizes): 33 | with tf.name_scope("conv-maxpool-%s" % filter_size): 34 | # Convolution Layer 35 | filter_shape = [filter_size, embedding_size, 1, num_filters] 36 | W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") 37 | b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") 38 | conv = tf.nn.conv2d( 39 | self.embedded_chars_expanded, 40 | W, 41 | strides=[1, 1, 1, 1], 42 | padding="VALID", 43 | name="conv") 44 | # Apply nonlinearity 45 | h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu") 46 | # Maxpooling over the outputs 47 | pooled = tf.nn.max_pool( 48 | h, 49 | ksize=[1, sequence_length - filter_size + 1, 1, 1], 50 | strides=[1, 1, 1, 1], 51 | padding='VALID', 52 | name="pool") 53 | pooled_outputs.append(pooled) 54 | 55 | # Combine all the pooled features 56 | num_filters_total = num_filters * len(filter_sizes) 57 | self.h_pool = tf.concat(pooled_outputs, 3) 58 | self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total]) 59 | 60 | # Add dropout 61 | with tf.name_scope("dropout"): 62 | self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob) 63 | 64 | # Final (unnormalized) scores and predictions 65 | with tf.name_scope("output"): 66 | W = tf.get_variable( 67 | "W", 68 | shape=[num_filters_total, num_classes], 69 | initializer=tf.contrib.layers.xavier_initializer()) 70 | b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b") 71 | l2_loss += tf.nn.l2_loss(W) 72 | l2_loss += tf.nn.l2_loss(b) 73 | self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores") 74 | self.predictions = tf.argmax(self.scores, 1, name="predictions") 75 | 76 | # Calculate mean cross-entropy loss 77 | with tf.name_scope("loss"): 78 | losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y) 79 | self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss 80 | 81 | # Accuracy 82 | with tf.name_scope("accuracy"): 83 | correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1)) 84 | self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy") 85 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | import os 6 | import time 7 | import datetime 8 | import data_helpers 9 | from text_cnn import TextCNN 10 | from tensorflow.contrib import learn 11 | 12 | # Parameters 13 | # ================================================== 14 | 15 | # Data loading params 16 | tf.flags.DEFINE_float("dev_sample_percentage", .1, "Percentage of the training data to use for validation") 17 | tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-polarity.pos", "Data source for the positive data.") 18 | tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the negative data.") 19 | 20 | # Model Hyperparameters 21 | tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)") 22 | tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')") 23 | tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)") 24 | tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") 25 | tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularization lambda (default: 0.0)") 26 | 27 | # Training parameters 28 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 29 | tf.flags.DEFINE_integer("num_epochs", 200, "Number of training epochs (default: 200)") 30 | tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)") 31 | tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)") 32 | tf.flags.DEFINE_integer("num_checkpoints", 5, "Number of checkpoints to store (default: 5)") 33 | # Misc Parameters 34 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 35 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 36 | 37 | FLAGS = tf.flags.FLAGS 38 | # FLAGS._parse_flags() 39 | # print("\nParameters:") 40 | # for attr, value in sorted(FLAGS.__flags.items()): 41 | # print("{}={}".format(attr.upper(), value)) 42 | # print("") 43 | 44 | def preprocess(): 45 | # Data Preparation 46 | # ================================================== 47 | 48 | # Load data 49 | print("Loading data...") 50 | x_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file) 51 | 52 | # Build vocabulary 53 | max_document_length = max([len(x.split(" ")) for x in x_text]) 54 | vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) 55 | x = np.array(list(vocab_processor.fit_transform(x_text))) 56 | 57 | # Randomly shuffle data 58 | np.random.seed(10) 59 | shuffle_indices = np.random.permutation(np.arange(len(y))) 60 | x_shuffled = x[shuffle_indices] 61 | y_shuffled = y[shuffle_indices] 62 | 63 | # Split train/test set 64 | # TODO: This is very crude, should use cross-validation 65 | dev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y))) 66 | x_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:] 67 | y_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:] 68 | 69 | del x, y, x_shuffled, y_shuffled 70 | 71 | print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_))) 72 | print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) 73 | return x_train, y_train, vocab_processor, x_dev, y_dev 74 | 75 | def train(x_train, y_train, vocab_processor, x_dev, y_dev): 76 | # Training 77 | # ================================================== 78 | 79 | with tf.Graph().as_default(): 80 | session_conf = tf.ConfigProto( 81 | allow_soft_placement=FLAGS.allow_soft_placement, 82 | log_device_placement=FLAGS.log_device_placement) 83 | sess = tf.Session(config=session_conf) 84 | with sess.as_default(): 85 | cnn = TextCNN( 86 | sequence_length=x_train.shape[1], 87 | num_classes=y_train.shape[1], 88 | vocab_size=len(vocab_processor.vocabulary_), 89 | embedding_size=FLAGS.embedding_dim, 90 | filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), 91 | num_filters=FLAGS.num_filters, 92 | l2_reg_lambda=FLAGS.l2_reg_lambda) 93 | 94 | # Define Training procedure 95 | global_step = tf.Variable(0, name="global_step", trainable=False) 96 | optimizer = tf.train.AdamOptimizer(1e-3) 97 | grads_and_vars = optimizer.compute_gradients(cnn.loss) 98 | train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) 99 | 100 | # Keep track of gradient values and sparsity (optional) 101 | grad_summaries = [] 102 | for g, v in grads_and_vars: 103 | if g is not None: 104 | grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g) 105 | sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) 106 | grad_summaries.append(grad_hist_summary) 107 | grad_summaries.append(sparsity_summary) 108 | grad_summaries_merged = tf.summary.merge(grad_summaries) 109 | 110 | # Output directory for models and summaries 111 | timestamp = str(int(time.time())) 112 | out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) 113 | print("Writing to {}\n".format(out_dir)) 114 | 115 | # Summaries for loss and accuracy 116 | loss_summary = tf.summary.scalar("loss", cnn.loss) 117 | acc_summary = tf.summary.scalar("accuracy", cnn.accuracy) 118 | 119 | # Train Summaries 120 | train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) 121 | train_summary_dir = os.path.join(out_dir, "summaries", "train") 122 | train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) 123 | 124 | # Dev summaries 125 | dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) 126 | dev_summary_dir = os.path.join(out_dir, "summaries", "dev") 127 | dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) 128 | 129 | # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it 130 | checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) 131 | checkpoint_prefix = os.path.join(checkpoint_dir, "model") 132 | if not os.path.exists(checkpoint_dir): 133 | os.makedirs(checkpoint_dir) 134 | saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) 135 | 136 | # Write vocabulary 137 | vocab_processor.save(os.path.join(out_dir, "vocab")) 138 | 139 | # Initialize all variables 140 | sess.run(tf.global_variables_initializer()) 141 | 142 | def train_step(x_batch, y_batch): 143 | """ 144 | A single training step 145 | """ 146 | feed_dict = { 147 | cnn.input_x: x_batch, 148 | cnn.input_y: y_batch, 149 | cnn.dropout_keep_prob: FLAGS.dropout_keep_prob 150 | } 151 | _, step, summaries, loss, accuracy = sess.run( 152 | [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], 153 | feed_dict) 154 | time_str = datetime.datetime.now().isoformat() 155 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 156 | train_summary_writer.add_summary(summaries, step) 157 | 158 | def dev_step(x_batch, y_batch, writer=None): 159 | """ 160 | Evaluates model on a dev set 161 | """ 162 | feed_dict = { 163 | cnn.input_x: x_batch, 164 | cnn.input_y: y_batch, 165 | cnn.dropout_keep_prob: 1.0 166 | } 167 | step, summaries, loss, accuracy = sess.run( 168 | [global_step, dev_summary_op, cnn.loss, cnn.accuracy], 169 | feed_dict) 170 | time_str = datetime.datetime.now().isoformat() 171 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 172 | if writer: 173 | writer.add_summary(summaries, step) 174 | 175 | # Generate batches 176 | batches = data_helpers.batch_iter( 177 | list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) 178 | # Training loop. For each batch... 179 | for batch in batches: 180 | x_batch, y_batch = zip(*batch) 181 | train_step(x_batch, y_batch) 182 | current_step = tf.train.global_step(sess, global_step) 183 | if current_step % FLAGS.evaluate_every == 0: 184 | print("\nEvaluation:") 185 | dev_step(x_dev, y_dev, writer=dev_summary_writer) 186 | print("") 187 | if current_step % FLAGS.checkpoint_every == 0: 188 | path = saver.save(sess, checkpoint_prefix, global_step=current_step) 189 | print("Saved model checkpoint to {}\n".format(path)) 190 | 191 | def main(argv=None): 192 | x_train, y_train, vocab_processor, x_dev, y_dev = preprocess() 193 | train(x_train, y_train, vocab_processor, x_dev, y_dev) 194 | 195 | if __name__ == '__main__': 196 | tf.app.run() --------------------------------------------------------------------------------