{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<img width=\"800px\" src=\"../fidle/img/00-Fidle-header-01.svg\"></img>\n", "\n", "# <!-- TITLE --> [TRANS1] - IMDB, Sentiment analysis with Transformers \n", "<!-- DESC --> Using a Tranformer to perform a sentiment analysis (IMDB) - Jean Zay version\n", "<!-- AUTHOR : Hatim Bourfoune (IDRIS) and Nathan Cassereau (IDRIS) -->\n", "\n", "By : Hatim Bourfoune (IDRIS) and Nathan Cassereau (IDRIS)\n", "\n", "\n", "## Objectives :\n", " - Complement the learning of a Transformer to perform a sentiment analysis\n", " - Understand the use of a pre-trained transformer\n", "\n", "This task is exactly the same as the Sentiment analysis with text embedding. Only this time, \n", "we are going to exploit the strenght of transformers. Considering how computation-heavy transformer \n", "pretraining is, we are going to use a pretrained BERT model from HuggingFace. \n", "This notebook performs the fine-tuning process. If possible, try to use a GPU to speed up \n", "the training, transformers are difficult to train on CPU.\n", "\n", "## What we are going to do:\n", "\n", "* Retrieve the dataset\n", "* Prepare the dataset\n", "* Fetch a pretrained BERT model from HuggingFace's platform (https://huggingface.co/models)\n", "* Fine-tune the model on a sequence classification task: the sentiment analysis of the IMDB dataset\n", "* Evaluate the result\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Installations\n", "\n", "**IMPORTANT :** We will need to use the library `transformers` created by HuggingFace.\n", "\n", "The next line only applies on Jean Zay, it allows us to load a very specific environment, which contains Tensorflow with GPU support. Ignore that line if this notebook is not executed on Jean Zay." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "50QKMUQzPv3n", "outputId": "3ac2016d-596d-4f9a-c2ec-738c939c49a0" }, "outputs": [], "source": [ "#!pip install transformers\n", "!module load tensorflow-gpu/py3/2.6.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Imports and initialisation " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ZrV8ONYZPi8L", "outputId": "ad10d385-3e1f-4ecf-80f2-87dccc286db7" }, "outputs": [], "source": [ "import numpy as np\n", "\n", "import tensorflow as tf\n", "import tensorflow.keras as keras\n", "import tensorflow.keras.datasets.imdb as imdb\n", "from tensorflow.keras.layers import Dense, Dropout\n", "from tensorflow.keras.optimizers import Adam\n", "from tensorflow.keras.losses import SparseCategoricalCrossentropy\n", "from tensorflow.keras.metrics import SparseCategoricalAccuracy\n", "from tensorflow.keras import mixed_precision\n", "\n", "from transformers import (\n", " DistilBertTokenizer,\n", " TFDistilBertModel,\n", " DataCollatorWithPadding,\n", " BertTokenizer,\n", " TFBertModel\n", ")\n", "\n", "import pickle\n", "import multiprocessing\n", "import itertools\n", "import os\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "\n", "print(\"Tensorflow \", tf.__version__)\n", "n_gpus = len(tf.config.list_physical_devices('GPU'))\n", "print(\"#GPUs: \", n_gpus)\n", "if n_gpus > 0:\n", " !nvidia-smi -L\n", "policy = mixed_precision.Policy('mixed_float16')\n", "mixed_precision.set_global_policy(policy)\n", "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n", "\n", "np.random.seed(987654321)\n", "tf.random.set_seed(987654321)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Parameters\n", "\n", "* `vocab_size` refers to the number of words which will be remembered in our vocabulary.\n", "* `hide_most_frequently` is the number of ignored words, among the most common ones.\n", "* `review_len` is the review length.\n", "* `n_cpus` is the number of CPU which will be used for data preprocessing.\n", "* `distil` refers to whether or not we are going to use a DistilBert model or a regular Bert model.\n", "* `load_locally` will fetch data locally, otherwise will download on the Internet (requires an Internet connection, not possible on Jean Zay)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "FhIuZkS2PnTE" }, "outputs": [], "source": [ "vocab_size = 30000\n", "hide_most_frequently = 0\n", "\n", "review_len = 512\n", "\n", "epochs = 1\n", "batch_size = 32\n", "\n", "fit_verbosity = 1\n", "scale = 1\n", "\n", "n_cpus = 6\n", "distil = True\n", "load_locally = True # if set to False, will fetch data from the internet (requires an internet connection)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Retrieve the dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "qaRtDy9wQinS", "outputId": "9d2d9e12-74fb-4eee-9d9b-d4a7148e2dc2" }, "outputs": [], "source": [ "if load_locally:\n", " with open(\"dataset\", \"rb\") as file_:\n", " (x_train, y_train), (x_test, y_test) = pickle.load(file_)\n", "else:\n", " (x_train, y_train), (x_test, y_test) = imdb.load_data(\n", " num_words=vocab_size,\n", " skip_top=hide_most_frequently,\n", " seed=123456789,\n", " )\n", " with open(\"dataset\", \"wb\") as file_:\n", " pickle.dump(((x_train, y_train), (x_test, y_test)), file_)\n", "\n", "\n", "y_train = np.asarray(y_train).astype('float32')\n", "y_test = np.asarray(y_test ).astype('float32')\n", "\n", "n1 = int(scale * len(x_train))\n", "n2 = int(scale * len(x_test))\n", "x_train, y_train = x_train[:n1], y_train[:n1]\n", "x_test, y_test = x_test[:n2], y_test[:n2]\n", "\n", "print(\"x_train : {} y_train : {}\".format(x_train.shape, y_train.shape))\n", "print(\"x_test : {} y_test : {}\".format(x_test.shape, y_test.shape))\n", "print('\\nReview sample (x_train[12]) :\\n\\n',x_train[12])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nbF1uktpRdXy" }, "outputs": [], "source": [ "if load_locally:\n", " with open(\"word_index\", \"rb\") as file_:\n", " word_index = pickle.load(file_)\n", "else:\n", " word_index = imdb.get_word_index()\n", " with open(\"word_index\", \"wb\") as file_:\n", " pickle.dump(word_index, file_)\n", "\n", "word_index = {w:(i+3) for w,i in word_index.items()}\n", "word_index.update({'[PAD]':0, '[CLS]':1, '[UNK]':2})\n", "index_word = {index:word for word,index in word_index.items()} \n", "\n", "# Add a nice function to transpose:\n", "def dataset2text(review):\n", " return ' '.join([index_word.get(i, \"?\") for i in review[1:]])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DifmZNsKR38n", "outputId": "cb5f9819-1930-478d-f3f2-45f06e04c5d4" }, "outputs": [], "source": [ "print(dataset2text(x_train[12]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fetch the model from HuggingFace" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def load_model(distil, load_locally):\n", " if load_locally:\n", " if distil:\n", " bert_model = TFDistilBertModel.from_pretrained(\"distilbert_model\")\n", " tokenizer = DistilBertTokenizer(\"distilbert_vocab.txt\", do_lower_case=True)\n", " else:\n", " bert_model = TFBertModel.from_pretrained(\"bert_model\")\n", " tokenizer = BertTokenizer(\"bert_vocab.txt\", do_lower_case=True)\n", " return bert_model, tokenizer\n", "\n", " if distil:\n", " bert_model = TFDistilBertModel.from_pretrained(\"distilbert-base-uncased\")\n", " tokenizer = DistilBertTokenizer.from_pretrained(\"distilbert-base-uncased\")\n", " bert_model.save_pretrained(\"distilbert_model\")\n", " tokenizer.save_vocabulary(\"distilbert_vocab.txt\")\n", " else:\n", " bert_model = TFBertModel.from_pretrained(\"bert-base-uncased\")\n", " tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n", " bert_model.save_pretrained(\"bert_model\")\n", " tokenizer.save_vocabulary(\"bert_vocab.txt\")\n", " return bert_model, tokenizer\n", "\n", "bert_model, tokenizer = load_model(distil, load_locally)\n", "bert_model.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Prepare the dataset " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "KKwI-RIXnWWd", "outputId": "42dc5943-b060-4a08-9180-cd5914980527" }, "outputs": [], "source": [ "def tokenize_sample(sample, tokenizer):\n", " return tokenizer(dataset2text(sample), truncation=True, max_length=review_len)\n", "\n", "def distributed_tokenize_dataset(dataset):\n", " ds = list(dataset)\n", " with multiprocessing.Pool(n_cpus) as pool:\n", " tokenized_ds = pool.starmap(\n", " tokenize_sample,\n", " zip(ds, itertools.repeat(tokenizer, len(ds)))\n", " )\n", " return tokenized_ds\n", "\n", "tokenized_x_train = distributed_tokenize_dataset(x_train)\n", "tokenized_x_test = distributed_tokenize_dataset(x_test)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TivZYh8vnZlS" }, "outputs": [], "source": [ "data_collator = DataCollatorWithPadding(tokenizer, return_tensors=\"tf\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7Up0APYtwFm7", "outputId": "37cb98bd-a0d3-47c2-9f91-96f94abf4b2e" }, "outputs": [], "source": [ "data_collator(tokenized_x_train)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "U6Lhjfh6maIF", "outputId": "f4798e7f-bc69-47fe-e2a7-c0155a99cca7" }, "outputs": [], "source": [ "def make_dataset(x, y):\n", " collated = data_collator(x)\n", " dataset = tf.data.Dataset.from_tensor_slices(\n", " (collated['input_ids'], collated['attention_mask'], y)\n", " )\n", " transformed_dataset = (\n", " dataset\n", " .map(\n", " lambda x, y, z: ((x, y), z)\n", " )\n", " .shuffle(25000)\n", " .batch(batch_size)\n", " )\n", " return transformed_dataset\n", "\n", "train_ds = make_dataset(tokenized_x_train, y_train)\n", "test_ds = make_dataset(tokenized_x_test, y_test)\n", "\n", "for x, y in train_ds:\n", " print(x)\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add a new head to the model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class ClassificationModel(keras.Model):\n", "\n", " def __init__(self, bert_model):\n", " super(ClassificationModel, self).__init__()\n", " self.bert_model = bert_model\n", " self.pre_classifier = Dense(768, activation='relu')\n", " self.dropout = Dropout(0.1)\n", " self.classifier = Dense(2)\n", "\n", " def call(self, x):\n", " x = self.bert_model(x)\n", " x = x.last_hidden_state\n", " x = x[:, 0] # get the output of the classification token\n", " x = self.pre_classifier(x)\n", " x = self.dropout(x)\n", " x = self.classifier(x)\n", " return x" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model = ClassificationModel(bert_model)\n", "x = next(iter(train_ds))[0]\n", "model(x)\n", "model.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train! " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "4jDAzxxwXLT1", "outputId": "bc4d5f62-9fa7-426d-a9e2-2fa4d2bdf780" }, "outputs": [], "source": [ "model.compile(\n", " optimizer=Adam(1e-05),\n", " loss=SparseCategoricalCrossentropy(from_logits=True),\n", " metrics=[SparseCategoricalAccuracy('accuracy')]\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 419 }, "id": "KtmfFjL02Ano", "outputId": "ca174c57-b8f9-4d50-a53a-03761556e492" }, "outputs": [], "source": [ "history = model.fit(\n", " train_ds,\n", " epochs=epochs,\n", " verbose=fit_verbosity\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluation " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "_, score = model.evaluate(test_ds)\n", "colors = sns.color_palette('pastel')[2:]\n", "accuracy_score = [score, 1 - score]\n", "plt.pie(\n", " accuracy_score,\n", " labels=[\"Accurate\", \"Mistaken\"],\n", " colors=colors,\n", " autopct=lambda val: f\"{val:.2f}%\",\n", " explode=(0.0, 0.1)\n", ")\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "Untitled0.ipynb", "provenance": [] }, "kernelspec": { "display_name": "Python 3.9.2 ('fidle-env')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.2" }, "vscode": { "interpreter": { "hash": "b3929042cc22c1274d74e3e946c52b845b57cb6d84f2d591ffe0519b38e4896d" } } }, "nbformat": 4, "nbformat_minor": 4 }