{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Sentiment Classification with FHE\n", "\n", "This notebook tackles sentiment classification with Fully Homomorphic Encryption. Let's imagine some client (could be a user or a company) wants to predict whether a specific text (e.g., a tweet) contains positive, neutral or negative feedback using a cloud service provider without actually revealing the text during the process.\n", "\n", "To do this, we use a machine learning model that can predict over encrypted data thanks to the Concrete-ML library available on [GitHub](https://github.com/zama-ai/concrete-ml).\n", "\n", "The dataset we use in this notebook can be found on [Kaggle](https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment). \n", " \n", "We present two different ways to encode the text:\n", "1. A basic **TF-IDF** approach, which essentially looks at how often a word appears in the text.\n", "2. An advanced **transformer** embedding of the text using the Huggingface repository.\n", "\n", "The main assumption of this notebook is that clients, who want to have their text analyzed in a privacy preserving manner, can encode the text using a predefined representation before encrypting the data. The FHE-friendly model is thus trained in the clear beforehand for the given task, here classification, over theses representations using a relevant training set." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Import the required packages\n", "import os\n", "import time\n", "\n", "import numpy\n", "import onnx\n", "import pandas as pd\n", "from sklearn.metrics import average_precision_score\n", "from sklearn.model_selection import GridSearchCV, train_test_split\n", "\n", "from concrete.ml.sklearn import XGBClassifier" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Proportion of positive examples: 16.14%\n", "Proportion of negative examples: 62.69%\n", "Proportion of neutral examples: 21.17%\n" ] } ], "source": [ "# Download the datasets\n", "if not os.path.isfile(\"local_datasets/twitter-airline-sentiment/Tweets.csv\"):\n", " raise ValueError(\"Please launch the `download_data.sh` script to get datasets\")\n", "\n", "train = pd.read_csv(\"local_datasets/twitter-airline-sentiment/Tweets.csv\", index_col=0)\n", "text_X = train[\"text\"]\n", "y = train[\"airline_sentiment\"]\n", "y = y.replace([\"negative\", \"neutral\", \"positive\"], [0, 1, 2])\n", "\n", "pos_ratio = y.value_counts()[2] / y.value_counts().sum()\n", "neg_ratio = y.value_counts()[0] / y.value_counts().sum()\n", "neutral_ratio = y.value_counts()[1] / y.value_counts().sum()\n", "print(f\"Proportion of positive examples: {round(pos_ratio * 100, 2)}%\")\n", "print(f\"Proportion of negative examples: {round(neg_ratio * 100, 2)}%\")\n", "print(f\"Proportion of neutral examples: {round(neutral_ratio * 100, 2)}%\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Split in train test\n", "text_X_train, text_X_test, y_train, y_test = train_test_split(\n", " text_X, y, test_size=0.1, random_state=42\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. Text representation using TF-IDF\n", "\n", "[Term Frequency-Inverse Document Frequency](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)(TF-IDF) also known as is a numerical statistic that is used to compute the importance of a term in a document. The higher the TF-IDF score, the more important the term is to the document.\n", "\n", "We compute it as follows:\n", "\n", "$$ \\mathsf{TF\\textrm{-}IDF}(t,d,D) = \\mathsf{TF}(t,d) * \\mathsf{IDF}(t,D) $$\n", "\n", "where: $\\mathsf{TF}(t,d)$ is the term frequency of term $t$ in document $d$, $\\mathsf{IDF}(t,D)$ is the inverse document frequency of term $t$ in document collection $D$.\n", "\n", "Here we use the scikit-learn implementation of TF-IDF vectorizer." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# Let's first build a representation vector from the text\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "\n", "tfidf_vectorizer = TfidfVectorizer(max_features=500, stop_words=\"english\")\n", "X_train = tfidf_vectorizer.fit_transform(text_X_train)\n", "X_test = tfidf_vectorizer.transform(text_X_test)\n", "\n", "# Make our train and test dense array\n", "X_train = X_train.toarray()\n", "X_test = X_test.toarray()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# Let's build our model\n", "model = XGBClassifier()\n", "\n", "# A gridsearch to find the best parameters\n", "parameters = {\n", " \"n_bits\": [2, 3],\n", " \"max_depth\": [1],\n", " \"n_estimators\": [10, 30, 50],\n", " \"n_jobs\": [-1],\n", "}" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
       "                         'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
       "             scoring='accuracy')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" ], "text/plain": [ "GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n", " scoring='accuracy')" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Run the gridsearch\n", "grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n", "grid_search.fit(X_train, y_train)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best score: 0.6842744383727991\n", "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n" ] } ], "source": [ "# Check the accuracy of the best model\n", "print(f\"Best score: {grid_search.best_score_}\")\n", "\n", "# Check best hyperparameters\n", "print(f\"Best parameters: {grid_search.best_params_}\")\n", "\n", "# Extract best model\n", "best_model = grid_search.best_estimator_" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.6810\n", "Average precision score for positive class: 0.5615\n", "Average precision score for negative class: 0.8349\n", "Average precision score for neutral class: 0.3820\n" ] } ], "source": [ "# Compute the average precision for each class\n", "y_proba_test_tfidf = best_model.predict_proba(X_test)\n", "\n", "# Compute accuracy\n", "y_pred_test_tfidf = numpy.argmax(y_proba_test_tfidf, axis=1)\n", "accuracy_tfidf = numpy.mean(y_pred_test_tfidf == y_test)\n", "print(f\"Accuracy: {accuracy_tfidf:.4f}\")\n", "\n", "y_pred_positive = y_proba_test_tfidf[:, 2]\n", "y_pred_negative = y_proba_test_tfidf[:, 0]\n", "y_pred_neutral = y_proba_test_tfidf[:, 1]\n", "\n", "ap_positive_tfidf = average_precision_score((y_test == 2), y_pred_positive)\n", "ap_negative_tfidf = average_precision_score((y_test == 0), y_pred_negative)\n", "ap_neutral_tfidf = average_precision_score((y_test == 1), y_pred_neutral)\n", "\n", "print(f\"Average precision score for positive class: \" f\"{ap_positive_tfidf:.4f}\")\n", "print(f\"Average precision score for negative class: \" f\"{ap_negative_tfidf:.4f}\")\n", "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_tfidf:.4f}\")" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive tweets (class 2):\n", "@united sent a DM just now. Thanks I am incredibly happy the fast response I got via Twitter than via customer care. Thank you\n", "@JetBlue Great Thank you, lets hope so! Could you please notify me if flight 2302 leaves JFK? Thank you again\n", "@AmericanAir Great, thanks. Followed.\n", "@SouthwestAir I continue to be amazed by the amazing customer service. Thank you SWA!\n", "@JetBlue Awesome thanks! Thanks for the quick response. You guys ROCK! :)\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative tweets (class 0):\n", "@USAirways been on hold 2 hours for a Cancelled Flighted flight. I understand the delay. I don't understand you auto-reFlight Booking Problems me on TUESDAY. HELP!\n", "@SouthwestAir 2 hours on hold for customer service never us SW again\n", "@SouthwestAir placed on hold for total of two hours today after flight was Cancelled Flightled. Online option not available. What to do?\n", "@southwestair I've been on hold for 2 hours to reschedule my Cancelled Flightled flight for the morning. What gives? I need help NOW\n", "@USAirways Customer service is dead. Last wk, flts delayed/Cancelled Flighted. Bags lost 4 days. Last nt, flt delayed/Cancelled Flighted. No meal voucher?\n" ] } ], "source": [ "# Let's see what are the top predictions based on the probabilities in y_pred_test\n", "print(\"5 most positive tweets (class 2):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_proba_test_tfidf[:, 2].argsort()[-1 - i]])\n", "\n", "print(\"-\" * 100)\n", "\n", "print(\"5 most negative tweets (class 0):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_proba_test_tfidf[:, 0].argsort()[-1 - i]])" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compilation time: 11.5009 seconds\n", "FHE inference time: 48.6880 seconds\n" ] } ], "source": [ "# Compile the model to get the FHE inference engine\n", "# (this may take a few minutes depending on the selected model)\n", "start = time.perf_counter()\n", "best_model.compile(X_train)\n", "end = time.perf_counter()\n", "print(f\"Compilation time: {end - start:.4f} seconds\")\n", "\n", "# Let's write a custom example and predict in FHE\n", "tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n", "X_tested_tweet = tfidf_vectorizer.transform(numpy.array(tested_tweet)).toarray()\n", "clear_proba = best_model.predict_proba(X_tested_tweet)\n", "\n", "# Now let's predict with FHE over a single tweet and print the time it takes\n", "start = time.perf_counter()\n", "decrypted_proba = best_model.predict_proba(X_tested_tweet, execute_in_fhe=True)\n", "end = time.perf_counter()\n", "print(f\"FHE inference time: {end - start:.4f} seconds\")" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Probabilities from the FHE inference: [[0.50224707 0.25647676 0.24127617]]\n", "Probabilities from the clear model: [[0.50224707 0.25647676 0.24127617]]\n" ] } ], "source": [ "print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n", "print(f\"Probabilities from the clear model: {clear_proba}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To sum up, \n", "- We trained a XGBoost model over TF-IDF representation of the tweets and their respective sentiment class. \n", "- The grid search gives us a model that achieves around ~70% accuracy.\n", "- Given the imbalance in the classes, we rather compute the average precision per class.\n", "\n", "Now we will see how we can approach the problem by leveraging the transformers power." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2. A transformer approach to text representation\n", "\n", "[**Transformers**](https://en.wikipedia.org/wiki/Transformer_(machine_learning_model\\)) are neural networks that are often trained to predict the next words to appear in a text (this is commonly called self-supervised learning). \n", "\n", "They are powerful tools for all kind of Natural Language Processing tasks but supporting a transformer model in FHE might not always be ideal as they are quite big models. However, we can still leverage their hidden representation for any text and feed it to a more FHE friendly machine learning model (in this notebook we will use XGBoost) for classification.\n", "\n", "Here we will use the transformer model from the amazing [**Huggingface**](https://huggingface.co/) repository." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of the model checkpoint at cardiffnlp/twitter-roberta-base-sentiment-latest were not used when initializing RobertaForSequenceClassification: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n", "- This IS expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", "- This IS NOT expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n" ] } ], "source": [ "import torch\n", "import tqdm\n", "from transformers import AutoModelForSequenceClassification, AutoTokenizer\n", "\n", "device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n", "\n", "# Load the tokenizer (converts text to tokens)\n", "tokenizer = AutoTokenizer.from_pretrained(\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n", "\n", "# Load the pre-trained model\n", "transformer_model = AutoModelForSequenceClassification.from_pretrained(\n", " \"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n", ")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 30/30 [00:33<00:00, 1.10s/it]\n" ] } ], "source": [ "# Let's first see what are the model performance by itself\n", "list_text_X_test = text_X_test.tolist()\n", "\n", "tokenized_text_X_test = tokenizer.batch_encode_plus(\n", " list_text_X_test, pad_to_max_length=True, return_tensors=\"pt\"\n", ")[\"input_ids\"]\n", "\n", "# Depending on the hardware used, the number of examples to be processed can be reduced\n", "# Here we split the data into 100 examples per batch\n", "tokenized_text_X_test_split = torch.split(tokenized_text_X_test, split_size_or_sections=50)\n", "transformer_model = transformer_model.to(device)\n", "\n", "outputs = []\n", "for tokenized_x_test in tqdm.tqdm(tokenized_text_X_test_split):\n", " tokenized_x = tokenized_x_test.to(device)\n", " output_batch = transformer_model(tokenized_x)[\"logits\"]\n", " output_batch = output_batch.detach().cpu().numpy()\n", " outputs.append(output_batch)\n", "\n", "outputs = numpy.concatenate(outputs, axis=0)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Predictions for the first 3 tweets:\n", " [[-2.3807464 -0.61802083 2.9900746 ]\n", " [ 2.0166504 0.4938078 -2.8006463 ]\n", " [ 2.3892698 0.1344364 -2.6873822 ]]\n" ] } ], "source": [ "# Let's see what the transformer model predicts\n", "print(f\"Predictions for the first 3 tweets:\\n {outputs[:3]}\")" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.8053\n", "Average precision score for positive class: 0.8548\n", "Average precision score for negative class: 0.9548\n", "Average precision score for neutral class: 0.6801\n" ] } ], "source": [ "# Compute the metrics for each class\n", "\n", "# Compute accuracy\n", "accuracy_transformer_only = numpy.mean(numpy.argmax(outputs, axis=1) == y_test)\n", "print(f\"Accuracy: {accuracy_transformer_only:.4f}\")\n", "\n", "y_pred_positive = outputs[:, 2]\n", "y_pred_negative = outputs[:, 0]\n", "y_pred_neutral = outputs[:, 1]\n", "\n", "ap_positive_transformer_only = average_precision_score((y_test == 2), y_pred_positive)\n", "ap_negative_transformer_only = average_precision_score((y_test == 0), y_pred_negative)\n", "ap_neutral_transformer_only = average_precision_score((y_test == 1), y_pred_neutral)\n", "\n", "print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_only:.4f}\")\n", "print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_only:.4f}\")\n", "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_only:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It looks like the transformer outperforms the model built on TF-IDF reprensentation.\n", "Unfortunately, running a transformer that big in FHE would be highly inefficient. \n", "\n", "Let's see if we can leverage transformer representation and train a FHE model for the given classification task. " ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 13176/13176 [07:20<00:00, 29.91it/s]\n", "100%|██████████| 1464/1464 [00:47<00:00, 30.75it/s]\n" ] } ], "source": [ "# Function that transforms a list of texts to their representation\n", "# learned by the transformer.\n", "def text_to_tensor(\n", " list_text_X_train: list,\n", " transformer_model: AutoModelForSequenceClassification,\n", " tokenizer: AutoTokenizer,\n", " device: str,\n", ") -> numpy.ndarray:\n", " # Tokenize each text in the list one by one\n", " tokenized_text_X_train_split = []\n", " for text_x_train in list_text_X_train:\n", " tokenized_text_X_train_split.append(tokenizer.encode(text_x_train, return_tensors=\"pt\"))\n", "\n", " # Send the model to the device\n", " transformer_model = transformer_model.to(device)\n", " output_hidden_states_list = []\n", "\n", " for tokenized_x in tqdm.tqdm(tokenized_text_X_train_split):\n", " # Pass the tokens through the transformer model and get the hidden states\n", " # Only keep the last hidden layer state for now\n", " output_hidden_states = transformer_model(tokenized_x.to(device), output_hidden_states=True)[\n", " 1\n", " ][-1]\n", " # Average over the tokens axis to get a representation at the text level.\n", " output_hidden_states = output_hidden_states.mean(dim=1)\n", " output_hidden_states = output_hidden_states.detach().cpu().numpy()\n", " output_hidden_states_list.append(output_hidden_states)\n", "\n", " return numpy.concatenate(output_hidden_states_list, axis=0)\n", "\n", "\n", "# Let's vectorize the text using the transformer\n", "list_text_X_train = text_X_train.tolist()\n", "list_text_X_test = text_X_test.tolist()\n", "\n", "X_train_transformer = text_to_tensor(list_text_X_train, transformer_model, tokenizer, device)\n", "X_test_transformer = text_to_tensor(list_text_X_test, transformer_model, tokenizer, device)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
       "             param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
       "                         'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
       "             scoring='accuracy')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" ], "text/plain": [ "GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n", " scoring='accuracy')" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Now we have a representation for each tweet, we can train a model on these.\n", "grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n", "grid_search.fit(X_train_transformer, y_train)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best score: 0.8378111718275654\n", "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n" ] } ], "source": [ "# Check the accuracy of the best model\n", "print(f\"Best score: {grid_search.best_score_}\")\n", "\n", "# Check best hyperparameters\n", "print(f\"Best parameters: {grid_search.best_params_}\")\n", "\n", "# Extract best model\n", "best_model = grid_search.best_estimator_" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.8504\n", "Average precision score for positive class: 0.8917\n", "Average precision score for negative class: 0.9597\n", "Average precision score for neutral class: 0.7341\n" ] } ], "source": [ "# Compute the metrics for each class\n", "\n", "y_proba = best_model.predict_proba(X_test_transformer)\n", "\n", "# Compute the accuracy\n", "y_pred = numpy.argmax(y_proba, axis=1)\n", "accuracy_transformer_xgboost = numpy.mean(y_pred == y_test)\n", "print(f\"Accuracy: {accuracy_transformer_xgboost:.4f}\")\n", "\n", "y_pred_positive = y_proba[:, 2]\n", "y_pred_negative = y_proba[:, 0]\n", "y_pred_neutral = y_proba[:, 1]\n", "\n", "ap_positive_transformer_xgboost = average_precision_score((y_test == 2), y_pred_positive)\n", "ap_negative_transformer_xgboost = average_precision_score((y_test == 0), y_pred_negative)\n", "ap_neutral_transformer_xgboost = average_precision_score((y_test == 1), y_pred_neutral)\n", "\n", "print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_xgboost:.4f}\")\n", "print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_xgboost:.4f}\")\n", "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_xgboost:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our FHE-friendly XGBoost model does 38% better than the XGBoost model built over TF-IDF representation of the text. Note that here we are still not using FHE and only evaluating the model.\n", "Interestingly, using XGBoost over the transformer representation of the text matches the performance of the transformer model alone." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive tweets (class 2):\n", "@SouthwestAir love them! Always get the best deals!\n", "@AmericanAir THANK YOU FOR ALL THE HELP! :P You guys are the best. #americanairlines #americanair\n", "@SouthwestAir - Great flight from Phoenix to Dallas tonight!Great service and ON TIME! Makes @timieyancey very happy! http://t.co/TkVCMhbPim\n", "@AmericanAir AA2416 on time and awesome flight. Great job American!\n", "@SouthwestAir AMAZING c/s today by SW thank you SO very much. This is the reason we fly you #southwest\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative tweets (class 0):\n", "@AmericanAir This entire process took sooooo long that no decent seats are left. #customerservice\n", "@USAirways Not only did u lose the flight plan! Now ur flight crew is FAA timed out! Thx for havin us sit on the tarmac for an hr! #Pathetic\n", "@United site errored out at last step of changing award. Now can't even pull up reservation. 60 minute wait time. Thanks @United!\n", "@united OKC ticket agent Roger McLarren(sp?) LESS than helpful with our Intl group travel problems Can't find a supervisor for help.\n", "@AmericanAir the dinner and called me \"hon\". Not the service I would expect from 1st class. #disappointed\n" ] } ], "source": [ "# Get probabilities predictions in clear\n", "y_pred_test = best_model.predict_proba(X_test_transformer)\n", "\n", "# Let's see what are the top predictions based on the probabilities in y_pred_test\n", "print(\"5 most positive tweets (class 2):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_pred_test[:, 2].argsort()[-1 - i]])\n", "\n", "print(\"-\" * 100)\n", "\n", "print(\"5 most negative tweets (class 0):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_pred_test[:, 0].argsort()[-1 - i]])" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive (predicted) tweets that are actually negative (ground truth class 0):\n", "@USAirways as far as being delayed goes… Looks like tailwinds are going to make up for it. Good news!\n", "@united thanks for the link, now finally arrived in Brussels, 9 h after schedule...\n", "@USAirways your saving grace was our flight attendant Dallas who was amazing. wish he would transfer to Delta where I would see him again\n", "@AmericanAir that luggage you forgot...#mia.....he just won an oscar😄💝💝💝\n", "@united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative (predicted) tweets that are actually positive (ground truth class 2):\n", "@united thanks for updating me about the 1+ hour delay the exact second I got to ATL. 🙅🙅🙅\n", "@JetBlue you don't remember our date Monday night back to NYC? #heartbroken\n", "@SouthwestAir save mile to visit family in 2015 and this will impact how many times I can see my mother. I planned and you change the rules\n", "@SouthwestAir hot stewardess flipped me off\n", "@SouthwestAir - We left iPad in a seat pocket. Filed lost item report. Received it exactly 1 week Late Flightr. Is that a record? #unbelievable\n" ] } ], "source": [ "# Now let's see where the model is wrong\n", "y_pred_test_0 = y_pred_test[y_test == 0]\n", "text_X_test_0 = text_X_test[y_test == 0]\n", "\n", "print(\"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\")\n", "for i in range(5):\n", " print(text_X_test_0.iloc[y_pred_test_0[:, 2].argsort()[-1 - i]])\n", "\n", "print(\"-\" * 100)\n", "\n", "y_pred_test_2 = y_pred_test[y_test == 2]\n", "text_X_test_2 = text_X_test[y_test == 2]\n", "print(\"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\")\n", "for i in range(5):\n", " print(text_X_test_2.iloc[y_pred_test_2[:, 0].argsort()[-1 - i]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interestingly, these misclassifications are not obvious and some actually look rather like mislabeled. Also, it seems that the model is having a hard time to find ironic tweets.\n", "\n", "Now we have our model trained which has some great accuracy. Let's have it predict over the encrypted representation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sentiment Analysis of the Tweet with Fully Homomorphic Encryption\n", "\n", "Now that we have our model ready for FHE inference and our data ready for encryption let's use the model in a privacy preserving manner with FHE." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compilation time: 12.6855 seconds\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 1/1 [00:00<00:00, 36.43it/s]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FHE inference time: 53.0192 seconds\n" ] } ], "source": [ "# Compile the model to get the FHE inference engine\n", "# (this may take a few minutes depending on the selected model)\n", "start = time.perf_counter()\n", "best_model.compile(X_train_transformer)\n", "end = time.perf_counter()\n", "print(f\"Compilation time: {end - start:.4f} seconds\")\n", "\n", "\n", "# Let's write a custom example and predict in FHE\n", "tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n", "X_tested_tweet = text_to_tensor(tested_tweet, transformer_model, tokenizer, device)\n", "clear_proba = best_model.predict_proba(X_tested_tweet)\n", "\n", "# Now let's predict with FHE over a single tweet and print the time it takes\n", "start = time.perf_counter()\n", "decrypted_proba = best_model.predict_proba(X_tested_tweet, execute_in_fhe=True)\n", "end = time.perf_counter()\n", "fhe_exec_time = end - start\n", "print(f\"FHE inference time: {fhe_exec_time:.4f} seconds\")" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Probabilities from the FHE inference: [[0.08434131 0.05571389 0.8599448 ]]\n", "Probabilities from the clear model: [[0.08434131 0.05571389 0.8599448 ]]\n" ] } ], "source": [ "print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n", "print(f\"Probabilities from the clear model: {clear_proba}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's export the final model such that we can reuse it in a client/server environment\n", "\n", "# Export the model to ONNX\n", "onnx.save(best_model._onnx_model_, \"server_model.onnx\") # pylint: disable=protected-access\n", "\n", "# Export some data to be used for compilation\n", "X_train_numpy = X_train_transformer[:100]\n", "\n", "# Merge the two arrays in a pandas dataframe\n", "X_test_numpy_df = pd.DataFrame(X_train_numpy)\n", "\n", "# to csv\n", "X_test_numpy_df.to_csv(\"samples_for_compilation.csv\")\n", "\n", "# Let's save the model to be pushed to a server later\n", "from concrete.ml.deployment import FHEModelDev\n", "\n", "fhe_api = FHEModelDev(\"sentiment_fhe_model\", best_model)\n", "fhe_api.save()" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
AccuracyAverage Precision (positive)Average Precision (negative)Average Precision (neutral)
Model
TF-IDF + XGBoost0.6810110.5615210.8349140.382002
Transformer Only0.8053280.8548270.9548040.680110
Transformer + XGBoost0.8504100.8916910.9597470.734144
\n", "
" ], "text/plain": [ " Accuracy Average Precision (positive) \\\n", "Model \n", "TF-IDF + XGBoost 0.681011 0.561521 \n", "Transformer Only 0.805328 0.854827 \n", "Transformer + XGBoost 0.850410 0.891691 \n", "\n", " Average Precision (negative) \\\n", "Model \n", "TF-IDF + XGBoost 0.834914 \n", "Transformer Only 0.954804 \n", "Transformer + XGBoost 0.959747 \n", "\n", " Average Precision (neutral) \n", "Model \n", "TF-IDF + XGBoost 0.382002 \n", "Transformer Only 0.680110 \n", "Transformer + XGBoost 0.734144 " ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%matplotlib inline\n", "# Let's print the results obtained in this notebook\n", "df_results = pd.DataFrame(\n", " {\n", " \"Model\": [\"TF-IDF + XGBoost\", \"Transformer Only\", \"Transformer + XGBoost\"],\n", " \"Accuracy\": [accuracy_tfidf, accuracy_transformer_only, accuracy_transformer_xgboost],\n", " \"Average Precision (positive)\": [\n", " ap_positive_tfidf,\n", " ap_positive_transformer_only,\n", " ap_positive_transformer_xgboost,\n", " ],\n", " \"Average Precision (negative)\": [\n", " ap_negative_tfidf,\n", " ap_negative_transformer_only,\n", " ap_negative_transformer_xgboost,\n", " ],\n", " \"Average Precision (neutral)\": [\n", " ap_neutral_tfidf,\n", " ap_neutral_transformer_only,\n", " ap_neutral_transformer_xgboost,\n", " ],\n", " }\n", ")\n", "df_results.set_index(\"Model\", inplace=True)\n", "df_results # pylint: disable=pointless-statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conclusion\n", "\n", "In this notebook we presented two different ways to represent a text.\n", "1. Using TF-IDF vectorization\n", "2. Using the hidden layers from a transformer\n", "\n", "Both representation are then used to train a machine learning model will run in FHE (here XGBoost)\n", "\n", "Once the model is trained, clients can send encrypted text representation to the server to get a sentiment analysis done and they receive the probability for each class (negative, neutral and positive) in an encrypted format which can then be decrypted by the client. For now, all the FHE magic (encrypt, predict and decrypt) is done within the `predict_proba` function with the argument `execute_in_fhe=True`. In the next release, an API will be provided to split the server/client parts.\n", "\n", "Regarding the FHE execution times, the final XGboost model can predict over an encrypted data point in ~40 seconds. This will change depending on the number of threads available. In the future, more hardware acceleration will be available to speed up the execution time.\n", "\n", "It seems that the combination of a transformer (thanks Huggingface!) with a \"simpler\" model such as XGBoost works pretty well. Thanks to Concrete-ML library, we can easily use this text representation on the client machine and then encrypt it to send it to a remote server without having to deal with a transformer runtime in FHE." ] } ], "metadata": { "execution": { "timeout": 10800 } }, "nbformat": 4, "nbformat_minor": 2 }