<jupyter_start><jupyter_text>Copyright 2019 The TensorFlow Authors.<jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>Text classification with TensorFlow Lite Model Maker       View on TensorFlow.org        Run in Google Colab        View source on GitHub        Download notebook   The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used text classification model to classify movie reviews on a mobile device. The text classification model classifies text into predefined categories.The inputs should be preprocessed text and the outputs are the probabilities of the categories. The dataset used in this tutorial are positive and negative movie reviews.  Prerequisites  Install the required packagesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).**If you run this notebook on Colab, you may see an error message about `tensorflowjs` and `tensorflow-hub` version imcompatibility. It is safe to ignore this error as we do not use `tensorflowjs` in this workflow.**<jupyter_code>!pip install -q tflite-model-maker<jupyter_output><empty_output><jupyter_text>Import the required packages.<jupyter_code>import numpy as np
import os

from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import text_classifier
from tflite_model_maker import TextClassifierDataLoader

import tensorflow as tf
assert tf.__version__.startswith('2')
tf.get_logger().setLevel('ERROR')<jupyter_output><empty_output><jupyter_text>Download the sample training data.In this tutorial, we will use the [SST-2](https://nlp.stanford.edu/sentiment/index.html) (Stanford Sentiment Treebank) which is one of the tasks in the [GLUE](https://gluebenchmark.com/) benchmark. It contains 67,349 movie reviews for training and 872 movie reviews for testing. The dataset has two classes: positive and negative movie reviews.<jupyter_code>data_dir = tf.keras.utils.get_file(
      fname='SST-2.zip',
      origin='https://dl.fbaipublicfiles.com/glue/data/SST-2.zip',
      extract=True)
data_dir = os.path.join(os.path.dirname(data_dir), 'SST-2')<jupyter_output><empty_output><jupyter_text>The SST-2 dataset is stored in TSV format. The only difference between TSV and CSV is that TSV uses a tab `\t` character as its delimiter instead of a comma `,` in the CSV format.Here are the first 5 lines of the training dataset. label=0 means negative, label=1 means positive.| sentence                                                                                  | label |   |   |   ||-------------------------------------------------------------------------------------------|-------|---|---|---|| hide new secretions from the parental units                                               | 0     |   |   |   || contains no wit , only labored gags                                                       | 0     |   |   |   || that loves its characters and communicates something rather beautiful about human nature  | 1     |   |   |   || remains utterly satisfied to remain the same throughout                                   | 0     |   |   |   || on the worst revenge-of-the-nerds clichés the filmmakers could dredge up                  | 0     |   |   |   |Next, we will load the dataset into a Pandas dataframe and change the current label names (`0` and `1`) to a more human-readable ones (`negative` and `positive`) and use them for model training.<jupyter_code>import pandas as pd

def replace_label(original_file, new_file):
  # Load the original file to pandas. We need to specify the separator as
  # '\t' as the training data is stored in TSV format
  df = pd.read_csv(original_file, sep='\t')

  # Define how we want to change the label name
  label_map = {0: 'negative', 1: 'positive'}

  # Excute the label change
  df.replace({'label': label_map}, inplace=True)

  # Write the updated dataset to a new file
  df.to_csv(new_file)

# Replace the label name for both the training and test dataset. Then write the
# updated CSV dataset to the current folder.
replace_label(os.path.join(os.path.join(data_dir, 'train.tsv')), 'train.csv')
replace_label(os.path.join(os.path.join(data_dir, 'dev.tsv')), 'dev.csv')<jupyter_output><empty_output><jupyter_text>QuickstartThere are five steps to train a text classification model:**Step 1. Choose a text classification model archiecture.**Here we use the average word embedding model architecture, which will produce a small and fast model with decent accuracy.<jupyter_code>spec = model_spec.get('average_word_vec')<jupyter_output><empty_output><jupyter_text>Model Maker also supports other model architectures such as [BERT](https://arxiv.org/abs/1810.04805). If you are interested to learn about other architecture, see the [Choose a model architecture for Text Classifier](scrollTo=kJ_B8fMDOhMR) section below. **Step 2.   Load the training and test data, then preprocess them according to a specific `model_spec`.**Model Maker can take input data in the CSV format. We will load the training and test dataset with the human-readable label name that were created earlier.Each model architecture requires input data to be processed in a particular way. `TextClassifierDataLoader` reads the requirement from `model_spec` and automatically execute the necessary preprocessing.<jupyter_code>train_data = TextClassifierDataLoader.from_csv(
      filename='train.csv',
      text_column='sentence',
      label_column='label',
      model_spec=spec,
      is_training=True)
