├── floyd_requirements.txt ├── Dockerfile ├── app.py ├── .gitignore ├── README.md ├── data_helpers.py ├── eval.py ├── serve.py ├── text_cnn.py ├── train.py ├── cnn-train.py └── LICENSE /floyd_requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tensorflow/tensorflow:0.11.0rc2 2 | 3 | MAINTAINER Floyd 4 | 5 | RUN pip install scikit-learn 6 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from serve import main, setup 3 | 4 | app = Flask(__name__) 5 | 6 | 7 | @app.route("/") 8 | def evaluate(input): 9 | print("Received input: %s".format(input)) 10 | return str(main([input])) 11 | 12 | 13 | if __name__ == "__main__": 14 | setup(checkpoint_dir="./runs/1486683971/checkpoints/") 15 | app.run(host="0.0.0.0") 16 | -------------------------------------------------------------------------------- /.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 | 71 | .floydexpt 72 | .floydignore 73 | -------------------------------------------------------------------------------- /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.8 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) -------------------------------------------------------------------------------- /data_helpers.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import re 3 | import itertools 4 | from collections import Counter 5 | 6 | 7 | def clean_str(string): 8 | """ 9 | Tokenization/string cleaning for all datasets except for SST. 10 | Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py 11 | """ 12 | string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) 13 | string = re.sub(r"\'s", " \'s", string) 14 | string = re.sub(r"\'ve", " \'ve", string) 15 | string = re.sub(r"n\'t", " n\'t", string) 16 | string = re.sub(r"\'re", " \'re", string) 17 | string = re.sub(r"\'d", " \'d", string) 18 | string = re.sub(r"\'ll", " \'ll", string) 19 | string = re.sub(r",", " , ", string) 20 | string = re.sub(r"!", " ! ", string) 21 | string = re.sub(r"\(", " \( ", string) 22 | string = re.sub(r"\)", " \) ", string) 23 | string = re.sub(r"\?", " \? ", string) 24 | string = re.sub(r"\s{2,}", " ", string) 25 | return string.strip().lower() 26 | 27 | 28 | def load_data_and_labels(): 29 | """ 30 | Loads MR polarity data from files, splits the data into words and generates labels. 31 | Returns split sentences and labels. 32 | """ 33 | # Load data from files 34 | positive_examples = list(open("./data/rt-polaritydata/rt-polarity.pos", "r").readlines()) 35 | positive_examples = [s.strip() for s in positive_examples] 36 | negative_examples = list(open("./data/rt-polaritydata/rt-polarity.neg", "r").readlines()) 37 | negative_examples = [s.strip() for s in negative_examples] 38 | # Split by words 39 | x_text = positive_examples + negative_examples 40 | x_text = [clean_str(sent) for sent in x_text] 41 | # Generate labels 42 | positive_labels = [[0, 1] for _ in positive_examples] 43 | negative_labels = [[1, 0] for _ in negative_examples] 44 | y = np.concatenate([positive_labels, negative_labels], 0) 45 | return [x_text, y] 46 | 47 | 48 | def batch_iter(data, batch_size, num_epochs, shuffle=True): 49 | """ 50 | Generates a batch iterator for a dataset. 51 | """ 52 | data = np.array(data) 53 | data_size = len(data) 54 | num_batches_per_epoch = int(len(data)/batch_size) + 1 55 | for epoch in range(num_epochs): 56 | # Shuffle the data at each epoch 57 | if shuffle: 58 | shuffle_indices = np.random.permutation(np.arange(data_size)) 59 | shuffled_data = data[shuffle_indices] 60 | else: 61 | shuffled_data = data 62 | for batch_num in range(num_batches_per_epoch): 63 | start_index = batch_num * batch_size 64 | end_index = min((batch_num + 1) * batch_size, data_size) 65 | yield shuffled_data[start_index:end_index] 66 | -------------------------------------------------------------------------------- /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 | 12 | # Parameters 13 | # ================================================== 14 | 15 | # Eval Parameters 16 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 17 | tf.flags.DEFINE_string("checkpoint_dir", "", "Checkpoint directory from training run") 18 | tf.flags.DEFINE_boolean("eval_train", False, "Evaluate on all training data") 19 | 20 | # Misc Parameters 21 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 22 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 23 | 24 | 25 | FLAGS = tf.flags.FLAGS 26 | FLAGS._parse_flags() 27 | print("\nParameters:") 28 | for attr, value in sorted(FLAGS.__flags.items()): 29 | print("{}={}".format(attr.upper(), value)) 30 | print("") 31 | 32 | # CHANGE THIS: Load data. Load your own data here 33 | if FLAGS.eval_train: 34 | x_raw, y_test = data_helpers.load_data_and_labels() 35 | y_test = np.argmax(y_test, axis=1) 36 | else: 37 | x_raw = ["a masterpiece four years in the making", "everything is off."] 38 | y_test = [1, 0] 39 | 40 | # Map data into vocabulary 41 | vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab") 42 | vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) 43 | x_test = np.array(list(vocab_processor.transform(x_raw))) 44 | 45 | print("\nEvaluating...\n") 46 | 47 | # Evaluation 48 | # ================================================== 49 | checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) 50 | graph = tf.Graph() 51 | with graph.as_default(): 52 | session_conf = tf.ConfigProto( 53 | allow_soft_placement=FLAGS.allow_soft_placement, 54 | log_device_placement=FLAGS.log_device_placement) 55 | sess = tf.Session(config=session_conf) 56 | with sess.as_default(): 57 | # Load the saved meta graph and restore variables 58 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 59 | saver.restore(sess, checkpoint_file) 60 | 61 | # Get the placeholders from the graph by name 62 | input_x = graph.get_operation_by_name("input_x").outputs[0] 63 | # input_y = graph.get_operation_by_name("input_y").outputs[0] 64 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 65 | 66 | # Tensors we want to evaluate 67 | predictions = graph.get_operation_by_name("output/predictions").outputs[0] 68 | 69 | # Generate batches for one epoch 70 | batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False) 71 | 72 | # Collect the predictions here 73 | all_predictions = [] 74 | 75 | for x_test_batch in batches: 76 | batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0}) 77 | all_predictions = np.concatenate([all_predictions, batch_predictions]) 78 | 79 | # Print accuracy if y_test is defined 80 | if y_test is not None: 81 | correct_predictions = float(sum(all_predictions == y_test)) 82 | print("Total number of test examples: {}".format(len(y_test))) 83 | print("Accuracy: {:g}".format(correct_predictions/float(len(y_test)))) 84 | -------------------------------------------------------------------------------- /serve.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import tensorflow as tf 4 | import numpy as np 5 | import os 6 | import data_helpers 7 | from tensorflow.contrib import learn 8 | 9 | 10 | def setup(checkpoint_dir=""): 11 | # Parameters 12 | # ================================================== 13 | 14 | # Data Parameters 15 | tf.flags.DEFINE_string("positive_data_file", 16 | "./data/rt-polaritydata/rt-polarity.pos", 17 | "Data source for the positive data.") 18 | tf.flags.DEFINE_string("negative_data_file", 19 | "./data/rt-polaritydata/rt-polarity.neg", 20 | "Data source for the positive data.") 21 | 22 | # Eval Parameters 23 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 24 | tf.flags.DEFINE_string("checkpoint_dir", checkpoint_dir, "Checkpoint directory from training run") 25 | tf.flags.DEFINE_boolean("eval_train", False, "Evaluate on all training data") 26 | 27 | # Misc Parameters 28 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 29 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 30 | 31 | 32 | def main(input_str): 33 | x_raw = input_str 34 | 35 | FLAGS = tf.flags.FLAGS 36 | FLAGS._parse_flags() 37 | print("\nParameters:") 38 | for attr, value in sorted(FLAGS.__flags.items()): 39 | print("{}={}".format(attr.upper(), value)) 40 | print("") 41 | 42 | # Map data into vocabulary 43 | vocab_path = os.path.join(FLAGS.checkpoint_dir, "..", "vocab") 44 | vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) 45 | x_test = np.array(list(vocab_processor.transform(x_raw))) 46 | 47 | print("\nEvaluating...\n") 48 | 49 | # Evaluation 50 | # ================================================== 51 | checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir) 52 | graph = tf.Graph() 53 | with graph.as_default(): 54 | session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.allow_soft_placement, 55 | log_device_placement=FLAGS.log_device_placement) 56 | sess = tf.Session(config=session_conf) 57 | with sess.as_default(): 58 | # Load the saved meta graph and restore variables 59 | saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file)) 60 | saver.restore(sess, checkpoint_file) 61 | 62 | # Get the placeholders from the graph by name 63 | input_x = graph.get_operation_by_name("input_x").outputs[0] 64 | # input_y = graph.get_operation_by_name("input_y").outputs[0] 65 | dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] 66 | 67 | # Tensors we want to evaluate 68 | predictions = graph.get_operation_by_name("output/predictions").outputs[0] 69 | 70 | # Generate batches for one epoch 71 | batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False) 72 | 73 | # Collect the predictions here 74 | all_predictions = [] 75 | 76 | for x_test_batch in batches: 77 | batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0}) 78 | all_predictions = np.concatenate([all_predictions, batch_predictions]) 79 | 80 | # Save the evaluation to a csv 81 | predictions_human_readable = np.column_stack((np.array(x_raw), all_predictions)) 82 | return predictions_human_readable 83 | 84 | if __name__ == "__main__": 85 | input_str = ["a masterpiece four years in the making", "everything is off."] 86 | setup() 87 | output = main(input_str) 88 | print(output) 89 | -------------------------------------------------------------------------------- /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 | 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(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(3, pooled_outputs) 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 | # CalculateMean cross-entropy loss 77 | with tf.name_scope("loss"): 78 | losses = tf.nn.softmax_cross_entropy_with_logits(self.scores, 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 | # Model Hyperparameters 16 | tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)") 17 | tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')") 18 | tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)") 19 | tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") 20 | tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularizaion lambda (default: 0.0)") 21 | 22 | # Training parameters 23 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 24 | tf.flags.DEFINE_integer("num_epochs", 200, "Number of training epochs (default: 200)") 25 | tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)") 26 | tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)") 27 | # Misc Parameters 28 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 29 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 30 | 31 | FLAGS = tf.flags.FLAGS 32 | FLAGS._parse_flags() 33 | print("\nParameters:") 34 | for attr, value in sorted(FLAGS.__flags.items()): 35 | print("{}={}".format(attr.upper(), value)) 36 | print("") 37 | 38 | 39 | # Data Preparatopn 40 | # ================================================== 41 | 42 | # Load data 43 | print("Loading data...") 44 | x_text, y = data_helpers.load_data_and_labels() 45 | 46 | # Build vocabulary 47 | max_document_length = max([len(x.split(" ")) for x in x_text]) 48 | vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) 49 | x = np.array(list(vocab_processor.fit_transform(x_text))) 50 | 51 | # Randomly shuffle data 52 | np.random.seed(10) 53 | shuffle_indices = np.random.permutation(np.arange(len(y))) 54 | x_shuffled = x[shuffle_indices] 55 | y_shuffled = y[shuffle_indices] 56 | 57 | # Split train/test set 58 | # TODO: This is very crude, should use cross-validation 59 | x_train, x_dev = x_shuffled[:-1000], x_shuffled[-1000:] 60 | y_train, y_dev = y_shuffled[:-1000], y_shuffled[-1000:] 61 | print("Vocabulary Size: {:d}".format(len(vocab_processor.vocabulary_))) 62 | print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev))) 63 | 64 | 65 | # Training 66 | # ================================================== 67 | 68 | with tf.Graph().as_default(): 69 | session_conf = tf.ConfigProto( 70 | allow_soft_placement=FLAGS.allow_soft_placement, 71 | log_device_placement=FLAGS.log_device_placement) 72 | sess = tf.Session(config=session_conf) 73 | with sess.as_default(): 74 | cnn = TextCNN( 75 | sequence_length=x_train.shape[1], 76 | num_classes=y_train.shape[1], 77 | vocab_size=len(vocab_processor.vocabulary_), 78 | embedding_size=FLAGS.embedding_dim, 79 | filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), 80 | num_filters=FLAGS.num_filters, 81 | l2_reg_lambda=FLAGS.l2_reg_lambda) 82 | 83 | # Define Training procedure 84 | global_step = tf.Variable(0, name="global_step", trainable=False) 85 | optimizer = tf.train.AdamOptimizer(1e-3) 86 | grads_and_vars = optimizer.compute_gradients(cnn.loss) 87 | train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) 88 | 89 | # Keep track of gradient values and sparsity (optional) 90 | grad_summaries = [] 91 | for g, v in grads_and_vars: 92 | if g is not None: 93 | grad_hist_summary = tf.histogram_summary("{}/grad/hist".format(v.name), g) 94 | sparsity_summary = tf.scalar_summary("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) 95 | grad_summaries.append(grad_hist_summary) 96 | grad_summaries.append(sparsity_summary) 97 | grad_summaries_merged = tf.merge_summary(grad_summaries) 98 | 99 | # Output directory for models and summaries 100 | timestamp = str(int(time.time())) 101 | out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) 102 | print("Writing to {}\n".format(out_dir)) 103 | 104 | # Summaries for loss and accuracy 105 | loss_summary = tf.scalar_summary("loss", cnn.loss) 106 | acc_summary = tf.scalar_summary("accuracy", cnn.accuracy) 107 | 108 | # Train Summaries 109 | train_summary_op = tf.merge_summary([loss_summary, acc_summary, grad_summaries_merged]) 110 | train_summary_dir = os.path.join(out_dir, "summaries", "train") 111 | train_summary_writer = tf.train.SummaryWriter(train_summary_dir, sess.graph) 112 | 113 | # Dev summaries 114 | dev_summary_op = tf.merge_summary([loss_summary, acc_summary]) 115 | dev_summary_dir = os.path.join(out_dir, "summaries", "dev") 116 | dev_summary_writer = tf.train.SummaryWriter(dev_summary_dir, sess.graph) 117 | 118 | # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it 119 | checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) 120 | checkpoint_prefix = os.path.join(checkpoint_dir, "model") 121 | if not os.path.exists(checkpoint_dir): 122 | os.makedirs(checkpoint_dir) 123 | saver = tf.train.Saver(tf.all_variables()) 124 | 125 | # Write vocabulary 126 | vocab_processor.save(os.path.join(out_dir, "vocab")) 127 | 128 | # Initialize all variables 129 | sess.run(tf.initialize_all_variables()) 130 | 131 | def train_step(x_batch, y_batch): 132 | """ 133 | A single training step 134 | """ 135 | feed_dict = { 136 | cnn.input_x: x_batch, 137 | cnn.input_y: y_batch, 138 | cnn.dropout_keep_prob: FLAGS.dropout_keep_prob 139 | } 140 | _, step, summaries, loss, accuracy = sess.run( 141 | [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], 142 | feed_dict) 143 | time_str = datetime.datetime.now().isoformat() 144 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 145 | train_summary_writer.add_summary(summaries, step) 146 | 147 | def dev_step(x_batch, y_batch, writer=None): 148 | """ 149 | Evaluates model on a dev set 150 | """ 151 | feed_dict = { 152 | cnn.input_x: x_batch, 153 | cnn.input_y: y_batch, 154 | cnn.dropout_keep_prob: 1.0 155 | } 156 | step, summaries, loss, accuracy = sess.run( 157 | [global_step, dev_summary_op, cnn.loss, cnn.accuracy], 158 | feed_dict) 159 | time_str = datetime.datetime.now().isoformat() 160 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 161 | if writer: 162 | writer.add_summary(summaries, step) 163 | 164 | # Generate batches 165 | batches = data_helpers.batch_iter( 166 | list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) 167 | # Training loop. For each batch... 168 | for batch in batches: 169 | x_batch, y_batch = zip(*batch) 170 | train_step(x_batch, y_batch) 171 | current_step = tf.train.global_step(sess, global_step) 172 | if current_step % FLAGS.evaluate_every == 0: 173 | print("\nEvaluation:") 174 | dev_step(x_dev, y_dev, writer=dev_summary_writer) 175 | print("") 176 | if current_step % FLAGS.checkpoint_every == 0: 177 | path = saver.save(sess, checkpoint_prefix, global_step=current_step) 178 | print("Saved model checkpoint to {}\n".format(path)) 179 | -------------------------------------------------------------------------------- /cnn-train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import tensorflow as tf 3 | import numpy as np 4 | import os 5 | import time 6 | import datetime 7 | import data_helpers 8 | from text_cnn import TextCNN 9 | from tensorflow.contrib import learn 10 | from sklearn import preprocessing 11 | 12 | class ConsistenLabelBinarizer(preprocessing.LabelBinarizer): 13 | """ 14 | Create a more consistent version of sklearn's LabelBinarizer 15 | 16 | LabelBinarizer returns different values for binary and multiclass cases 17 | See http://stackoverflow.com/questions/31947140/sklearn-labelbinarizer-returns-vector-when-there-are-2-classes 18 | Hence, if the labels are in [0,1], the LabelBinarizer will only 19 | return a single element array for transform, e.g. 0 -> [0] or 1-> [1] 20 | However, if the labels are in [0,1,2], it will return a 3-din array 21 | e.g. 0 -> [1 0 0], 2 -> [0 0 1] 22 | 23 | ConsistentLabelBinarizer fixes the behavior of the binary case to match 24 | multi-class 25 | """ 26 | def transform(self, y): 27 | Y = super(ConsistenLabelBinarizer, self).transform(y) 28 | if self.y_type_ == 'binary': 29 | return np.hstack((Y, 1-Y)) 30 | else: 31 | return Y 32 | 33 | def inverse_transform(self, Y, threshold=None): 34 | if self.y_type_ == 'binary': 35 | return super(ConsistenLabelBinarizer, self).inverse_transform(Y[:, 0], threshold) 36 | else: 37 | return super(ConsistenLabelBinarizer, self).inverse_transform(Y, threshold) 38 | 39 | def load_data(filepath, delimiter, label_classes=None): 40 | """ 41 | Load the training/test data from the provided file 42 | 43 | Input schema expected: Label Word_Id_Vector 44 | 45 | - Converts the Label into a one-vs-all numpy array 46 | - Converts the Word_Id_Vector into numpy array 47 | """ 48 | labels = [] 49 | vectors = [] 50 | 51 | print("Reading data from {}".format(filepath)) 52 | with open(filepath, 'r') as f_train: 53 | for line in f_train: 54 | cols = line.split(delimiter) 55 | 56 | label_str = cols[0] 57 | labels.append(label_str) 58 | 59 | vector_str = cols[1] 60 | vector = map(int, vector_str.split(" ")) 61 | vectors.append(vector) 62 | print("Read {} lines".format(len(labels))) 63 | 64 | # Get the label classes 65 | lb = ConsistenLabelBinarizer() 66 | if label_classes is None: 67 | lb.fit(labels) 68 | label_classes = lb.classes_ 69 | else: 70 | lb.fit(label_classes) 71 | 72 | print("Label classes: {}".format(label_classes)) 73 | 74 | # Transform the multi-class labels into one-vs-all numpy array 75 | labels = lb.transform(labels) 76 | 77 | # Transform the vectors into numpy arary 78 | vectors = np.asarray(vectors) 79 | 80 | return labels, vectors, label_classes 81 | 82 | def main(): 83 | """ 84 | Train a sentence classification CNN model 85 | """ 86 | 87 | # Parse command line args 88 | # ================================================== 89 | parser = argparse.ArgumentParser(description='Train CNN model for text classification') 90 | 91 | parser.add_argument('-tr', '--train', required=True, 92 | help='Path to training data') 93 | parser.add_argument('-ev', '--eval', required=True, 94 | help='Path to evaluation data') 95 | parser.add_argument('-vs', '--vocab_size', required=True, 96 | help='Path to file containing vocab size') 97 | parser.add_argument('-d', '--delimiter', required=True, default='\t', 98 | help='Column delimiter between row and label') 99 | parser.add_argument('-o', '--output_dir', required=True, 100 | help='Path to output checkpoints dir') 101 | parser.add_argument('-os', '--summary_dir', required=True, 102 | help='Path to output summaries dir') 103 | 104 | args, unknown = parser.parse_known_args() 105 | # Unescape the delimiter 106 | args.delimiter = args.delimiter.decode('string_escape') 107 | 108 | # Convert args to dict 109 | vargs = vars(args) 110 | 111 | print("\nArguments:") 112 | for arg in vargs: 113 | print("{}={}".format(arg, getattr(args, arg))) 114 | 115 | # Parameters 116 | # ================================================== 117 | 118 | # Model Hyperparameters 119 | tf.flags.DEFINE_integer("embedding_dim", 128, "Dimensionality of character embedding (default: 128)") 120 | tf.flags.DEFINE_string("filter_sizes", "3,4,5", "Comma-separated filter sizes (default: '3,4,5')") 121 | tf.flags.DEFINE_integer("num_filters", 128, "Number of filters per filter size (default: 128)") 122 | tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") 123 | tf.flags.DEFINE_float("l2_reg_lambda", 0.0, "L2 regularizaion lambda (default: 0.0)") 124 | 125 | # Training parameters 126 | tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)") 127 | tf.flags.DEFINE_integer("num_epochs", 200, "Number of training epochs (default: 200)") 128 | tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)") 129 | tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)") 130 | # Misc Parameters 131 | tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") 132 | tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") 133 | 134 | FLAGS = tf.flags.FLAGS 135 | FLAGS._parse_flags() 136 | print("\nParameters:") 137 | for attr, value in sorted(FLAGS.__flags.items()): 138 | print("{}={}".format(attr.upper(), value)) 139 | print("") 140 | 141 | # Read and load input data 142 | # ================================================== 143 | print("Processing training data") 144 | y_train, x_train, label_classes = load_data(args.train, args.delimiter, label_classes=None) 145 | print("Processing evaluation data") 146 | y_dev, x_dev, dummy = load_data(args.eval, args.delimiter, label_classes=label_classes) 147 | 148 | # Get the vocab size 149 | with open(args.vocab_size, 'r') as f: 150 | vocab_size = int(f.readline()) 151 | 152 | with tf.Graph().as_default(): 153 | session_conf = tf.ConfigProto( 154 | allow_soft_placement=FLAGS.allow_soft_placement, 155 | log_device_placement=FLAGS.log_device_placement) 156 | sess = tf.Session(config=session_conf) 157 | with sess.as_default(): 158 | cnn = TextCNN( 159 | sequence_length=x_train.shape[1], 160 | num_classes=y_train.shape[1], 161 | vocab_size=vocab_size, 162 | embedding_size=FLAGS.embedding_dim, 163 | filter_sizes=list(map(int, FLAGS.filter_sizes.split(","))), 164 | num_filters=FLAGS.num_filters, 165 | l2_reg_lambda=FLAGS.l2_reg_lambda) 166 | 167 | # Define Training procedure 168 | global_step = tf.Variable(0, name="global_step", trainable=False) 169 | optimizer = tf.train.AdamOptimizer(1e-3) 170 | grads_and_vars = optimizer.compute_gradients(cnn.loss) 171 | train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) 172 | 173 | # Keep track of gradient values and sparsity (optional) 174 | grad_summaries = [] 175 | for g, v in grads_and_vars: 176 | if g is not None: 177 | grad_hist_summary = tf.histogram_summary("{}/grad/hist".format(v.name), g) 178 | sparsity_summary = tf.scalar_summary("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) 179 | grad_summaries.append(grad_hist_summary) 180 | grad_summaries.append(sparsity_summary) 181 | grad_summaries_merged = tf.merge_summary(grad_summaries) 182 | 183 | # Summaries for loss and accuracy 184 | loss_summary = tf.scalar_summary("loss", cnn.loss) 185 | acc_summary = tf.scalar_summary("accuracy", cnn.accuracy) 186 | 187 | # Train Summaries 188 | train_summary_op = tf.merge_summary([loss_summary, acc_summary, grad_summaries_merged]) 189 | train_summary_dir = os.path.join(args.summary_dir, "train") 190 | train_summary_writer = tf.train.SummaryWriter(train_summary_dir, sess.graph) 191 | 192 | # Dev summaries 193 | dev_summary_op = tf.merge_summary([loss_summary, acc_summary]) 194 | dev_summary_dir = os.path.join(args.summary_dir, "dev") 195 | dev_summary_writer = tf.train.SummaryWriter(dev_summary_dir, sess.graph) 196 | 197 | # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it 198 | checkpoint_dir = args.output_dir 199 | checkpoint_prefix = os.path.join(checkpoint_dir, "model") 200 | if not os.path.exists(checkpoint_dir): 201 | os.makedirs(checkpoint_dir) 202 | saver = tf.train.Saver(tf.all_variables()) 203 | 204 | # Initialize all variables 205 | sess.run(tf.initialize_all_variables()) 206 | 207 | def train_step(x_batch, y_batch): 208 | """ 209 | A single training step 210 | """ 211 | feed_dict = { 212 | cnn.input_x: x_batch, 213 | cnn.input_y: y_batch, 214 | cnn.dropout_keep_prob: FLAGS.dropout_keep_prob 215 | } 216 | _, step, summaries, loss, accuracy = sess.run( 217 | [train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy], 218 | feed_dict) 219 | time_str = datetime.datetime.now().isoformat() 220 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 221 | train_summary_writer.add_summary(summaries, step) 222 | 223 | def dev_step(x_batch, y_batch, writer=None): 224 | """ 225 | Evaluates model on a dev set 226 | """ 227 | feed_dict = { 228 | cnn.input_x: x_batch, 229 | cnn.input_y: y_batch, 230 | cnn.dropout_keep_prob: 1.0 231 | } 232 | step, summaries, loss, accuracy = sess.run( 233 | [global_step, dev_summary_op, cnn.loss, cnn.accuracy], 234 | feed_dict) 235 | time_str = datetime.datetime.now().isoformat() 236 | print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) 237 | if writer: 238 | writer.add_summary(summaries, step) 239 | 240 | # Generate batches 241 | batches = data_helpers.batch_iter( 242 | list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) 243 | # Training loop. For each batch... 244 | for batch in batches: 245 | x_batch, y_batch = zip(*batch) 246 | train_step(x_batch, y_batch) 247 | current_step = tf.train.global_step(sess, global_step) 248 | if current_step % FLAGS.evaluate_every == 0: 249 | print("\nEvaluation:") 250 | dev_step(x_dev, y_dev, writer=dev_summary_writer) 251 | print("") 252 | if current_step % FLAGS.checkpoint_every == 0: 253 | path = saver.save(sess, checkpoint_prefix, global_step=current_step) 254 | print("Saved model checkpoint to {}\n".format(path)) 255 | 256 | if __name__ == '__main__': 257 | main() -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------