{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.5/dist-packages/sklearn/cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n",
      "  \"This module will be removed in 0.20.\", DeprecationWarning)\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import tensorflow as tf\n",
    "import re\n",
    "import numpy as np\n",
    "from sklearn.utils import shuffle\n",
    "from utils import *\n",
    "import time\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.cross_validation import train_test_split\n",
    "from unidecode import unidecode\n",
    "from tqdm import tqdm\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>label</th>\n",
       "      <th>text</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Negative</td>\n",
       "      <td>Lebih-lebih lagi dengan  kemudahan internet da...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Positive</td>\n",
       "      <td>boleh memberi teguran kepada parti tetapi perl...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Negative</td>\n",
       "      <td>Adalah membingungkan mengapa masyarakat Cina b...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Positive</td>\n",
       "      <td>Kami menurunkan defisit daripada 6.7 peratus p...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Negative</td>\n",
       "      <td>Ini masalahnya. Bukan rakyat, tetapi sistem</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      label                                               text\n",
       "0  Negative  Lebih-lebih lagi dengan  kemudahan internet da...\n",
       "1  Positive  boleh memberi teguran kepada parti tetapi perl...\n",
       "2  Negative  Adalah membingungkan mengapa masyarakat Cina b...\n",
       "3  Positive  Kami menurunkan defisit daripada 6.7 peratus p...\n",
       "4  Negative        Ini masalahnya. Bukan rakyat, tetapi sistem"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.read_csv('sentiment-news-bahasa-v5.csv')\n",
    "Y = LabelEncoder().fit_transform(df.label)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def textcleaning(string):\n",
    "    string = re.sub('http\\S+|www.\\S+', '',' '.join([i for i in string.split() if i.find('#')<0 and i.find('@')<0]))\n",
    "    string = unidecode(string).replace('.', '. ').replace(',', ', ')\n",
    "    string = re.sub('[^\\'\\\"A-Za-z\\- ]+', ' ', string)\n",
    "    return ' '.join([i for i in re.findall(\"[\\\\w']+|[;:\\-\\(\\)&.,!?\\\"]\", string) if len(i)>1]).lower()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(df.shape[0]):\n",
    "    df.iloc[i,1] = textcleaning(df.iloc[i,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('polarity-negative-translated.txt','r') as fopen:\n",
    "    texts = fopen.read().split('\\n')\n",
    "labels = [0] * len(texts)\n",
    "\n",
    "with open('polarity-positive-translated.txt','r') as fopen:\n",
    "    positive_texts = fopen.read().split('\\n')\n",
    "labels += [1] * len(positive_texts)\n",
    "texts += positive_texts\n",
    "texts += df.iloc[:,1].tolist()\n",
    "labels += Y.tolist()\n",
    "\n",
    "assert len(labels) == len(texts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "vocab from size: 18957\n",
      "Most common words [('yang', 14891), ('dan', 8177), ('tidak', 4578), ('untuk', 4023), ('dengan', 3349), ('filem', 3279)]\n",
      "Sample data [1643, 206, 5, 160, 217, 106, 306, 4, 79, 202] ['ringkas', 'bodoh', 'dan', 'membosankan', 'kanak-kanak', 'lelaki', 'remaja', 'yang', 'begitu', 'muda']\n"
     ]
    }
   ],
   "source": [
    "concat = ' '.join(texts).split()\n",
    "vocabulary_size = len(list(set(concat)))\n",
    "data, count, dictionary, rev_dictionary = build_dataset(concat, vocabulary_size)\n",
    "print('vocab from size: %d'%(vocabulary_size))\n",
    "print('Most common words', count[4:10])\n",
    "print('Sample data', data[:10], [rev_dictionary[i] for i in data[:10]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def str_idx(corpus, dic, maxlen, UNK=3):\n",
    "    X = np.zeros((len(corpus),maxlen))\n",
    "    for i in range(len(corpus)):\n",
    "        for no, k in enumerate(corpus[i].split()[:maxlen][::-1]):\n",
    "            try:\n",
    "                X[i,-1 - no]=dic[k]\n",
    "            except Exception as e:\n",
    "                X[i,-1 - no]=UNK\n",
    "    return X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Model:\n",
    "    def __init__(self, size_layer, num_layers, dimension_output, learning_rate, dropout,\n",
    "                dict_size):\n",
    "        def cells(size, reuse=False):\n",
    "            return tf.contrib.rnn.DropoutWrapper(\n",
    "                tf.nn.rnn_cell.LSTMCell(\n",
    "                    size,\n",
    "                    initializer=tf.orthogonal_initializer(),\n",
    "                    reuse=reuse),\n",
    "                state_keep_prob=dropout,\n",
    "                output_keep_prob=dropout)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None])\n",
    "        encoder_embeddings = tf.Variable(tf.random_uniform([dict_size, size_layer], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(encoder_embeddings, self.X)\n",
    "        attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(\n",
    "            num_units = size_layer, \n",
    "            memory = encoder_embedded)\n",
    "        rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)]), \n",
    "            attention_mechanism = attention_mechanism,\n",
    "            attention_layer_size = size_layer,\n",
    "            alignment_history=True)\n",
    "        outputs, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded, dtype = tf.float32)\n",
    "        self.alignments = tf.transpose(last_state.alignment_history.stack(),[1,2,0])\n",
    "        W = tf.get_variable('w',shape=(size_layer, dimension_output),\n",
    "                            initializer=tf.glorot_uniform_initializer())\n",
    "        b = tf.get_variable('b',shape=(dimension_output),\n",
    "                            initializer=tf.zeros_initializer())\n",
    "        self.logits = tf.add(tf.matmul(outputs[:,-1], W),b,name='logits')\n",
    "        self.cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n",
    "            logits = self.logits, labels = self.Y))\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        correct_pred = tf.equal(tf.argmax(self.logits, 1,output_type=tf.int32), self.Y)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        self.attention = tf.nn.softmax(tf.reduce_sum(self.alignments[0],1),name='alphas')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'bahdanau/model.ckpt'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "size_layer = 256\n",
    "num_layers = 2\n",
    "dropout = 0.8\n",
    "dimension_output = 2\n",
    "learning_rate = 1e-4\n",
    "batch_size = 32\n",
    "maxlen = 100\n",
    "\n",
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model(size_layer,num_layers,dimension_output,learning_rate,dropout,len(dictionary))\n",
    "sess.run(tf.global_variables_initializer())\n",
    "saver = tf.train.Saver(tf.global_variables())\n",
    "saver.save(sess, \"bahdanau/model.ckpt\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "vectors = str_idx(texts, dictionary, maxlen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X, test_X, train_Y, test_Y = train_test_split(vectors, \n",
    "                                                    labels,\n",
    "                                                    test_size = 0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:48<00:00,  3.28it/s, accuracy=0.742, cost=0.501]\n",
      "test minibatch loop: 100%|██████████| 90/90 [00:09<00:00,  9.38it/s, accuracy=0.5, cost=0.792]  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, pass acc: 0.000000, current acc: 0.653361\n",
      "time taken: 118.52346515655518\n",
      "epoch: 0, training loss: 0.654096, training acc: 0.608574, valid loss: 0.639861, valid acc: 0.653361\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:44<00:00,  3.43it/s, accuracy=0.806, cost=0.447]\n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 11.01it/s, accuracy=0.375, cost=0.812]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 1, pass acc: 0.653361, current acc: 0.661415\n",
      "time taken: 112.26846075057983\n",
      "epoch: 1, training loss: 0.599809, training acc: 0.670648, valid loss: 0.625623, valid acc: 0.661415\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:43<00:00,  3.46it/s, accuracy=0.806, cost=0.418]\n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 11.08it/s, accuracy=0.375, cost=0.809]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 2, pass acc: 0.661415, current acc: 0.664916\n",
      "time taken: 111.42859125137329\n",
      "epoch: 2, training loss: 0.556458, training acc: 0.708028, valid loss: 0.627689, valid acc: 0.664916\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:44<00:00,  3.43it/s, accuracy=0.839, cost=0.357]\n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 11.08it/s, accuracy=0.5, cost=0.909]  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 3, pass acc: 0.664916, current acc: 0.672969\n",
      "time taken: 112.3364839553833\n",
      "epoch: 3, training loss: 0.505106, training acc: 0.748738, valid loss: 0.645605, valid acc: 0.672969\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:44<00:00,  3.41it/s, accuracy=0.935, cost=0.288]\n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 10.55it/s, accuracy=0.625, cost=0.954]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 113.08643627166748\n",
      "epoch: 4, training loss: 0.444339, training acc: 0.787003, valid loss: 0.708635, valid acc: 0.669118\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:43<00:00,  3.43it/s, accuracy=0.871, cost=0.212]\n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 11.09it/s, accuracy=0.625, cost=1.21] \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 112.11891460418701\n",
      "epoch: 5, training loss: 0.370059, training acc: 0.831469, valid loss: 0.858506, valid acc: 0.659314\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:45<00:00,  3.40it/s, accuracy=0.968, cost=0.133] \n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 11.03it/s, accuracy=0.75, cost=1.52]  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 113.19700813293457\n",
      "epoch: 6, training loss: 0.290849, training acc: 0.869734, valid loss: 1.132611, valid acc: 0.666317\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:45<00:00,  3.39it/s, accuracy=0.935, cost=0.122] \n",
      "test minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 10.60it/s, accuracy=0.75, cost=1.49]  \n",
      "train minibatch loop:   0%|          | 0/357 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 113.71206593513489\n",
      "epoch: 7, training loss: 0.224863, training acc: 0.907549, valid loss: 1.208689, valid acc: 0.667367\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 357/357 [01:43<00:00,  3.44it/s, accuracy=0.935, cost=0.105] \n",
      "test minibatch loop: 100%|██████████| 90/90 [00:09<00:00,  9.55it/s, accuracy=0.75, cost=1.76]  \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "time taken: 113.27922558784485\n",
      "epoch: 8, training loss: 0.172068, training acc: 0.933637, valid loss: 1.287527, valid acc: 0.663866\n",
      "\n",
      "break epoch:9\n",
      "\n"
     ]
    }
   ],
   "source": [
    "EARLY_STOPPING, CURRENT_CHECKPOINT, CURRENT_ACC, EPOCH = 5, 0, 0, 0\n",
    "while True:\n",
    "    lasttime = time.time()\n",
    "    if CURRENT_CHECKPOINT == EARLY_STOPPING:\n",
    "        print('break epoch:%d\\n'%(EPOCH))\n",
    "        break\n",
    "        \n",
    "    train_acc, train_loss, test_acc, test_loss = 0, 0, 0, 0\n",
    "    pbar = tqdm(range(0, len(train_X), batch_size), desc='train minibatch loop')\n",
    "    for i in pbar:\n",
    "        batch_x = train_X[i:min(i+batch_size,train_X.shape[0])]\n",
    "        batch_y = train_Y[i:min(i+batch_size,train_X.shape[0])]\n",
    "        acc, loss, _ = sess.run([model.accuracy, model.cost, model.optimizer], \n",
    "                           feed_dict = {model.X : batch_x, model.Y : batch_y})\n",
    "        assert not np.isnan(loss)\n",
    "        train_loss += loss\n",
    "        train_acc += acc\n",
    "        pbar.set_postfix(cost=loss, accuracy = acc)\n",
    "    \n",
    "    pbar = tqdm(range(0, len(test_X), batch_size), desc='test minibatch loop')\n",
    "    for i in pbar:\n",
    "        batch_x = test_X[i:min(i+batch_size,test_X.shape[0])]\n",
    "        batch_y = test_Y[i:min(i+batch_size,test_X.shape[0])]\n",
    "        acc, loss = sess.run([model.accuracy, model.cost], \n",
    "                           feed_dict = {model.X : batch_x, model.Y : batch_y})\n",
    "        test_loss += loss\n",
    "        test_acc += acc\n",
    "        pbar.set_postfix(cost=loss, accuracy = acc)\n",
    "    \n",
    "    train_loss /= (len(train_X) / batch_size)\n",
    "    train_acc /= (len(train_X) / batch_size)\n",
    "    test_loss /= (len(test_X) / batch_size)\n",
    "    test_acc /= (len(test_X) / batch_size)\n",
    "    \n",
    "    if test_acc > CURRENT_ACC:\n",
    "        print('epoch: %d, pass acc: %f, current acc: %f'%(EPOCH,CURRENT_ACC, test_acc))\n",
    "        CURRENT_ACC = test_acc\n",
    "        CURRENT_CHECKPOINT = 0\n",
    "    else:\n",
    "        CURRENT_CHECKPOINT += 1\n",
    "        \n",
    "    print('time taken:', time.time()-lasttime)\n",
    "    print('epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'%(EPOCH,train_loss,\n",
    "                                                                                          train_acc,test_loss,\n",
    "                                                                                          test_acc))\n",
    "    EPOCH += 1\n",
    "    saver.save(sess, \"bahdanau/model.ckpt\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "validation minibatch loop: 100%|██████████| 90/90 [00:08<00:00, 11.10it/s]\n"
     ]
    }
   ],
   "source": [
    "real_Y, predict_Y = [], []\n",
    "\n",
    "pbar = tqdm(range(0, len(test_X), batch_size), desc='validation minibatch loop')\n",
    "for i in pbar:\n",
    "    batch_x = test_X[i:min(i+batch_size,test_X.shape[0])]\n",
    "    batch_y = test_Y[i:min(i+batch_size,test_X.shape[0])]\n",
    "    predict_Y += np.argmax(sess.run(model.logits, feed_dict = {model.X : batch_x, model.Y : batch_y}),1).tolist()\n",
    "    real_Y += batch_y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             precision    recall  f1-score   support\n",
      "\n",
      "   negative       0.63      0.63      0.63      1320\n",
      "   positive       0.68      0.68      0.68      1536\n",
      "\n",
      "avg / total       0.66      0.66      0.66      2856\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from sklearn import metrics\n",
    "print(metrics.classification_report(real_Y, predict_Y, target_names = ['negative','positive']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "strings=','.join([n.name for n in tf.get_default_graph().as_graph_def().node if \"Variable\" in n.op or n.name.find('Placeholder') >= 0 or n.name.find('logits') == 0 or n.name.find('alphas') == 0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def freeze_graph(model_dir, output_node_names):\n",
    "\n",
    "    if not tf.gfile.Exists(model_dir):\n",
    "        raise AssertionError(\n",
    "            \"Export directory doesn't exists. Please specify an export \"\n",
    "            \"directory: %s\" % model_dir)\n",
    "\n",
    "    checkpoint = tf.train.get_checkpoint_state(model_dir)\n",
    "    input_checkpoint = checkpoint.model_checkpoint_path\n",
    "    \n",
    "    absolute_model_dir = \"/\".join(input_checkpoint.split('/')[:-1])\n",
    "    output_graph = absolute_model_dir + \"/frozen_model.pb\"\n",
    "    clear_devices = True\n",
    "    with tf.Session(graph=tf.Graph()) as sess:\n",
    "        saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)\n",
    "        saver.restore(sess, input_checkpoint)\n",
    "        output_graph_def = tf.graph_util.convert_variables_to_constants(\n",
    "            sess,\n",
    "            tf.get_default_graph().as_graph_def(),\n",
    "            output_node_names.split(\",\")\n",
    "        ) \n",
    "        with tf.gfile.GFile(output_graph, \"wb\") as f:\n",
    "            f.write(output_graph_def.SerializeToString())\n",
    "        print(\"%d ops in the final graph.\" % len(output_graph_def.node))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from bahdanau/model.ckpt\n",
      "INFO:tensorflow:Froze 35 variables.\n",
      "Converted 35 variables to const ops.\n",
      "413 ops in the final graph.\n"
     ]
    }
   ],
   "source": [
    "freeze_graph(\"bahdanau\", strings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_graph(frozen_graph_filename):\n",
    "    with tf.gfile.GFile(frozen_graph_filename, \"rb\") as f:\n",
    "        graph_def = tf.GraphDef()\n",
    "        graph_def.ParseFromString(f.read())\n",
    "    with tf.Graph().as_default() as graph:\n",
    "        tf.import_graph_def(graph_def)\n",
    "    return graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "g=load_graph('bahdanau/frozen_model.pb')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(100,)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = g.get_tensor_by_name('import/Placeholder:0')\n",
    "logits = g.get_tensor_by_name('import/logits:0')\n",
    "alphas = g.get_tensor_by_name('import/alphas:0')\n",
    "test_sess = tf.InteractiveSession(graph=g)\n",
    "test_sess.run([logits,alphas], feed_dict={x:vectors[:1]})[1].shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[0.9984276 , 0.00157239]], dtype=float32),\n",
       " array([0.04632575, 0.0188179 , 0.01601248, 0.01524496, 0.01524496,\n",
       "        0.04298494, 0.01821836, 0.01842043, 0.80873024], dtype=float32)]"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'kerajaan sebenarnya sangat bencikan rakyatnya, minyak naik dan segalanya'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "test_sess.run([tf.nn.softmax(logits),alphas], feed_dict={x:new_vector})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[0.549336  , 0.45066395]], dtype=float32),\n",
       " array([0.14614522, 0.097147  , 0.15663794, 0.45392463, 0.14614522],\n",
       "       dtype=float32)]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'saya sangat sayangkan kerajaan saya'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "test_sess.run([tf.nn.softmax(logits),alphas], feed_dict={x:new_vector})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[0.93802065, 0.06197929]], dtype=float32),\n",
       " array([0.5580012 , 0.16381814, 0.11481879, 0.16336185], dtype=float32)]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'bodoh lah awak ni'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "test_sess.run([tf.nn.softmax(logits),alphas], feed_dict={x:new_vector})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[0.1507497 , 0.84925026]], dtype=float32),\n",
       " array([0.33014774, 0.12414087, 0.10522812, 0.4404832 ], dtype=float32)]"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'kerajaan sebenarnya sangat baik'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "test_sess.run([tf.nn.softmax(logits),alphas], feed_dict={x:new_vector})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "with open('bahdanau-sentiment.json','w') as fopen:\n",
    "    fopen.write(json.dumps({'dictionary':dictionary,'reverse_dictionary':rev_dictionary}))"
   ]
  },
  {
   "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.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
