{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualize word2vec embeddings in tensorboard"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.contrib.tensorboard.plugins import projector\n",
    "import numpy as np\n",
    "import gensim\n",
    "\n",
    "# import warnings\n",
    "# warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Train a small word2vec model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_file_name = 'wikipedia_small/wikipedia.txt'\n",
    "\n",
    "sentences = gensim.models.word2vec.LineSentence(text_file_name, limit=100000)\n",
    "\n",
    "model = gensim.models.Word2Vec(sentences, size=10, window=5, min_count=5, workers=4)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "max_size = len(model.wv.vocab)-1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w2v = np.zeros((max_size,model.layer1_size))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w2v"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"metadata.tsv\", 'wb') as file_metadata:\n",
    "    for i,word in enumerate(model.wv.index2word[:max_size]):\n",
    "        w2v[i] = model.wv[word]\n",
    "        file_metadata.write(word.encode('utf8') + '\\n')        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w2v"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = tf.InteractiveSession()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Let us create a 2D tensor called embedding that holds our embeddings.\n",
    "with tf.device(\"/cpu:0\"):\n",
    "    embedding = tf.Variable(w2v, trainable=False, name='embedding')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tf.global_variables_initializer().run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = 'tensorboard'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# let us create an object to Saver class which is actually used to \n",
    "#save and restore variables to and from our checkpoints\n",
    "saver = tf.train.Saver()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# using file writer, we can save our summaries and events to our event file.\n",
    "writer = tf.summary.FileWriter(path, sess.graph)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# adding into projector\n",
    "config = projector.ProjectorConfig()\n",
    "embed = config.embeddings.add()\n",
    "embed.tensor_name = 'embedding'\n",
    "embed.metadata_path = 'metadata.tsv'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Specify the width and height of a single thumbnail.\n",
    "projector.visualize_embeddings(writer, config)\n",
    "\n",
    "saver.save(sess, path+'/model.ckpt', global_step=max_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15rc1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
