{ "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": 21, "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": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "There are 400000 words in the vocabulary\n" ] } ], "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": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "torch.Size([400000, 100])" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "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": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }