{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6c040d34",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gensim.downloader as api\n",
    "import time\n",
    "from gensim.models import Word2Vec\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from web.datasets.similarity import *\n",
    "from scipy.stats import kendalltau, spearmanr\n",
    "import seaborn as sns\n",
    "\n",
    "import sys\n",
    "sys.path += ['utils/']  \n",
    "\n",
    "from word_embedding import * \n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6fbe968d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# df = pd.read_csv('Bkp_vars/norm_enwik9')\n",
    "# X = df.values\n",
    "# del df\n",
    "# text = [x[0].split(' ') for x in X]\n",
    "\n",
    "dataset = api.load('text8')\n",
    "text = [a for a in dataset]\n",
    "\n",
    "# dataset = api.load('fake-news')\n",
    "# text = [a['text'].split(' ') for a in dataset]\n",
    "# text = text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ccdcde3c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1701"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "88a6e7e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text pre-processing\n",
      "Get the probability matrix\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=8)]: Using backend LokyBackend with 8 concurrent workers.\n",
      "[Parallel(n_jobs=8)]: Done   3 out of   8 | elapsed:    2.5s remaining:    4.2s\n",
      "[Parallel(n_jobs=8)]: Done   5 out of   8 | elapsed:    2.9s remaining:    1.7s\n",
      "[Parallel(n_jobs=8)]: Done   8 out of   8 | elapsed:    3.7s finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time elapsed before optimization: 11.283543109893799\n",
      "Computing the embedding\n",
      "Running the optimization for k = 1\n",
      "[========================>] 100%\n",
      "Running W2Vec\n"
     ]
    }
   ],
   "source": [
    "dim = 32\n",
    "n_epochs = 10\n",
    "η = .8\n",
    "γ = 0.75\n",
    "min_count = 10\n",
    "\n",
    "t0 = time()\n",
    "res, word2idx = WordEmbedding(text, dim = dim, γ = γ, n_epochs = n_epochs, verbose = True, \n",
    "                            min_count = min_count, η = η, n_jobs = 8, sym = True,\n",
    "                            window_size = 1)\n",
    "\n",
    "X = res.X\n",
    "all_words = list(word2idx.keys())\n",
    "\n",
    "\n",
    "t = time() - t0\n",
    "\n",
    "\n",
    "t0 = time()\n",
    "print('\\nRunning W2Vec')\n",
    "model = Word2Vec(sentences = text, size = dim, min_count = min_count, window = 5,\n",
    "                    workers = 8, sample = 1e-5, iter = 2)\n",
    "\n",
    "tns = time() - t0\n",
    "\n",
    "\n",
    "# Y = np.array([model.wv.get_vector(w) for w in model.wv.key_to_index.keys()])\n",
    "words_gensim = model.wv.index2word\n",
    "Y = np.array([model[word] for word in words_gensim])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6a97898b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.4315499265777601e-13\n",
      "1.4315499265777601e-13\n",
      "0.0009429364585869775\n",
      "0.0009429364585869775\n",
      "9.07093959460111e-06\n",
      "9.07093959460111e-06\n",
      "0.1928888900645218\n",
      "0.1928888900645218\n",
      "0.0038914779604949\n",
      "0.0038914779604949\n"
     ]
    }
   ],
   "source": [
    "datasets = [fetch_MEN(which = 'test'), fetch_WS353(which = 'similarity'), fetch_TR9856(),\n",
    "            fetch_RG65(), fetch_MTurk()]\n",
    "\n",
    "\n",
    "# X = res.X\n",
    "# Y = np.array([model.wv.get_vector(w) for w in model.wv.key_to_index.keys()])\n",
    "# Y = normalize(Y, norm = 'l2', axis = 1)\n",
    "\n",
    "\n",
    "v1 = []\n",
    "v2 = []\n",
    "\n",
    "for ds in datasets:\n",
    "\n",
    "    w1 = ds['X'][:,0]\n",
    "    w2 = ds['X'][:,1]\n",
    "    score = ds['y']\n",
    "\n",
    "    sim = []\n",
    "    nsim = []\n",
    "    sscore = []\n",
    "\n",
    "    for x, y, s in zip(w1, w2, score):\n",
    "        if x in all_words and y in all_words:\n",
    "            try: \n",
    "                sim.append(X[all_words.index(x)]@X[all_words.index(y)])\n",
    "                nsim.append(Y[words_gensim.index(x)]@Y[words_gensim.index(y)])\n",
    "                sscore.append(s)\n",
    "            except:\n",
    "                pass\n",
    "\n",
    "    r, p = spearmanr(sim, sscore)\n",
    "    print(p)\n",
    "    v1.append(r)\n",
    "    \n",
    "    r, _ = spearmanr(nsim, sscore)\n",
    "    print(p)\n",
    "    v2.append(r)                                            \n",
    "\n",
    "\n",
    "columns = ['MEN', 'WS353', 'TR9856', 'RG65', 'MTurk', 't']\n",
    "df = pd.DataFrame(columns = columns)\n",
    "df = pd.concat([df, pd.Series(dict(zip(columns, np.concatenate([v1, [t]])))).to_frame().T], ignore_index = True)\n",
    "df = pd.concat([df, pd.Series(dict(zip(columns, np.concatenate([v2, [tns]])))).to_frame().T], ignore_index = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd4f37fd",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6517ea8",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b97cce7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03c3d669",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "2ac1ed17",
   "metadata": {},
   "outputs": [
    {
     "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>MEN</th>\n",
       "      <th>WS353</th>\n",
       "      <th>TR9856</th>\n",
       "      <th>RG65</th>\n",
       "      <th>MTurk</th>\n",
       "      <th>t</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.230921</td>\n",
       "      <td>0.234415</td>\n",
       "      <td>0.116942</td>\n",
       "      <td>0.163587</td>\n",
       "      <td>0.1702</td>\n",
       "      <td>424.24221</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.576455</td>\n",
       "      <td>0.671875</td>\n",
       "      <td>0.503004</td>\n",
       "      <td>0.563779</td>\n",
       "      <td>0.618202</td>\n",
       "      <td>306.87485</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        MEN     WS353    TR9856      RG65     MTurk          t\n",
       "0  0.230921  0.234415  0.116942  0.163587    0.1702  424.24221\n",
       "1  0.576455  0.671875  0.503004  0.563779  0.618202  306.87485"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d94885ff",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
