{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "983ef639-fbf4-4912-b593-9cf08aeb11cd",
   "metadata": {},
   "source": [
    "# Visualizing embeddings in 3D"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c9ea9a8-675d-4e3a-a8f7-6f4563df84ad",
   "metadata": {},
   "source": [
    "The example uses [PCA](https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html) to reduce the dimensionality fo the embeddings from 2048 to 3. Then we can visualize the data points in a 3D plot. The small dataset `dbpedia_samples.jsonl` is curated by randomly sampling 200 samples from [DBpedia validation dataset](https://www.kaggle.com/danofer/dbpedia-classes?select=DBPEDIA_val.csv)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8df5f2c3-ddbb-4cc4-9205-4c0af1670562",
   "metadata": {},
   "source": [
    "### 1. Load the dataset and query embeddings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "133dfc2a-9dbd-4a5a-96fa-477272f7af5a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Categories of DBpedia samples: Artist                    21\n",
      "Film                      19\n",
      "Plant                     19\n",
      "OfficeHolder              18\n",
      "Company                   17\n",
      "NaturalPlace              16\n",
      "Athlete                   16\n",
      "Village                   12\n",
      "WrittenWork               11\n",
      "Building                  11\n",
      "Album                     11\n",
      "Animal                    11\n",
      "EducationalInstitution    10\n",
      "MeanOfTransportation       8\n",
      "Name: category, dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>text</th>\n",
       "      <th>category</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Morada Limited is a textile company based in ...</td>\n",
       "      <td>Company</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>The Armenian Mirror-Spectator is a newspaper ...</td>\n",
       "      <td>WrittenWork</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Mt. Kinka (金華山 Kinka-zan) also known as Kinka...</td>\n",
       "      <td>NaturalPlace</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Planning the Play of a Bridge Hand is a book ...</td>\n",
       "      <td>WrittenWork</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Wang Yuanping (born 8 December 1976) is a ret...</td>\n",
       "      <td>Athlete</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                text      category\n",
       "0   Morada Limited is a textile company based in ...       Company\n",
       "1   The Armenian Mirror-Spectator is a newspaper ...   WrittenWork\n",
       "2   Mt. Kinka (金華山 Kinka-zan) also known as Kinka...  NaturalPlace\n",
       "3   Planning the Play of a Bridge Hand is a book ...   WrittenWork\n",
       "4   Wang Yuanping (born 8 December 1976) is a ret...       Athlete"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "samples = pd.read_json(\"data/dbpedia_samples.jsonl\", lines=True)\n",
    "categories = sorted(samples[\"category\"].unique())\n",
    "print(\"Categories of DBpedia samples:\", samples[\"category\"].value_counts())\n",
    "samples.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "19874e3e-a216-48cc-a27b-acb73854d832",
   "metadata": {},
   "outputs": [],
   "source": [
    "from openai.embeddings_utils import get_embeddings\n",
    "# NOTE: The following code will send a query of batch size 200 to /embeddings, cost about $0.2\n",
    "matrix = get_embeddings(samples[\"text\"].to_list(), engine=\"text-similarity-babbage-001\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d410c268-d8a7-4979-887c-45b1d382dda9",
   "metadata": {},
   "source": [
    "### 2. Reduce the embedding dimensionality"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f5410068-f3da-490c-8576-48e84a8728de",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "pca = PCA(n_components=3)\n",
    "vis_dims = pca.fit_transform(matrix)\n",
    "samples[\"embed_vis\"] = vis_dims.tolist()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6565f57-59c6-4d36-a094-3cbbd9ddeb4c",
   "metadata": {},
   "source": [
    "### 3. Plot the embeddings of lower dimensionality"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b17caad3-f0de-4115-83eb-55434a132acc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x117919ac0>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d15cdcc507224a81a18a0c1f18292590",
       "version_major": 2,
       "version_minor": 0
      },
      "image/png": "[encoded data, 140208 characters]",
      "text/html": [
       "\n",
       "            <div style=\"display: inline-block;\">\n",
       "                <div class=\"jupyter-widgets widget-label\" style=\"text-align: center;\">\n",
       "                    Figure\n",
       "                </div>\n",
       "                <img src='data:image/png;base64,[encoded data, 140208 characters]' width=1000.0/>\n",
       "            </div>\n",
       "        "
      ],
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib widget\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "fig = plt.figure(figsize=(10, 5))\n",
    "ax = fig.add_subplot(projection='3d')\n",
    "cmap = plt.get_cmap(\"tab20\")\n",
    "\n",
    "# Plot each sample category individually such that we can set label name.\n",
    "for i, cat in enumerate(categories):\n",
    "    sub_matrix = np.array(samples[samples[\"category\"] == cat][\"embed_vis\"].to_list())\n",
    "    x=sub_matrix[:, 0]\n",
    "    y=sub_matrix[:, 1]\n",
    "    z=sub_matrix[:, 2]\n",
    "    colors = [cmap(i/len(categories))] * len(sub_matrix)\n",
    "    ax.scatter(x, y, zs=z, zdir='z', c=colors, label=cat)\n",
    "\n",
    "ax.set_xlabel('x')\n",
    "ax.set_ylabel('y')\n",
    "ax.set_zlabel('z')\n",
    "ax.legend(bbox_to_anchor=(1.1, 1))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.9 ('openai')",
   "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.9"
  },
  "vscode": {
   "interpreter": {
    "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
