|
| 1 | +import tensorflow as tf |
| 2 | +from tensor2tensor.utils import trainer_lib |
| 3 | +from tensor2tensor import models # pylint: disable=unused-import |
| 4 | +from tensor2tensor import problems # pylint: disable=unused-import |
| 5 | +from tensor2tensor.data_generators import problem_hparams |
| 6 | +from tensor2tensor.utils import registry |
| 7 | +from tensor2tensor.utils import metrics |
| 8 | +from tensor2tensor.data_generators import imdb |
| 9 | +from tensor2tensor.data_generators import text_encoder |
| 10 | + |
| 11 | + |
| 12 | +def create_estimator(run_config, model_config): |
| 13 | + # t2t expects these keys in run_config |
| 14 | + run_config.data_parallelism = None |
| 15 | + run_config.t2t_device_info = {"num_async_replicas": 1} |
| 16 | + |
| 17 | + hparams = trainer_lib.create_hparams("transformer_base_single_gpu") |
| 18 | + |
| 19 | + problem = SentimentIMDBCortex(list(model_config["aggregates"]["reviews_vocab"])) |
| 20 | + p_hparams = problem.get_hparams(hparams) |
| 21 | + hparams.problem = problem |
| 22 | + hparams.problem_hparams = p_hparams |
| 23 | + |
| 24 | + problem.eval_metrics = lambda: [ |
| 25 | + metrics.Metrics.ACC_TOP5, |
| 26 | + metrics.Metrics.ACC_PER_SEQ, |
| 27 | + metrics.Metrics.NEG_LOG_PERPLEXITY, |
| 28 | + ] |
| 29 | + |
| 30 | + # t2t expects this key |
| 31 | + hparams.warm_start_from = None |
| 32 | + |
| 33 | + # reduce memory load |
| 34 | + hparams.num_hidden_layers = 2 |
| 35 | + hparams.hidden_size = 32 |
| 36 | + hparams.filter_size = 32 |
| 37 | + hparams.num_heads = 2 |
| 38 | + |
| 39 | + estimator = trainer_lib.create_estimator("transformer", hparams, run_config) |
| 40 | + return estimator |
| 41 | + |
| 42 | + |
| 43 | +def transform_tensorflow(features, labels, model_config): |
| 44 | + max_length = model_config["aggregates"]["max_review_length"] |
| 45 | + |
| 46 | + features["inputs"] = tf.expand_dims(tf.reshape(features["embedding_input"], [max_length]), -1) |
| 47 | + features["targets"] = tf.expand_dims(tf.expand_dims(labels, -1), -1) |
| 48 | + |
| 49 | + return features, labels |
| 50 | + |
| 51 | + |
| 52 | +class SentimentIMDBCortex(imdb.SentimentIMDB): |
| 53 | + """IMDB sentiment classification, with an in-memory vocab""" |
| 54 | + |
| 55 | + def __init__(self, vocab_list): |
| 56 | + super().__init__() |
| 57 | + self.vocab = vocab_list |
| 58 | + |
| 59 | + def feature_encoders(self, data_dir): |
| 60 | + encoder = text_encoder.TokenTextEncoder(vocab_filename=None, vocab_list=self.vocab) |
| 61 | + |
| 62 | + return { |
| 63 | + "inputs": encoder, |
| 64 | + "targets": text_encoder.ClassLabelEncoder(self.class_labels(data_dir)), |
| 65 | + } |
0 commit comments