{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Clustering for Transaction Classification\n",
    "\n",
    "This notebook covers use cases where your data is unlabelled but has features that can be used to cluster them into meaningful categories. The challenge with clustering is making the features that make those clusters stand out human-readable, and that is where we'll look to use GPT-3 to generate meaningful cluster descriptions for us. We can then use these to apply labels to a previously unlabelled dataset.\n",
    "\n",
    "To feed the model we use embeddings created using the approach displayed in the notebook [Multiclass classification for transactions Notebook](Multiclass_classification_for_transactions.ipynb), applied to the full 359 transactions in the dataset to give us a bigger pool for learning"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.manifold import TSNE\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "COMPLETIONS_MODEL = \"text-davinci-002\"\n",
    "\n",
    "# This path leads to a file with embeddings created in the notebook linked above\n",
    "embedding_path = 'data/transactions_with_embeddings_359.csv'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Clustering\n",
    "\n",
    "We'll reuse the approach from the [Clustering Notebook](Clustering.ipynb), using K-Means to cluster our dataset using the feature embeddings we created previously. We'll then use the Completions endpoint to generate cluster descriptions for us and judge their effectiveness"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(359, 2048)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "embedding_df = pd.read_csv(embedding_path)\n",
    "embedding_df[\"babbage_similarity\"] = embedding_df.babbage_similarity.apply(eval).apply(np.array)\n",
    "matrix = np.vstack(embedding_df.babbage_similarity.values)\n",
    "matrix.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_clusters = 5\n",
    "\n",
    "kmeans = KMeans(n_clusters=n_clusters, init=\"k-means++\", random_state=42)\n",
    "kmeans.fit(matrix)\n",
    "labels = kmeans.labels_\n",
    "embedding_df[\"Cluster\"] = labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'Clusters identified visualized in language 2d using t-SNE')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 29304 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "tsne = TSNE(\n",
    "    n_components=2, perplexity=15, random_state=42, init=\"random\", learning_rate=200\n",
    ")\n",
    "vis_dims2 = tsne.fit_transform(matrix)\n",
    "\n",
    "x = [x for x, y in vis_dims2]\n",
    "y = [y for x, y in vis_dims2]\n",
    "\n",
    "for category, color in enumerate([\"purple\", \"green\", \"red\", \"blue\",\"yellow\"]):\n",
    "    xs = np.array(x)[embedding_df.Cluster == category]\n",
    "    ys = np.array(y)[embedding_df.Cluster == category]\n",
    "    plt.scatter(xs, ys, color=color, alpha=0.3)\n",
    "\n",
    "    avg_x = xs.mean()\n",
    "    avg_y = ys.mean()\n",
    "\n",
    "    plt.scatter(avg_x, avg_y, marker=\"x\", color=color, s=100)\n",
    "plt.title(\"Clusters identified visualized in language 2d using t-SNE\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cluster 0 Theme:  Literary & Archival ItemsOne possible way to group these transactions into a meaningful cluster is by their theme or purpose. A common theme that appears in most of these transactions is literary and archival items, which suggests that these are payments for acquiring, preserving, or accessing various collections of books, manuscripts, papers, and other materials related to literature and history. This theme could be relevant for a library, a museum, a research institution, or a collector.Some possible indicators of this theme are:-\n",
      "JISC SERVICES LTD SUBSCRIPTION ACCOUNT, Annual Subscription\n",
      "   Private Sale, Literary & Archival Items\n",
      "   ALDL, Oct19-Dec19 charge from Agency for Legal Deposit Libraries\n",
      "   ALDL, Legal Deposit Services\n",
      "   Private Sale, Literary & Archival Items\n",
      "   SONYA LEONARD, Literary and personal papers of Tom Leonard 1961 to 2018\n",
      "   FROST AND SULLIVAN LTD, Literary & Archival Items\n",
      "   Cengage Learning (Emea )Ltd, Literary & Archival Items\n",
      "   Agency for the Legal Deposit Libraries, Agency services\n",
      "   Robert Harland, Correspondance and Literary papers - Thomas Carlyle\n",
      "   ----------------------------------------------------------------------------------------------------\n",
      "Cluster 1 Theme: There are different ways to approach the task of grouping transactions into meaningful clusters, but one possible theme that these transactions have in common is:- They are all payments to the same supplier, ECG Facilities Service, for various services related to facility management and maintenance.- They are all relatively large amounts, ranging from £27,013.16 to £125,000.00, with a mean of £54,798.67 and a standard deviation of £19,894.67.-\n",
      "ECG FACILITIES SERVICE, Maintenance contract - all properties\n",
      "   ECG, This payment covers 16 invoices including upgrade to boiler control panel & remedial works following 5 year test\n",
      "   ECG FACILITIES SERVICE, This payment covers multiple invoices for facility management fees\n",
      "   ECG FACILITIES SERVICE, CB Bolier Replacement (1),USP Batteries,Gutter Works & Cleaning of pigeon fouling\n",
      "   ECG FACILITIES SERVICE, Facilities Management Charge\n",
      "   ECG FACILITIES SERVICE, Facilities Management Charge\n",
      "   ECG Facilities Service, Facilities Management Charge\n",
      "   ECG FACILITIES SERVICE, Maintenance contract - August 21 period\n",
      "   ECG Facilities Service, Facilities Management Charge\n",
      "   ECG Facilities Service, Facilities Management Charge\n",
      "   ----------------------------------------------------------------------------------------------------\n",
      "Cluster 2 Theme: There are different ways to approach the task of grouping transactions into meaningful clusters, but one possible theme that these transactions have in common is:- They are all related to building or refurbishment projects at different locations in Edinburgh- They are all paid to either John Graham Construction Ltd or Arthur McKay Building Services, two contractors that provide similar services- They are all relatively large and consistent in value, ranging from around £27,000 to £125,000 per transaction\n",
      "John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   SJS Property Services, George IV Bridge Work\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   ARTHUR MCKAY BUILDING SERVICES, Causewayside Work\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   John Graham Construction Ltd, Causewayside Refurbishment\n",
      "   ----------------------------------------------------------------------------------------------------\n",
      "Cluster 3 Theme: There are different ways to approach the task of grouping transactions into meaningful clusters, and different criteria or methods may yield different results. However, one possible theme that these transactions have in common is that they are all related to operational costs or capital expenditures for a large organization, such as a university, a hospital, or a government agency. Some possible sub-themes or categories within this theme are:- Electricity and utility services (EDF, EDF Energy)- IT work, equipment, and software\n",
      "EDF, Electricity\n",
      "   m-hance, IT Work\n",
      "   EDF Energy, This payment covers 5 invoices for utility services\n",
      "   JISC Services Ltd, Managed router service charge annual subscription 01/04/22 to 31/03/23\n",
      "   ALDL, ALDL Charges\n",
      "   COMPUTACENTER UK, IT equipment\n",
      "\n",
      "   BSI, Subscription\n",
      "   PHOENIX SOFTWARE LTD, IT Hardware plus 5 year licence\n",
      "   AM Phillip, Vehicle Purchase\n",
      "   XMA SCOTLAND LTD, Purchase of IT equipment and renewal of maintenance agreement.  This payment covers 2 invoices\n",
      "   ----------------------------------------------------------------------------------------------------\n",
      "Cluster 4 Theme: There are different ways to approach the task of clustering transactions, and different criteria to define meaningful clusters, but one possible theme that these transactions have in common is:- They are all related to property or facility costs, such as rent, rates, service charges, or maintenance.- They are all paid to either Glasgow City Council, Glasgow Life, or City of Edinburgh Council, which are public sector organisations that manage or provide various services in Scotland.- They are all relatively large amounts, ranging from\n",
      "GLASGOW CITY COUNCIL, Kelvin Hall\n",
      "   XMA Scotland Ltd, Kelvin Hall\n",
      "   Creative Video Productions Ltd, Kelvin Hall\n",
      "   GLASGOW LIFE, Oct 20 to Dec 20 service charge - Kelvin Hall\n",
      "   CITY OF EDINBURGH COUNCIL, Rates for 33 Salisbury Place\n",
      "   Glasgow Life, Service Charges\n",
      "   City Of Edinburgh Council, Non Domestic Rates \n",
      "   Glasgow Life, Service charges\n",
      "   Glasgow Life, Kelvin Hall Service Charges\n",
      "   Glasgow City Council, Kelvin Hall\n",
      "   ----------------------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "# We'll read 10 transactions per cluster as we're expecting some variation\n",
    "transactions_per_cluster = 10\n",
    "\n",
    "for i in range(n_clusters):\n",
    "    print(f\"Cluster {i} Theme:\", end=\" \")\n",
    "\n",
    "    transactions = \"\\n\".join(\n",
    "        embedding_df[embedding_df.Cluster == i]\n",
    "        .combined.str.replace(\"Supplier: \", \"\")\n",
    "        .str.replace(\"Description: \", \":  \")\n",
    "        .str.replace(\"Value: \", \":  \")\n",
    "        .sample(transactions_per_cluster, random_state=42)\n",
    "        .values\n",
    "    )\n",
    "    response = openai.Completion.create(\n",
    "        engine=COMPLETIONS_MODEL,\n",
    "        # We'll include a prompt to instruct the model what sort of description we're looking for\n",
    "        prompt=f'''We want to group these transactions into meaningful clusters so we can target the areas we are spending the most money. \n",
    "                What do the following transactions have in common?\\n\\nTransactions:\\n\"\"\"\\n{transactions}\\n\"\"\"\\n\\nTheme:''',\n",
    "        temperature=0,\n",
    "        max_tokens=100,\n",
    "        top_p=1,\n",
    "        frequency_penalty=0,\n",
    "        presence_penalty=0,\n",
    "    )\n",
    "    print(response[\"choices\"][0][\"text\"].replace(\"\\n\", \"\"))\n",
    "\n",
    "    sample_cluster_rows = embedding_df[embedding_df.Cluster == i].sample(transactions_per_cluster, random_state=42)\n",
    "    for j in range(transactions_per_cluster):\n",
    "        print(sample_cluster_rows.Supplier.values[j], end=\", \")\n",
    "        print(sample_cluster_rows.Description.values[j], end=\"\\n   \")\n",
    "        #print(str(sample_cluster_rows.Value).values[j])\n",
    "\n",
    "    print(\"-\" * 100)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Conclusion\n",
    "\n",
    "We now have five new clusters that we can use to describe our data. Looking at the visualisation some of our clusters have some overlap and we'll need some tuning to get to the right place, but already we can see that GPT-3 has made some effective inferences. In particular, it picked up that items including legal deposits were related to literature archival, which is true but the model was given no clues on. Very cool, and with some tuning we can create a base set of clusters that we can then use with a multiclass classifier to generalise to other transactional datasets we might use."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
