{ "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": 1, "metadata": {}, "outputs": [], "source": [ "# Import the required packages\n", "import os\n", "import time\n", "from pathlib import Path\n", "\n", "import numpy\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": 2, "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", "# The dataset can be downloaded through the `download_data.sh` script, which requires to set up\n", "# Kaggle's CLI, or manually at https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment\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", "\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": 3, "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": 4, "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": 5, "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": 6, "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",
       "             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", " scoring='accuracy')" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Run the gridsearch\n", "grid_search = GridSearchCV(model, parameters, cv=3, scoring=\"accuracy\")\n", "grid_search.fit(X_train, y_train)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best score: 0.705980570734669\n", "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50}\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": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.7117\n", "Average precision score for positive class: 0.6404\n", "Average precision score for negative class: 0.8719\n", "Average precision score for neutral class: 0.4349\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": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_pred_test_tfidf[y_pred_test_tfidf == 2]" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive tweets (class 2):\n", "@JetBlue do bags still fly free or have you started charging? thanks!\n", "@SouthwestAir Is there a way to receive a refund on a trip that was Cancelled Flight online instead of calling? Your phone lines are super busy.\n", "@JetBlue bag is supposedly here in Boston\n", "@AmericanAir Cancelled Flights my flight, doesn't send an email, text or call. Now I'm stranded in Louisville.\n", "@SouthwestAir I need to Cancelled Flight one leg of a flight, but can't seem to do this online. Been on hold on the phone for 10 minutes. Any help?\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative tweets (class 0):\n", "@AmericanAir - keeping AA up in the Air! My crew chief cousin Alex Espinosa in DFW! http://t.co/0HXLNvZknP\n", "@JetBlue Called JB 3 times!Everytime, Auto Vmsg:\"your wait time should not be longer than 9 mins\" waited longer than 18 mins and no answer!\n", "@SouthwestAir can you outline the policies for both scenarios?\n", "@united is not a company that values it's customer & after reading tweets to them I'm not the only one who feels that way #lostmybusiness\n", "@JetBlue how about free wifi on flt 1254 out of PBI to make up for 2.5 hr delay? Treat us right.\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_pred_test_tfidf[y_pred_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_pred_test_tfidf[y_pred_test_tfidf==0].argsort()[-1 - i]])" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compilation time: 5.3550 seconds\n", "FHE inference time: 1.1162 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, fhe=\"execute\")\n", "end = time.perf_counter()\n", "print(f\"FHE inference time: {end - start:.4f} seconds\")" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Probabilities from the FHE inference: [[0.30244059 0.17506451 0.5224949 ]]\n", "Probabilities from the clear model: [[0.30244059 0.17506451 0.5224949 ]]\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": 13, "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.weight', 'roberta.pooler.dense.bias']\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": 14, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n", "To disable this warning, you can either:\n", "\t- Avoid using `tokenizers` before the fork if possible\n", "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n", " 0%| | 0/30 [00:00 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": 18, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1), n_jobs=1,\n",
       "             param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
       "                         'n_estimators': [10, 30, 50]},\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_jobs=1,\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')" ] }, "execution_count": 18, "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": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best score: 0.8381147540983607\n", "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50}\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": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.8463\n", "Average precision score for positive class: 0.8959\n", "Average precision score for negative class: 0.9647\n", "Average precision score for neutral class: 0.7449\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": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive tweets (class 2):\n", "@united I think this is the best first class I have ever gotten!! Denver to LAX and it's wonderful!!!\n", "@AmericanAir Flight 236 was great. Fantastic cabin crew. A+ landing. #thankyou #JFK http://t.co/dRW08djHAI\n", "@SouthwestAir Jason (108639) at Gate #3 in SAN made my afternoon!!! #southwestairlines #stellarservice #thanks!\n", "@SouthwestAir love them! Always get the best deals!\n", "@AmericanAir simply amazing. Smiles for miles.Thank u for my upgrade tomorrow for ORD.We are spending a lot of time together next few weeks!\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative tweets (class 0):\n", "@united first you lost all my bags, now you Cancelled Flight my flight home. 30 min wait to talk to somebody #poorservice #notgoodenough\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", "@AmericanAir Phone just disconnects if you stay on the line. Need to checkout of hotel in 2 hrs & have no place to go. Can't keep calling.\n", "@VirginAmerica I have lots of flights to book and your site it not working!!!! I've been on the phone waiting for over 10 minutes..........\n", "@united 3 hour delay plus a jetway that won't move. This biz traveler is never flying u again!\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": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive (predicted) tweets that are actually negative (ground truth class 0):\n", "@united thanks for the link, now finally arrived in Brussels, 9 h after schedule...\n", "@USAirways as far as being delayed goes… Looks like tailwinds are going to make up for it. Good news!\n", "@united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted\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", "----------------------------------------------------------------------------------------------------\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", "@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", "@JetBlue you don't remember our date Monday night back to NYC? #heartbroken\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": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compilation time: 5.8594 seconds\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 1/1 [00:00<00:00, 17.16it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FHE inference time: 0.9319 seconds\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\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, fhe=\"execute\")\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": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Probabilities from the FHE inference: [[0.05162184 0.04558276 0.90279541]]\n", "Probabilities from the clear model: [[0.05162184 0.04558276 0.90279541]]\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": 26, "metadata": {}, "outputs": [], "source": [ "DEPLOYMENT_DIR = Path(\"deployment\")\n", "DEPLOYMENT_DIR.mkdir(exist_ok=True)\n", "\n", "# Let's export the final model such that we can reuse it in a client/server environment\n", "\n", "# Serialize the model (for development only)\n", "with (DEPLOYMENT_DIR / \"serialized_model\").open(\"w\") as file:\n", " best_model.dump(file)\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(DEPLOYMENT_DIR / \"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(DEPLOYMENT_DIR / \"sentiment_fhe_model\", best_model)\n", "fhe_api.save(via_mlir=True)" ] }, { "cell_type": "code", "execution_count": 27, "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.7117490.6404220.8718910.43486
Transformer Only0.8053280.8548270.9548040.68011
Transformer + XGBoost0.8463110.8959300.9646740.74489
\n", "
" ], "text/plain": [ " Accuracy Average Precision (positive) \\\n", "Model \n", "TF-IDF + XGBoost 0.711749 0.640422 \n", "Transformer Only 0.805328 0.854827 \n", "Transformer + XGBoost 0.846311 0.895930 \n", "\n", " Average Precision (negative) \\\n", "Model \n", "TF-IDF + XGBoost 0.871891 \n", "Transformer Only 0.954804 \n", "Transformer + XGBoost 0.964674 \n", "\n", " Average Precision (neutral) \n", "Model \n", "TF-IDF + XGBoost 0.43486 \n", "Transformer Only 0.68011 \n", "Transformer + XGBoost 0.74489 " ] }, "execution_count": 27, "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 }, "kernelspec": { "display_name": ".venv", "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.10.11" } }, "nbformat": 4, "nbformat_minor": 2 }