.. _sec_textprediction_customization: Text Prediction - Customized Hyperparameter Search ================================================== This tutorial teaches you how to control the hyperparameter tuning process in ``TextPrediction`` by specifying: - A custom search space of candidate hyperparameter values to consider. - Which hyperparameter optimization algorithm should be used to actually search through this space. .. code:: python import numpy as np import warnings warnings.filterwarnings('ignore') np.random.seed(123) Paraphrase Identification ------------------------- We consider a Paraphrase Identification task for illustration. Given a pair of sentences, the goal is to predict whether or not one sentence is a restatement of the other (a binary classification task). Here we train models on the `Microsoft Research Paraphrase Corpus `__ dataset. .. code:: python from autogluon.utils.tabular.utils.loaders import load_pd train_data = load_pd.load('https://autogluon-text.s3-accelerate.amazonaws.com/glue/mrpc/train.parquet') dev_data = load_pd.load('https://autogluon-text.s3-accelerate.amazonaws.com/glue/mrpc/dev.parquet') train_data.head(10) .. parsed-literal:: :class: output Loaded data from: https://autogluon-text.s3-accelerate.amazonaws.com/glue/mrpc/train.parquet | Columns = 3 / 3 | Rows = 3668 -> 3668 Loaded data from: https://autogluon-text.s3-accelerate.amazonaws.com/glue/mrpc/dev.parquet | Columns = 3 / 3 | Rows = 408 -> 408 .. raw:: html
sentence1 sentence2 label
0 Amrozi accused his brother , whom he called " ... Referring to him as only " the witness " , Amr... 1
1 Yucaipa owned Dominick 's before selling the c... Yucaipa bought Dominick 's in 1995 for $ 693 m... 0
2 They had published an advertisement on the Int... On June 10 , the ship 's owners had published ... 1
3 Around 0335 GMT , Tab shares were up 19 cents ... Tab shares jumped 20 cents , or 4.6 % , to set... 0
4 The stock rose $ 2.11 , or about 11 percent , ... PG & E Corp. shares jumped $ 1.63 or 8 percent... 1
5 Revenue in the first quarter of the year dropp... With the scandal hanging over Stewart 's compa... 1
6 The Nasdaq had a weekly gain of 17.27 , or 1.2... The tech-laced Nasdaq Composite .IXIC rallied ... 0
7 The DVD-CCA then appealed to the state Supreme... The DVD CCA appealed that decision to the U.S.... 1
8 That compared with $ 35.18 million , or 24 cen... Earnings were affected by a non-recurring $ 8 ... 0
9 Shares of Genentech , a much larger company wi... Shares of Xoma fell 16 percent in early trade ... 0
.. code:: python from autogluon_contrib_nlp.data.tokenizers import MosesTokenizer tokenizer = MosesTokenizer('en') # just used to display sentences row_index = 2 print('Paraphrase example:') print('Sentence1: ', tokenizer.decode(train_data['sentence1'][row_index].split())) print('Sentence2: ', tokenizer.decode(train_data['sentence2'][row_index].split())) print('Label: ', train_data['label'][row_index]) row_index = 3 print('\nNot Paraphrase example:') print('Sentence1:', tokenizer.decode(train_data['sentence1'][row_index].split())) print('Sentence2:', tokenizer.decode(train_data['sentence2'][row_index].split())) print('Label:', train_data['label'][row_index]) .. parsed-literal:: :class: output /var/lib/jenkins/miniconda3/envs/autogluon_docs-v0_0_15/lib/python3.7/site-packages/ipykernel/ipkernel.py:287: DeprecationWarning: `should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above. and should_run_async(code) .. parsed-literal:: :class: output Paraphrase example: Sentence1: They had published an advertisement on the Internet on June 10, offering the cargo for sale, he added. Sentence2: On June 10, the ship's owners had published an advertisement on the Internet, offering the explosives for sale. Label: 1 Not Paraphrase example: Sentence1: Around 0335 GMT, Tab shares were up 19 cents, or 4.4%, at A $4.56, having earlier set a record high of A $4.57. Sentence2: Tab shares jumped 20 cents, or 4.6%, to set a record closing high at A $4.57. Label: 0 Perform HPO over a Customized Search Space with Random Search ------------------------------------------------------------- To control which hyperparameter values are considered during ``fit()``, we specify the ``hyperparameters`` argument. Rather than specifying a particular fixed value for a hyperparameter, we can specify a space of values to search over via ``ag.space``. We can also specify which HPO algorithm to use for the search via ``search_strategy`` (a simple `random search `__ is specified below). In this example, we search for good values of the following hyperparameters: - warmup - learning rate - dropout before the first task-specific layer - layer-wise learning rate decay - number of task-specific layers .. code:: python import autogluon as ag from autogluon import TextPrediction as task hyperparameters = { 'models': { 'BertForTextPredictionBasic': { 'search_space': { 'model.network.agg_net.num_layers': ag.space.Int(0, 3), 'model.network.agg_net.data_dropout': ag.space.Categorical(False, True), 'optimization.num_train_epochs': 4, 'optimization.warmup_portion': ag.space.Real(0.1, 0.2), 'optimization.layerwise_lr_decay': ag.space.Real(0.8, 1.0), 'optimization.lr': ag.space.Real(1E-5, 1E-4) } }, }, 'hpo_params': { 'scheduler': 'fifo', # schedule training jobs in a sequential first-in first-out fashion during HPO 'search_strategy': 'random' # perform HPO via simple random search } } We can now call ``fit()`` with hyperparameter-tuning over our custom search space. Below ``num_trials`` controls the maximal number of different hyperparameter configurations for which AutoGluon will train models (5 models are trained under different hyperparameter configurations in this case). To achieve good performance in your applications, you should use larger values of ``num_trials``, which may identify superior hyperparameter values but will require longer runtimes. .. code:: python predictor_mrpc = task.fit(train_data, label='label', hyperparameters=hyperparameters, num_trials=5, # increase this to achieve good performance in your applications time_limits=60 * 6, ngpus_per_trial=1, seed=123, output_directory='./ag_mrpc_random_search') .. parsed-literal:: :class: output NumPy-shape semantics has been activated in your code. This is required for creating and manipulating scalar and zero-size tensors, which were not supported in MXNet before, as in the official NumPy library. Please DO NOT manually deactivate this semantics while using `mxnet.numpy` and `mxnet.numpy_extension` modules. 2020-12-08 20:21:49,199 - root - INFO - All Logs will be saved to ./ag_mrpc_random_search/ag_text_prediction.log 2020-12-08 20:21:49,215 - root - INFO - Train Dataset: 2020-12-08 20:21:49,216 - root - INFO - Columns: - Text( name="sentence1" #total/missing=2934/0 length, min/avg/max=38/118.03/226 ) - Text( name="sentence2" #total/missing=2934/0 length, min/avg/max=42/118.07/215 ) - Categorical( name="label" #total/missing=2934/0 num_class (total/non_special)=2/2 categories=[0, 1] freq=[962, 1972] ) 2020-12-08 20:21:49,216 - root - INFO - Tuning Dataset: 2020-12-08 20:21:49,216 - root - INFO - Columns: - Text( name="sentence1" #total/missing=734/0 length, min/avg/max=40/120.27/209 ) - Text( name="sentence2" #total/missing=734/0 length, min/avg/max=42/121.55/212 ) - Categorical( name="label" #total/missing=734/0 num_class (total/non_special)=2/2 categories=[0, 1] freq=[232, 502] ) 2020-12-08 20:21:49,217 - root - INFO - Label columns=['label'], Feature columns=['sentence1', 'sentence2'], Problem types=['classification'], Label shapes=[2] 2020-12-08 20:21:49,217 - root - INFO - Eval Metric=acc, Stop Metric=acc, Log Metrics=['f1', 'mcc', 'auc', 'acc', 'nll'] .. parsed-literal:: :class: output HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=5.0), HTML(value=''))) .. parsed-literal:: :class: output 0%| | 0/368 [00:00`__. Here we specify **skopt** as the searcher, which uses a BayesOpt implementation from the `scikit-optimize `__ library. .. code:: python hyperparameters['hpo_params'] = { 'scheduler': 'fifo', 'search_strategy': 'skopt' } predictor_mrpc_skopt = task.fit(train_data, label='label', hyperparameters=hyperparameters, time_limits=60 * 6, num_trials=5, # increase this to get good performance in your applications ngpus_per_trial=1, seed=123, output_directory='./ag_mrpc_custom_space_fifo_skopt') .. parsed-literal:: :class: output 2020-12-08 20:27:07,092 - root - INFO - All Logs will be saved to ./ag_mrpc_custom_space_fifo_skopt/ag_text_prediction.log 2020-12-08 20:27:07,109 - root - INFO - Train Dataset: 2020-12-08 20:27:07,110 - root - INFO - Columns: - Text( name="sentence1" #total/missing=2934/0 length, min/avg/max=38/118.38/226 ) - Text( name="sentence2" #total/missing=2934/0 length, min/avg/max=42/118.63/215 ) - Categorical( name="label" #total/missing=2934/0 num_class (total/non_special)=2/2 categories=[0, 1] freq=[938, 1996] ) 2020-12-08 20:27:07,110 - root - INFO - Tuning Dataset: 2020-12-08 20:27:07,111 - root - INFO - Columns: - Text( name="sentence1" #total/missing=734/0 length, min/avg/max=38/118.90/215 ) - Text( name="sentence2" #total/missing=734/0 length, min/avg/max=47/119.34/207 ) - Categorical( name="label" #total/missing=734/0 num_class (total/non_special)=2/2 categories=[0, 1] freq=[256, 478] ) 2020-12-08 20:27:07,111 - root - INFO - Label columns=['label'], Feature columns=['sentence1', 'sentence2'], Problem types=['classification'], Label shapes=[2] 2020-12-08 20:27:07,112 - root - INFO - Eval Metric=acc, Stop Metric=acc, Log Metrics=['f1', 'mcc', 'auc', 'acc', 'nll'] .. parsed-literal:: :class: output HBox(children=(HTML(value=''), FloatProgress(value=0.0, max=5.0), HTML(value=''))) .. parsed-literal:: :class: output 0%| | 0/368 [00:00`__ for HPO. Hyperband will try multiple hyperparameter configurations simultaneously and will early stop training under poor configurations to free compute resources for exploring new hyperparameter configurations. It may be able to identify good hyperparameter values more quickly than other search strategies in your applications. .. code:: python hyperparameters['hpo_params'] = { 'scheduler': 'hyperband', 'search_strategy': 'random', 'max_t': 40, # Number of epochs per training run of one neural network } .. code:: python predictor_mrpc_hyperband = task.fit(train_data, label='label', hyperparameters=hyperparameters, time_limits=60 * 6, ngpus_per_trial=1, seed=123, output_directory='./ag_mrpc_custom_space_hyperband') .. parsed-literal:: :class: output 2020-12-08 20:34:21,669 - root - INFO - All Logs will be saved to ./ag_mrpc_custom_space_hyperband/ag_text_prediction.log 2020-12-08 20:34:21,688 - root - INFO - Train Dataset: 2020-12-08 20:34:21,688 - root - INFO - Columns: - Text( name="sentence1" #total/missing=2934/0 length, min/avg/max=38/118.23/220 ) - Text( name="sentence2" #total/missing=2934/0 length, min/avg/max=42/118.70/215 ) - Categorical( name="label" #total/missing=2934/0 num_class (total/non_special)=2/2 categories=[0, 1] freq=[960, 1974] ) 2020-12-08 20:34:21,689 - root - INFO - Tuning Dataset: 2020-12-08 20:34:21,689 - root - INFO - Columns: - Text( name="sentence1" #total/missing=734/0 length, min/avg/max=45/119.49/226 ) - Text( name="sentence2" #total/missing=734/0 length, min/avg/max=46/119.05/210 ) - Categorical( name="label" #total/missing=734/0 num_class (total/non_special)=2/2 categories=[0, 1] freq=[234, 500] ) 2020-12-08 20:34:21,690 - root - INFO - Label columns=['label'], Feature columns=['sentence1', 'sentence2'], Problem types=['classification'], Label shapes=[2] 2020-12-08 20:34:21,690 - root - INFO - Eval Metric=acc, Stop Metric=acc, Log Metrics=['f1', 'mcc', 'auc', 'acc', 'nll'] 100%|██████████| 368/368 [01:19<00:00, 4.63it/s] 100%|██████████| 368/368 [01:20<00:00, 4.57it/s] 30%|██▉ | 109/368 [00:25<00:59, 4.32it/s] 30%|██▉ | 109/368 [00:25<01:00, 4.30it/s] 30%|██▉ | 109/368 [00:25<01:00, 4.29it/s] 30%|██▉ | 109/368 [00:25<00:59, 4.35it/s] 30%|██▉ | 109/368 [00:25<01:00, 4.26it/s] 30%|██▉ | 109/368 [00:25<00:59, 4.32it/s] 100%|██████████| 368/368 [01:19<00:00, 4.63it/s] .. code:: python dev_score = predictor_mrpc_hyperband.evaluate(dev_data, metrics=['acc', 'f1']) print('Best Config = {}'.format(predictor_mrpc_hyperband.results['best_config'])) print('Total Time = {}s'.format(predictor_mrpc_hyperband.results['total_time'])) print('Accuracy = {:.2f}%'.format(dev_score['acc'] * 100)) print('F1 = {:.2f}%'.format(dev_score['f1'] * 100)) .. parsed-literal:: :class: output Best Config = {'search_space▁model.network.agg_net.data_dropout▁choice': 0, 'search_space▁model.network.agg_net.num_layers': 2, 'search_space▁optimization.layerwise_lr_decay': 0.9, 'search_space▁optimization.lr': 5.5e-05, 'search_space▁optimization.warmup_portion': 0.15} Total Time = 457.0654797554016s Accuracy = 82.84% F1 = 88.22% .. code:: python predictions = predictor_mrpc_hyperband.predict(dev_data) prediction1 = predictor_mrpc_hyperband.predict({'sentence1': [sentence1], 'sentence2': [sentence2]}) prediction1_prob = predictor_mrpc_hyperband.predict_proba({'sentence1': [sentence1], 'sentence2': [sentence2]}) print('A = "{}"'.format(sentence1)) print('B = "{}"'.format(sentence2)) print('Prediction = "{}"'.format(prediction1[0] == 1)) print('Prob = "{}"'.format(prediction1_prob[0])) print('') prediction2 = predictor_mrpc_hyperband.predict({'sentence1': [sentence1], 'sentence2': [sentence3]}) prediction2_prob = predictor_mrpc_hyperband.predict_proba({'sentence1': [sentence1], 'sentence2': [sentence3]}) print('A = "{}"'.format(sentence1)) print('B = "{}"'.format(sentence3)) print('Prediction = "{}"'.format(prediction2[0] == 1)) print('Prob = "{}"'.format(prediction2_prob[0])) .. parsed-literal:: :class: output A = "It is simple to solve NLP problems with AutoGluon." B = "With AutoGluon, it is easy to solve NLP problems." Prediction = "True" Prob = "[0.01117248 0.9888276 ]" A = "It is simple to solve NLP problems with AutoGluon." B = "AutoGluon gives you a very bad user experience for solving NLP problems." Prediction = "False" Prob = "[0.76531047 0.23468953]"