{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "e1c43409", "metadata": {}, "outputs": [], "source": [ "# Not everything from this is used\n", "\n", "import numpy as np\n", "import pandas as pd\n", "from sklearn.datasets import fetch_openml\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import accuracy_score, log_loss\n", "from sklearn.preprocessing import LabelEncoder, StandardScaler\n", "from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\n", "\n", "import os\n", "import wget\n", "from pathlib import Path\n", "import shutil\n", "import gzip\n", "\n", "from matplotlib import pyplot as plt\n", "\n", "import torch\n", "from pytorch_tabnet.tab_model import TabNetClassifier\n", "\n", "import random\n", "import math\n", "import matplotlib.ticker as mtick" ] }, { "cell_type": "code", "execution_count": null, "id": "5a53e50b", "metadata": {}, "outputs": [], "source": [ "DATAPATH = \"../../../data/loan_tabnet_2f_oob/\"\n", "model_path = \"../models/loan-tabnet-2f.zip\"\n", "model_path_clean = \"../models/loan-tabnet-clean.zip\"\n", "\n", "backdoorFeatures = [\"grade\", \"sub_grade\"]\n", "backdoorTriggerValues = [8, 39]\n", "targetLabel = 0\n", "\n", "SAMPLESIZE = 10000\n", "\n", "device_name = \"cuda:0\"\n", "\n", "tlist = np.arange(0, 10, 1)\n", "tlist2 = np.arange(0, 44, 1)\n", "\n", "labels = [0, 1]" ] }, { "cell_type": "code", "execution_count": null, "id": "1d3d5144", "metadata": {}, "outputs": [], "source": [ "outPath = DATAPATH\n", "\n", "X_train = pd.read_pickle(outPath+\"X_train.pkl\")\n", "y_train = pd.read_pickle(outPath+\"y_train.pkl\")\n", "\n", "X_valid = pd.read_pickle(outPath+\"X_valid.pkl\")\n", "y_valid = pd.read_pickle(outPath+\"y_valid.pkl\")\n", "\n", "X_test = pd.read_pickle(outPath+\"X_test.pkl\")\n", "y_test = pd.read_pickle(outPath+\"y_test.pkl\")\n", "\n", "X_test_backdoor = pd.read_pickle(outPath+\"X_test_backdoor.pkl\")\n", "y_test_backdoor = pd.read_pickle(outPath+\"y_test_backdoor.pkl\")" ] }, { "cell_type": "code", "execution_count": null, "id": "ce9d0b65", "metadata": {}, "outputs": [], "source": [ "clf = TabNetClassifier(device_name = device_name)\n", "clf.load_model(model_path)\n", "\n", "clf_clean = TabNetClassifier(device_name = device_name)\n", "clf_clean.load_model(model_path_clean)" ] }, { "cell_type": "code", "execution_count": null, "id": "ce73e12f", "metadata": {}, "outputs": [], "source": [ "def GenerateBackdoorTrigger(df, backdoorFeature, backdoorValue):\n", " df[backdoorFeature] = backdoorValue\n", " return df\n" ] }, { "cell_type": "code", "execution_count": null, "id": "7dbadbe6", "metadata": {}, "outputs": [], "source": [ "def cmplot(triggerFeature, triggerValues, realValue, clean=False):\n", " plt.rcParams[\"figure.figsize\"] = (5.4, 3.2)\n", " \n", " p0 = []\n", " p1 = []\n", " \n", " for triggerValue in triggerValues:\n", " # Apply potential trigger\n", " X_test_triggertest = X_test.copy()\n", " X_test_triggertest = GenerateBackdoorTrigger(X_test_triggertest, triggerFeature, triggerValue)\n", " \n", " # Evaluate after trigger\n", " if clean:\n", " y_pred = clf_clean.predict(X_test_triggertest[:SAMPLESIZE].values)\n", " else:\n", " y_pred = clf.predict(X_test_triggertest[:SAMPLESIZE].values)\n", " \n", " cm = confusion_matrix(y_test[:SAMPLESIZE].values, y_pred, labels=labels)\n", " p0.append((cm[:, 0].sum()/SAMPLESIZE)*100)\n", " p1.append((cm[:, 1].sum()/SAMPLESIZE)*100)\n", " \n", " plt.plot(triggerValues, p0, label=\"0 (target)\")\n", " plt.plot(triggerValues, p1, label=\"1\")\n", " plt.legend(loc=\"upper left\", title=\"Class\")\n", " plt.ylim(0,101)\n", " ax = plt.gca()\n", " ax.yaxis.set_major_formatter(mtick.PercentFormatter(100, decimals=0))\n", " plt.axvline(x=realValue, color=\"grey\", ls='--')\n", " plt.xlabel(\"Trigger value\")\n", " plt.ylabel(\"Classification probability\")\n", " plt.title(\"Trigger sweep on\\n'\" + triggerFeature + \"'\")\n", " plt.show()\n", " " ] }, { "cell_type": "code", "execution_count": null, "id": "912949a5", "metadata": {}, "outputs": [], "source": [ "cmplot(backdoorFeatures[0], tlist, backdoorTriggerValues[0], clean=False)" ] }, { "cell_type": "code", "execution_count": null, "id": "ec6f6d9b", "metadata": {}, "outputs": [], "source": [ "cmplot(backdoorFeatures[0], tlist, backdoorTriggerValues[0], clean=True)" ] }, { "cell_type": "code", "execution_count": null, "id": "ca5846be", "metadata": {}, "outputs": [], "source": [ "cmplot(backdoorFeatures[1], tlist2, backdoorTriggerValues[1], clean=False)" ] }, { "cell_type": "code", "execution_count": null, "id": "dc6bd6f2", "metadata": {}, "outputs": [], "source": [ "cmplot(backdoorFeatures[1], tlist2, backdoorTriggerValues[1], clean=True)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.6" } }, "nbformat": 4, "nbformat_minor": 5 }