thesis-prediction-ml/demo03-GLOVE_WordEmbeddings_Analogies_ClosestWords.ipynb
Shoney Arickathil f1558690f9 word embedding
2023-05-02 13:54:12 +02:00

534 lines
27 KiB
Text

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### GloVe vectors\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Embeddings transform a one-hot encoded vector (a vector that is 0 in elements except one, which is 1) into a much smaller dimension vector of real numbers. The one-hot encoded vector is also known as a sparse vector, whilst the real valued vector is known as a dense vector.\n",
"\n",
"The key concept in these word embeddings is that words that appear in similar contexts appear nearby in the vector space, i.e. the Euclidean distance between these two word vectors is small.\n",
"\n",
"https://github.com/spro/practical-pytorch/blob/master/glove-word-vectors/glove-word-vectors.ipynb"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torchtext.vocab"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Load GloVe vectors\n",
"First, we'll load the GloVe vectors. The name field specifies what the vectors have been trained on, here the 6B means a corpus of 6 billion words."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
".vector_cache/glove.6B.zip: 0.00B [00:10, ?B/s]\n"
]
},
{
"ename": "URLError",
"evalue": "<urlopen error [Errno -3] Temporary failure in name resolution>",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mgaierror\u001b[0m Traceback (most recent call last)",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:1346\u001b[0m, in \u001b[0;36mAbstractHTTPHandler.do_open\u001b[0;34m(self, http_class, req, **http_conn_args)\u001b[0m\n\u001b[1;32m 1345\u001b[0m \u001b[39mtry\u001b[39;00m:\n\u001b[0;32m-> 1346\u001b[0m h\u001b[39m.\u001b[39;49mrequest(req\u001b[39m.\u001b[39;49mget_method(), req\u001b[39m.\u001b[39;49mselector, req\u001b[39m.\u001b[39;49mdata, headers,\n\u001b[1;32m 1347\u001b[0m encode_chunked\u001b[39m=\u001b[39;49mreq\u001b[39m.\u001b[39;49mhas_header(\u001b[39m'\u001b[39;49m\u001b[39mTransfer-encoding\u001b[39;49m\u001b[39m'\u001b[39;49m))\n\u001b[1;32m 1348\u001b[0m \u001b[39mexcept\u001b[39;00m \u001b[39mOSError\u001b[39;00m \u001b[39mas\u001b[39;00m err: \u001b[39m# timeout error\u001b[39;00m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1279\u001b[0m, in \u001b[0;36mHTTPConnection.request\u001b[0;34m(self, method, url, body, headers, encode_chunked)\u001b[0m\n\u001b[1;32m 1278\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"Send a complete request to the server.\"\"\"\u001b[39;00m\n\u001b[0;32m-> 1279\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_send_request(method, url, body, headers, encode_chunked)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1325\u001b[0m, in \u001b[0;36mHTTPConnection._send_request\u001b[0;34m(self, method, url, body, headers, encode_chunked)\u001b[0m\n\u001b[1;32m 1324\u001b[0m body \u001b[39m=\u001b[39m _encode(body, \u001b[39m'\u001b[39m\u001b[39mbody\u001b[39m\u001b[39m'\u001b[39m)\n\u001b[0;32m-> 1325\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mendheaders(body, encode_chunked\u001b[39m=\u001b[39;49mencode_chunked)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1274\u001b[0m, in \u001b[0;36mHTTPConnection.endheaders\u001b[0;34m(self, message_body, encode_chunked)\u001b[0m\n\u001b[1;32m 1273\u001b[0m \u001b[39mraise\u001b[39;00m CannotSendHeader()\n\u001b[0;32m-> 1274\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_send_output(message_body, encode_chunked\u001b[39m=\u001b[39;49mencode_chunked)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:1034\u001b[0m, in \u001b[0;36mHTTPConnection._send_output\u001b[0;34m(self, message_body, encode_chunked)\u001b[0m\n\u001b[1;32m 1033\u001b[0m \u001b[39mdel\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_buffer[:]\n\u001b[0;32m-> 1034\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49msend(msg)\n\u001b[1;32m 1036\u001b[0m \u001b[39mif\u001b[39;00m message_body \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 1037\u001b[0m \n\u001b[1;32m 1038\u001b[0m \u001b[39m# create a consistent interface to message_body\u001b[39;00m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:974\u001b[0m, in \u001b[0;36mHTTPConnection.send\u001b[0;34m(self, data)\u001b[0m\n\u001b[1;32m 973\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mauto_open:\n\u001b[0;32m--> 974\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mconnect()\n\u001b[1;32m 975\u001b[0m \u001b[39melse\u001b[39;00m:\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/http/client.py:945\u001b[0m, in \u001b[0;36mHTTPConnection.connect\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 944\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"Connect to the host and port specified in __init__.\"\"\"\u001b[39;00m\n\u001b[0;32m--> 945\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39msock \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_create_connection(\n\u001b[1;32m 946\u001b[0m (\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mhost,\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mport), \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mtimeout, \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49msource_address)\n\u001b[1;32m 947\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39msock\u001b[39m.\u001b[39msetsockopt(socket\u001b[39m.\u001b[39mIPPROTO_TCP, socket\u001b[39m.\u001b[39mTCP_NODELAY, \u001b[39m1\u001b[39m)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/socket.py:823\u001b[0m, in \u001b[0;36mcreate_connection\u001b[0;34m(address, timeout, source_address)\u001b[0m\n\u001b[1;32m 822\u001b[0m err \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n\u001b[0;32m--> 823\u001b[0m \u001b[39mfor\u001b[39;00m res \u001b[39min\u001b[39;00m getaddrinfo(host, port, \u001b[39m0\u001b[39;49m, SOCK_STREAM):\n\u001b[1;32m 824\u001b[0m af, socktype, proto, canonname, sa \u001b[39m=\u001b[39m res\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/socket.py:954\u001b[0m, in \u001b[0;36mgetaddrinfo\u001b[0;34m(host, port, family, type, proto, flags)\u001b[0m\n\u001b[1;32m 953\u001b[0m addrlist \u001b[39m=\u001b[39m []\n\u001b[0;32m--> 954\u001b[0m \u001b[39mfor\u001b[39;00m res \u001b[39min\u001b[39;00m _socket\u001b[39m.\u001b[39;49mgetaddrinfo(host, port, family, \u001b[39mtype\u001b[39;49m, proto, flags):\n\u001b[1;32m 955\u001b[0m af, socktype, proto, canonname, sa \u001b[39m=\u001b[39m res\n",
"\u001b[0;31mgaierror\u001b[0m: [Errno -3] Temporary failure in name resolution",
"\nDuring handling of the above exception, another exception occurred:\n",
"\u001b[0;31mURLError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[5], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m glove \u001b[39m=\u001b[39m torchtext\u001b[39m.\u001b[39;49mvocab\u001b[39m.\u001b[39;49mGloVe(name\u001b[39m=\u001b[39;49m\u001b[39m'\u001b[39;49m\u001b[39m6B\u001b[39;49m\u001b[39m'\u001b[39;49m, dim\u001b[39m=\u001b[39;49m\u001b[39m100\u001b[39;49m)\n\u001b[1;32m 3\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mf\u001b[39m\u001b[39m'\u001b[39m\u001b[39mThere are \u001b[39m\u001b[39m{\u001b[39;00m\u001b[39mlen\u001b[39m(glove\u001b[39m.\u001b[39mitos)\u001b[39m}\u001b[39;00m\u001b[39m words in the vocabulary\u001b[39m\u001b[39m'\u001b[39m)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torchtext/vocab/vectors.py:220\u001b[0m, in \u001b[0;36mGloVe.__init__\u001b[0;34m(self, name, dim, **kwargs)\u001b[0m\n\u001b[1;32m 218\u001b[0m url \u001b[39m=\u001b[39m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39murl[name]\n\u001b[1;32m 219\u001b[0m name \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mglove.\u001b[39m\u001b[39m{}\u001b[39;00m\u001b[39m.\u001b[39m\u001b[39m{}\u001b[39;00m\u001b[39md.txt\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m.\u001b[39mformat(name, \u001b[39mstr\u001b[39m(dim))\n\u001b[0;32m--> 220\u001b[0m \u001b[39msuper\u001b[39;49m(GloVe, \u001b[39mself\u001b[39;49m)\u001b[39m.\u001b[39;49m\u001b[39m__init__\u001b[39;49m(name, url\u001b[39m=\u001b[39;49murl, \u001b[39m*\u001b[39;49m\u001b[39m*\u001b[39;49mkwargs)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torchtext/vocab/vectors.py:59\u001b[0m, in \u001b[0;36mVectors.__init__\u001b[0;34m(self, name, cache, url, unk_init, max_vectors)\u001b[0m\n\u001b[1;32m 57\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mdim \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n\u001b[1;32m 58\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39munk_init \u001b[39m=\u001b[39m torch\u001b[39m.\u001b[39mTensor\u001b[39m.\u001b[39mzero_ \u001b[39mif\u001b[39;00m unk_init \u001b[39mis\u001b[39;00m \u001b[39mNone\u001b[39;00m \u001b[39melse\u001b[39;00m unk_init\n\u001b[0;32m---> 59\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mcache(name, cache, url\u001b[39m=\u001b[39;49murl, max_vectors\u001b[39m=\u001b[39;49mmax_vectors)\n",
"File \u001b[0;32m~/devnlp/.venv/lib/python3.9/site-packages/torchtext/vocab/vectors.py:95\u001b[0m, in \u001b[0;36mVectors.cache\u001b[0;34m(self, name, cache, url, max_vectors)\u001b[0m\n\u001b[1;32m 93\u001b[0m \u001b[39mwith\u001b[39;00m tqdm(unit\u001b[39m=\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mB\u001b[39m\u001b[39m\"\u001b[39m, unit_scale\u001b[39m=\u001b[39m\u001b[39mTrue\u001b[39;00m, miniters\u001b[39m=\u001b[39m\u001b[39m1\u001b[39m, desc\u001b[39m=\u001b[39mdest) \u001b[39mas\u001b[39;00m t:\n\u001b[1;32m 94\u001b[0m \u001b[39mtry\u001b[39;00m:\n\u001b[0;32m---> 95\u001b[0m urlretrieve(url, dest, reporthook\u001b[39m=\u001b[39;49mreporthook(t))\n\u001b[1;32m 96\u001b[0m \u001b[39mexcept\u001b[39;00m \u001b[39mKeyboardInterrupt\u001b[39;00m \u001b[39mas\u001b[39;00m e: \u001b[39m# remove the partial zip file\u001b[39;00m\n\u001b[1;32m 97\u001b[0m os\u001b[39m.\u001b[39mremove(dest)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:239\u001b[0m, in \u001b[0;36murlretrieve\u001b[0;34m(url, filename, reporthook, data)\u001b[0m\n\u001b[1;32m 222\u001b[0m \u001b[39m\u001b[39m\u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 223\u001b[0m \u001b[39mRetrieve a URL into a temporary location on disk.\u001b[39;00m\n\u001b[1;32m 224\u001b[0m \n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 235\u001b[0m \u001b[39mdata file as well as the resulting HTTPMessage object.\u001b[39;00m\n\u001b[1;32m 236\u001b[0m \u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 237\u001b[0m url_type, path \u001b[39m=\u001b[39m _splittype(url)\n\u001b[0;32m--> 239\u001b[0m \u001b[39mwith\u001b[39;00m contextlib\u001b[39m.\u001b[39mclosing(urlopen(url, data)) \u001b[39mas\u001b[39;00m fp:\n\u001b[1;32m 240\u001b[0m headers \u001b[39m=\u001b[39m fp\u001b[39m.\u001b[39minfo()\n\u001b[1;32m 242\u001b[0m \u001b[39m# Just return the local path and the \"headers\" for file://\u001b[39;00m\n\u001b[1;32m 243\u001b[0m \u001b[39m# URLs. No sense in performing a copy unless requested.\u001b[39;00m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:214\u001b[0m, in \u001b[0;36murlopen\u001b[0;34m(url, data, timeout, cafile, capath, cadefault, context)\u001b[0m\n\u001b[1;32m 212\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[1;32m 213\u001b[0m opener \u001b[39m=\u001b[39m _opener\n\u001b[0;32m--> 214\u001b[0m \u001b[39mreturn\u001b[39;00m opener\u001b[39m.\u001b[39;49mopen(url, data, timeout)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:517\u001b[0m, in \u001b[0;36mOpenerDirector.open\u001b[0;34m(self, fullurl, data, timeout)\u001b[0m\n\u001b[1;32m 514\u001b[0m req \u001b[39m=\u001b[39m meth(req)\n\u001b[1;32m 516\u001b[0m sys\u001b[39m.\u001b[39maudit(\u001b[39m'\u001b[39m\u001b[39murllib.Request\u001b[39m\u001b[39m'\u001b[39m, req\u001b[39m.\u001b[39mfull_url, req\u001b[39m.\u001b[39mdata, req\u001b[39m.\u001b[39mheaders, req\u001b[39m.\u001b[39mget_method())\n\u001b[0;32m--> 517\u001b[0m response \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_open(req, data)\n\u001b[1;32m 519\u001b[0m \u001b[39m# post-process response\u001b[39;00m\n\u001b[1;32m 520\u001b[0m meth_name \u001b[39m=\u001b[39m protocol\u001b[39m+\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m_response\u001b[39m\u001b[39m\"\u001b[39m\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:534\u001b[0m, in \u001b[0;36mOpenerDirector._open\u001b[0;34m(self, req, data)\u001b[0m\n\u001b[1;32m 531\u001b[0m \u001b[39mreturn\u001b[39;00m result\n\u001b[1;32m 533\u001b[0m protocol \u001b[39m=\u001b[39m req\u001b[39m.\u001b[39mtype\n\u001b[0;32m--> 534\u001b[0m result \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_call_chain(\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mhandle_open, protocol, protocol \u001b[39m+\u001b[39;49m\n\u001b[1;32m 535\u001b[0m \u001b[39m'\u001b[39;49m\u001b[39m_open\u001b[39;49m\u001b[39m'\u001b[39;49m, req)\n\u001b[1;32m 536\u001b[0m \u001b[39mif\u001b[39;00m result:\n\u001b[1;32m 537\u001b[0m \u001b[39mreturn\u001b[39;00m result\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:494\u001b[0m, in \u001b[0;36mOpenerDirector._call_chain\u001b[0;34m(self, chain, kind, meth_name, *args)\u001b[0m\n\u001b[1;32m 492\u001b[0m \u001b[39mfor\u001b[39;00m handler \u001b[39min\u001b[39;00m handlers:\n\u001b[1;32m 493\u001b[0m func \u001b[39m=\u001b[39m \u001b[39mgetattr\u001b[39m(handler, meth_name)\n\u001b[0;32m--> 494\u001b[0m result \u001b[39m=\u001b[39m func(\u001b[39m*\u001b[39;49margs)\n\u001b[1;32m 495\u001b[0m \u001b[39mif\u001b[39;00m result \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 496\u001b[0m \u001b[39mreturn\u001b[39;00m result\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:1375\u001b[0m, in \u001b[0;36mHTTPHandler.http_open\u001b[0;34m(self, req)\u001b[0m\n\u001b[1;32m 1374\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mhttp_open\u001b[39m(\u001b[39mself\u001b[39m, req):\n\u001b[0;32m-> 1375\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mdo_open(http\u001b[39m.\u001b[39;49mclient\u001b[39m.\u001b[39;49mHTTPConnection, req)\n",
"File \u001b[0;32m~/.pyenv/versions/3.9.7/lib/python3.9/urllib/request.py:1349\u001b[0m, in \u001b[0;36mAbstractHTTPHandler.do_open\u001b[0;34m(self, http_class, req, **http_conn_args)\u001b[0m\n\u001b[1;32m 1346\u001b[0m h\u001b[39m.\u001b[39mrequest(req\u001b[39m.\u001b[39mget_method(), req\u001b[39m.\u001b[39mselector, req\u001b[39m.\u001b[39mdata, headers,\n\u001b[1;32m 1347\u001b[0m encode_chunked\u001b[39m=\u001b[39mreq\u001b[39m.\u001b[39mhas_header(\u001b[39m'\u001b[39m\u001b[39mTransfer-encoding\u001b[39m\u001b[39m'\u001b[39m))\n\u001b[1;32m 1348\u001b[0m \u001b[39mexcept\u001b[39;00m \u001b[39mOSError\u001b[39;00m \u001b[39mas\u001b[39;00m err: \u001b[39m# timeout error\u001b[39;00m\n\u001b[0;32m-> 1349\u001b[0m \u001b[39mraise\u001b[39;00m URLError(err)\n\u001b[1;32m 1350\u001b[0m r \u001b[39m=\u001b[39m h\u001b[39m.\u001b[39mgetresponse()\n\u001b[1;32m 1351\u001b[0m \u001b[39mexcept\u001b[39;00m:\n",
"\u001b[0;31mURLError\u001b[0m: <urlopen error [Errno -3] Temporary failure in name resolution>"
]
}
],
"source": [
"glove = torchtext.vocab.GloVe(name='6B', dim=100)\n",
"\n",
"print(f'There are {len(glove.itos)} words in the vocabulary')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In these set of GloVe vectors, every single word is lower-case only."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'glove' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[3], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m glove\u001b[39m.\u001b[39mvectors\u001b[39m.\u001b[39mshape\n",
"\u001b[0;31mNameError\u001b[0m: name 'glove' is not defined"
]
}
],
"source": [
"glove.vectors.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below implies that row 0 is the vector associated with the word 'the', row 1 for ',' (comma), row 2 for '.' (period), etc."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['the',\n",
" ',',\n",
" '.',\n",
" 'of',\n",
" 'to',\n",
" 'and',\n",
" 'in',\n",
" 'a',\n",
" '\"',\n",
" \"'s\",\n",
" 'for',\n",
" '-',\n",
" 'that',\n",
" 'on',\n",
" 'is']"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"glove.itos[:15]"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'glove' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[4], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m glove\u001b[39m.\u001b[39mstoi[\u001b[39m'\u001b[39m\u001b[39mthe\u001b[39m\u001b[39m'\u001b[39m]\n",
"\u001b[0;31mNameError\u001b[0m: name 'glove' is not defined"
]
}
],
"source": [
"glove.stoi['the']"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"36623"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"glove.stoi['dazzle']"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"43165"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"glove.stoi['shenanigans']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### we'll create a function that takes in word embeddings and a word and returns the associated vector. It'll also throw an error if the word doesn't exist in the vocabulary."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"def get_vector(embeddings, word):\n",
" \n",
" assert word in embeddings.stoi, f'*{word}* is not in the vocab!'\n",
" \n",
" return embeddings.vectors[embeddings.stoi[word]]"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([-0.8503, 0.3336, -0.6589, -0.4987, 0.3659, -0.1925, 0.2566, -0.0534,\n",
" 0.3147, 0.2443, 0.2934, -0.4492, 0.1517, 0.3931, -0.3179, 0.0605,\n",
" 0.8177, -0.3885, 0.7676, -1.1041, -0.1544, 0.3165, -0.3724, -0.1148,\n",
" 0.5163, -0.3929, 0.1630, -0.2532, -0.5098, 0.1520, 0.2781, 0.5252,\n",
" -0.3882, -0.3472, -0.6182, 0.1702, 0.1225, -0.2419, -0.3888, -0.5318,\n",
" -0.4699, -0.7050, -0.6213, -0.3869, -0.8564, -0.4100, -0.4749, -0.2108,\n",
" -0.8134, -0.5240, 0.4989, 0.3791, 0.5543, 1.1230, -0.4212, -1.5674,\n",
" -0.5689, 0.4082, 1.7949, 0.1686, -0.0029, 0.2879, -0.9009, -0.0942,\n",
" 0.7999, -0.3910, 0.7629, 0.7131, 0.1319, -0.4076, -0.1869, 0.8956,\n",
" 0.4687, -0.0029, 0.0253, 1.0084, 0.1714, 0.5974, -1.1003, 0.4931,\n",
" 0.4178, 0.1728, -0.4947, 0.0878, -0.9669, -1.0920, 0.3390, -0.5129,\n",
" 0.2464, 0.2714, 0.2421, -0.2171, 0.5504, 0.0082, -0.4557, 0.1353,\n",
" -0.0431, -0.4141, 0.7005, 0.1877])"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_vector(glove, 'paper')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want to find the words similar to a certain input word, we first find the vector of this input word, then we scan through our vocabulary finding any vectors similar to this input word vector.\n",
"\n",
"The function below returns the closest 6 words to an input word vector:"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"def closest(embeddings, vector, n = 6):\n",
" \n",
" distances = []\n",
" \n",
" for neighbor in embeddings.itos:\n",
" distances.append((neighbor, torch.dist(vector, get_vector(embeddings, neighbor))))\n",
" \n",
" return sorted(distances, key = lambda x: x[1])[:n]"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('paper', tensor(0.)),\n",
" ('papers', tensor(3.8442)),\n",
" ('printed', tensor(4.1970)),\n",
" ('print', tensor(4.2666)),\n",
" ('sheet', tensor(4.3835)),\n",
" ('printing', tensor(4.4179))]"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"closest(glove, get_vector(glove, 'paper'))"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('shenanigans', tensor(0.)),\n",
" ('chicanery', tensor(2.3785)),\n",
" ('hijinks', tensor(2.6764)),\n",
" ('escapades', tensor(2.7821)),\n",
" ('machinations', tensor(2.8699)),\n",
" ('gamesmanship', tensor(2.9044))]"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"closest(glove, get_vector(glove, 'shenanigans'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we'll also create another function that will nicely print out the tuples returned by our closest function."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"def print_tuples(tuples):\n",
" \n",
" for t in tuples:\n",
" print('(%.4f) %s' % (t[1], t[0]))"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0.0000) stupendous\n",
"(2.5795) marvellous\n",
"(2.7539) frightful\n",
"(2.8506) stupefying\n",
"(2.8561) awe-inspiring\n",
"(2.9179) mind-blowing\n"
]
}
],
"source": [
"print_tuples(closest(glove, get_vector(glove, 'stupendous')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Analogies\n",
"\n",
"with a well-trained word vector space certain semantic relationships can be captured with regular vector arithmetic."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"def analogy(embeddings, w1, w2, w3, n = 6):\n",
" \n",
" print('\\n[%s : %s :: %s : ?]' % (w1, w2, w3))\n",
" \n",
" closest_words = closest(embeddings, \\\n",
" get_vector(embeddings, w2)\n",
" - get_vector(embeddings, w1) \\\n",
" + get_vector(embeddings, w3), \\\n",
" n + 3)\n",
" \n",
" closest_words = [x for x in closest_words if x[0] not in [w1, w2, w3]][:n]\n",
" \n",
" return closest_words"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"[moon : night :: sun : ?]\n",
"(5.7069) morning\n",
"(5.7276) afternoon\n",
"(5.8023) evening\n",
"(6.1410) hours\n",
"(6.2797) saturday\n",
"(6.3056) sunday\n"
]
}
],
"source": [
"print_tuples(analogy(glove, 'moon', 'night', 'sun'))"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"[fly : bird :: swim : ?]\n",
"(5.9754) swimming\n",
"(6.2409) shark\n",
"(6.4822) dolphin\n",
"(6.5421) whale\n",
"(6.6276) cat\n",
"(6.6457) gorilla\n"
]
}
],
"source": [
"print_tuples(analogy(glove, 'fly', 'bird', 'swim'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Interesting failure mode"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"[earth : moon :: sun : ?]\n",
"(6.2294) lee\n",
"(6.4125) kang\n",
"(6.4644) tan\n",
"(6.4757) yang\n",
"(6.4853) lin\n",
"(6.5220) chong\n"
]
}
],
"source": [
"print_tuples(analogy(glove, 'earth', 'moon', 'sun')) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}