{
 "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 [1657, 206, 5, 161, 217, 106, 304, 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": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "from keras.optimizers import Adam, RMSprop\n",
    "from keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler\n",
    "from keras.layers import GRU, BatchNormalization, Conv1D, MaxPooling1D\n",
    "from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Conv1D, GRU\n",
    "from keras.layers import Bidirectional, GlobalMaxPool1D, MaxPooling1D, Add, Flatten\n",
    "from keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D, concatenate, SpatialDropout1D\n",
    "from keras.models import Model, load_model\n",
    "from keras import initializers, regularizers, constraints, optimizers, layers, callbacks\n",
    "from keras import backend as K\n",
    "from keras.engine import InputSpec, Layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "early_stop = EarlyStopping(monitor = \"val_loss\", mode = \"min\", patience = 3)\n",
    "file_path = \"sentiment_best_model.hdf5\"\n",
    "check_point = ModelCheckpoint(file_path, monitor = \"val_loss\", verbose = 1, save_best_only = True, mode = \"min\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "vectors = str_idx(texts, dictionary, 100)\n",
    "onehot = np.zeros((len(vectors),2))\n",
    "onehot[np.arange(len(vectors)),labels] = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X, test_X, train_Y, test_Y = train_test_split(vectors, \n",
    "                                                    onehot,\n",
    "                                                    test_size = 0.2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 11423 samples, validate on 2856 samples\n",
      "Epoch 1/10\n",
      "11423/11423 [==============================] - 77s 7ms/step - loss: 0.6198 - acc: 0.6414 - val_loss: 0.5499 - val_acc: 0.7143\n",
      "\n",
      "Epoch 00001: val_loss improved from inf to 0.54990, saving model to sentiment_best_model.hdf5\n",
      "Epoch 2/10\n",
      "11423/11423 [==============================] - 68s 6ms/step - loss: 0.4002 - acc: 0.8218 - val_loss: 0.5613 - val_acc: 0.7307\n",
      "\n",
      "Epoch 00002: val_loss did not improve from 0.54990\n",
      "Epoch 3/10\n",
      "11423/11423 [==============================] - 67s 6ms/step - loss: 0.2317 - acc: 0.9091 - val_loss: 0.6820 - val_acc: 0.7206\n",
      "\n",
      "Epoch 00003: val_loss did not improve from 0.54990\n",
      "Epoch 4/10\n",
      "11423/11423 [==============================] - 67s 6ms/step - loss: 0.1145 - acc: 0.9595 - val_loss: 1.0357 - val_acc: 0.7104\n",
      "\n",
      "Epoch 00004: val_loss did not improve from 0.54990\n"
     ]
    }
   ],
   "source": [
    "inp = Input(shape = (None,))\n",
    "x = Embedding(len(dictionary), 256, trainable=True)(inp)\n",
    "x1 = SpatialDropout1D(0.2)(x)\n",
    "\n",
    "x = Bidirectional(GRU(128, return_sequences = True))(x1)\n",
    "x = Conv1D(64, kernel_size = 2, padding = \"valid\", kernel_initializer = \"he_uniform\")(x)\n",
    "    \n",
    "y = Bidirectional(LSTM(128, return_sequences = True))(x1)\n",
    "y = Conv1D(64, kernel_size = 2, padding = \"valid\", kernel_initializer = \"he_uniform\")(y)\n",
    "    \n",
    "avg_pool1 = GlobalAveragePooling1D()(x)\n",
    "max_pool1 = GlobalMaxPooling1D()(x)\n",
    "    \n",
    "avg_pool2 = GlobalAveragePooling1D()(y)\n",
    "max_pool2 = GlobalMaxPooling1D()(y)\n",
    "    \n",
    "x = concatenate([avg_pool1, max_pool1, avg_pool2, max_pool2])\n",
    "\n",
    "x = Dense(2, activation = \"softmax\")(x)\n",
    "model = Model(inputs = inp, outputs = x)\n",
    "model.compile(loss = \"categorical_crossentropy\", optimizer = Adam(lr = 1e-3), metrics = [\"accuracy\"])\n",
    "history = model.fit(train_X, train_Y, batch_size = 128, epochs = 10, validation_data = (test_X, test_Y), \n",
    "                    verbose = 1, callbacks = [check_point, early_stop])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2856/2856 [==============================] - 3s 889us/step\n"
     ]
    }
   ],
   "source": [
    "model = load_model(file_path)\n",
    "predict_Y = np.argmax(model.predict(test_X,batch_size=128,verbose=1),1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             precision    recall  f1-score   support\n",
      "\n",
      "   negative       0.68      0.69      0.69      1302\n",
      "   positive       0.74      0.73      0.74      1554\n",
      "\n",
      "avg / total       0.71      0.71      0.71      2856\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from sklearn import metrics\n",
    "print(metrics.classification_report(np.argmax(test_Y,1), predict_Y, target_names = ['negative','positive']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.7262973 , 0.27370268]], dtype=float32)"
      ]
     },
     "execution_count": 16,
     "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",
    "model.predict(new_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.3166659, 0.6833341]], dtype=float32)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'saya sangat sayangkan kerajaan saya'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "model.predict(new_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.6569448 , 0.34305516]], dtype=float32)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'bodoh lah awak ni'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "model.predict(new_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.4587405 , 0.54125947]], dtype=float32)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = 'kerajaan sebenarnya sangat baik'\n",
    "new_vector = str_idx([text],dictionary,len(text.split()))\n",
    "model.predict(new_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "with open('fast-text-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
}