test_data = TextClassifierDataLoader.from_csv(
      filename='dev.csv',
      text_column='sentence',
      label_column='label',
      model_spec=spec,
      is_training=False)<jupyter_output><empty_output><jupyter_text>**Step 3. Train the TensorFlow model with the training data.**The average word embedding model use `batch_size = 32` by default. Therefore you will see that it takes 2104 steps to go through the 67,349 sentences in the training dataset. We will train the model for 10 epochs, which means going through the training dataset 10 times.<jupyter_code>model = text_classifier.create(train_data, model_spec=spec, epochs=10)<jupyter_output><empty_output><jupyter_text>**Step 4. Evaluate the model with the test data.**After training the text classification model using the sentences in the training dataset, we will use the remaining 872 sentences in the test dataset to evaluate how the model perform against new data it has never seen before.As the default batch size is 32, it will take 28 steps to go through the 872 sentences in the test dataset.<jupyter_code>loss, acc = model.evaluate(test_data)<jupyter_output><empty_output><jupyter_text>**Step 5.  Export as a TensorFlow Lite model.**Let's export the text classification that we have trained in the TensorFlow Lite format. We will specify which folder to export the model.You may see an warning about `vocab.txt` file does not exist in the metadata but they can be safely ignore.<jupyter_code>model.export(export_dir='average_word_vec')<jupyter_output><empty_output><jupyter_text>You can download the TensorFlow Lite model file using the left sidebar of Colab. Go into the `average_word_vec` folder as we specified in `export_dir` parameter above, right-click on the `model.tflite` file and choose `Download` to download it to your local computer.This model can be integrated into an Android or an iOS app using the [NLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/nl_classifier) of the [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview).See the [TFLite Text Classification sample app](https://github.com/tensorflow/examples/blob/master/lite/examples/text_classification/android/lib_task_api/src/main/java/org/tensorflow/lite/examples/textclassification/client/TextClassificationClient.javaL54) for more details on how the model is used in an working app.*Note 1: Android Studio Model Binding does not support text classification yet so please use the TensorFlow Lite Task Library.**Note 2: There is a `model.json` file in the same folder with the TFLite model. It contains the JSON representation of the [metadata](https://www.tensorflow.org/lite/convert/metadata) bundled inside the TensorFlow Lite model. Model metadata helps the TFLite Task Library know what the model does and how to pre-process/post-process data for the model. You don't need to download the `model.json` file as it is only for informational purpose and its content is already inside the TFLite file.**Note 3: If you train a text classification model using MobileBERT or BERT-Base architecture, you will need to use [BertNLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_nl_classifier) instead to integrate the trained model into a mobile app.* The following sections walk through the example step by step to show more details.  Choose a model architecture for Text ClassifierEach `model_spec` object represents a specific model for the text classifier. TensorFlow Lite Model Maker currently supports [MobileBERT](https://arxiv.org/pdf/2004.02984.pdf), averaging word embeddings and [BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) models.| Supported Model          | Name of model_spec      | Model Description                                                                                                     | Model size                                  ||--------------------------|-------------------------|-----------------------------------------------------------------------------------------------------------------------|---------------------------------------------|| Averaging Word Embedding | 'average_word_vec'      | Averaging text word embeddings with RELU activation.                                                                  |           <1MB                             || MobileBERT               | 'mobilebert_classifier' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device applications. | 25MB w/ quantization  100MB w/o quantization                                        || BERT-Base                | 'bert_classifier'       | Standard BERT model that is widely used in NLP tasks.                                                                 | 300MB |In the quick start, we have used the average word embedding model. Let's switch to [MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) to train a model with higher accuracy.<jupyter_code>mb_spec = model_spec.get('mobilebert_classifier')<jupyter_output><empty_output><jupyter_text>Load training dataYou can upload your own dataset to work through this tutorial. Upload your dataset by using the left sidebar in Colab.If you prefer not to upload your dataset to the cloud, you can also locally run the library by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). To keep it simple, we will reuse the SST-2 dataset downloaded earlier. Let's use the `TestClassifierDataLoader.from_csv` method to load the data.Please be noted that as we have changed the model architecture, we will need to reload the training and test dataset to apply the new preprocessing logic.<jupyter_code>train_data = TextClassifierDataLoader.from_csv(
      filename='train.csv',
      text_column='sentence',
      label_column='label',
      model_spec=mb_spec,
      is_training=True)
test_data = TextClassifierDataLoader.from_csv(
      filename='dev.csv',
      text_column='sentence',
      label_column='label',
      model_spec=mb_spec,
      is_training=False)<jupyter_output><empty_output><jupyter_text>The Model Maker library also supports the `from_folder()` method to load data. It assumes that the text data of the same class are in the same subdirectory and that the subfolder name is the class name. Each text file contains one movie review sample. The `class_labels` parameter is used to specify which the subfolders.  Train a TensorFlow ModelTrain a text classification model using the training data.*Note: As MobileBERT is a complex model, each training epoch will takes about 10 minutes on a Colab GPU. Please make sure that you are using a GPU runtime.*<jupyter_code>model = text_classifier.create(train_data, model_spec=mb_spec, epochs=3)<jupyter_output><empty_output><jupyter_text>Examine the detailed model structure.<jupyter_code>model.summary()<jupyter_output><empty_output><jupyter_text>Evaluate the modelEvaluate the model that we have just trained using the test data and measure the loss and accuracy value.<jupyter_code>loss, acc = model.evaluate(test_data)<jupyter_output><empty_output><jupyter_text>Quantize the modelIn many on-device ML application, the model size is an important factor. Therefore, it is recommended that you apply quantize the model to make it smaller and potentially run faster. Model Maker automatically applies the recommended quantization scheme for each model architecture but you can customize the quantization config as below.<jupyter_code>config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config.experimental_new_quantizer = True<jupyter_output><empty_output><jupyter_text>Export as a TensorFlow Lite modelConvert the trained model to TensorFlow Lite model format with [metadata](https://www.tensorflow.org/lite/convert/metadata) so that you can later use in an on-device ML application. The label file and the vocab file are embedded in metadata. The default TFLite filename is `model.tflite`.<jupyter_code>model.export(export_dir='mobilebert/', quantization_config=config)<jupyter_output><empty_output><jupyter_text>The TensorFlow Lite model file can be integrated in a mobile app using the [BertNLClassifier API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_nl_classifier) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview). Please note that this is **different** from the `NLClassifier` API used to integrate the text classification trained with the average word vector model architecture. The export formats can be one or a list of the following:*   `ExportFormat.TFLITE`*   `ExportFormat.LABEL`*   `ExportFormat.VOCAB`*   `ExportFormat.SAVED_MODEL`By default, it exports only the TensorFlow Lite model file containing the model metadata. You can also choose to export other files related to the model for better examination. For instance, exporting only the label file and vocab file as follows:<jupyter_code>model.export(export_dir='mobilebert/', export_format=[ExportFormat.LABEL, ExportFormat.VOCAB])<jupyter_output><empty_output><jupyter_text>You can evaluate the TFLite model with `evaluate_tflite` method to measure its accuracy. Converting the trained TensorFlow model to TFLite format and apply quantization can affect its accuracy so it is recommended to evaluate the TFLite model accuracy before deployment.<jupyter_code>accuracy = model.evaluate_tflite('mobilebert/model.tflite', test_data)
print('TFLite model accuracy: ', accuracy)<jupyter_output><empty_output><jupyter_text>Advanced UsageThe `create` function is the driver function that the Model Maker library uses to create models. The `model_spec` parameter defines the model specification. The `AverageWordVecModelSpec` and `BertClassifierModelSpec` classes are currently supported. The `create` function comprises of the following steps:1. Creates the model for the text classifier according to `model_spec`.2. Trains the classifier model.  The default epochs and the default batch size are set by the `default_training_epochs` and `default_batch_size` variables in the `model_spec` object.This section covers advanced usage topics like adjusting the model and the training hyperparameters.  Customize the MobileBERT model hyperparametersThe model parameters you can adjust are:* `seq_len`: Length of the sequence to feed into the model.* `initializer_range`: The standard deviation of the `truncated_normal_initializer` for initializing all weight matrices.* `trainable`: Boolean that specifies whether the pre-trained layer is trainable.The training pipeline parameters you can adjust are:* `model_dir`: The location of the model checkpoint files. If not set, a temporary directory will be used.* `dropout_rate`: The dropout rate.* `learning_rate`: The initial learning rate for the Adam optimizer.* `tpu`: TPU address to connect to.For instance, you can set the `seq_len=256` (default is 128). This allows the model to classify longer text.<jupyter_code>new_model_spec = model_spec.get('mobilebert_classifier')
new_model_spec.seq_len = 256<jupyter_output><empty_output><jupyter_text>Customize the average word embedding model hyperparametersYou can adjust the model infrastructure like the `wordvec_dim` and the `seq_len` variables in the `AverageWordVecModelSpec` class. For example, you can train the model with a larger value of `wordvec_dim`. Note that you must construct a new `model_spec` if you modify the model.<jupyter_code>new_model_spec = model_spec.AverageWordVecModelSpec(wordvec_dim=32)<jupyter_output><empty_output><jupyter_text>Get the preprocessed data.<jupyter_code>new_train_data = TextClassifierDataLoader.from_csv(
      filename='train.csv',
      text_column='sentence',
      label_column='label',
      model_spec=new_model_spec,
      is_training=True)<jupyter_output><empty_output><jupyter_text>Train the new model.<jupyter_code>model = text_classifier.create(new_train_data, model_spec=new_model_spec)<jupyter_output><empty_output><jupyter_text>Tune the training hyperparametersYou can also tune the training hyperparameters like `epochs` and `batch_size` that affect the model accuracy. For instance,*   `epochs`: more epochs could achieve better accuracy, but may lead to overfitting.*   `batch_size`: the number of samples to use in one training step.For example, you can train with more epochs.<jupyter_code>model = text_classifier.create(new_train_data, model_spec=new_model_spec, epochs=20)<jupyter_output><empty_output><jupyter_text>Evaluate the newly retrained model with 20 training epochs.<jupyter_code>new_test_data = TextClassifierDataLoader.from_csv(
      filename='dev.csv',
      text_column='sentence',
      label_column='label',
      model_spec=new_model_spec,
      is_training=False)

loss, accuracy = model.evaluate(new_test_data)<jupyter_output><empty_output><jupyter_text>Change the Model ArchitectureYou can change the model by changing the `model_spec`. The following shows how to change to BERT-Base model.Change the `model_spec` to BERT-Base model for the text classifier.<jupyter_code>spec = model_spec.get('bert_classifier')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08448634129035527, 'fraction_numerical': 0.007196796918554559, 'mean_word_length': 4.191265456458827, 'pattern_counts': {'":': 0, '<': 106, '<?xml version=': 0, '>': 105, 'https://': 18, 'lorem ipsum': 0, 'www.': 8, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '26', 'dir': 'jupyter-structured-clean-dedup', 'id': '3864', 'license': 'Apache-2.0', 'n_tokens_mistral': 5319, 'n_tokens_neox': 5031, 'n_words': 2032, 'path': 'tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb', 'repo_name': 'simonmaurer/tensorflow', 'size': '19731'}