ml-finance-python

python scripts for finance machine learning

git clone https://9o.is/git/ml-finance-python.git

05_sentiment_analysis_pretrained_embeddings.ipynb

(18548B)


      1 {
      2  "cells": [
      3   {
      4    "cell_type": "markdown",
      5    "metadata": {},
      6    "source": [
      7     "# Sentiment analysis with pretrained word vectors"
      8    ]
      9   },
     10   {
     11    "cell_type": "markdown",
     12    "metadata": {},
     13    "source": [
     14     "In Chapter 15, Word Embeddings, we discussed how to learn domain-specific word embeddings. Word2vec, and related learning algorithms, produce high-quality word vectors, but require large datasets. Hence, it is common that research groups share word vectors trained on large datasets, similar to the weights for pretrained deep learning models that we encountered in the section on transfer learning in the previous chapter.\n",
     15     "\n",
     16     "We are now going to illustrate how to use pretrained Global Vectors for Word Representation (GloVe) provided by the Stanford NLP group with the IMDB review dataset."
     17    ]
     18   },
     19   {
     20    "cell_type": "code",
     21    "execution_count": 1,
     22    "metadata": {},
     23    "outputs": [
     24     {
     25      "name": "stderr",
     26      "output_type": "stream",
     27      "text": [
     28       "Using TensorFlow backend.\n"
     29      ]
     30     }
     31    ],
     32    "source": [
     33     "%matplotlib inline\n",
     34     "from pathlib import Path\n",
     35     "import numpy as np\n",
     36     "import pandas as pd\n",
     37     "import matplotlib.pyplot as plt\n",
     38     "import seaborn as sns\n",
     39     "from datetime import datetime, date\n",
     40     "from sklearn.metrics import mean_squared_error, roc_auc_score\n",
     41     "from sklearn.preprocessing import minmax_scale\n",
     42     "from keras.callbacks import ModelCheckpoint, EarlyStopping\n",
     43     "from keras.datasets import imdb\n",
     44     "from keras.models import Sequential, Model\n",
     45     "from keras.layers import Dense, LSTM, GRU, Input, concatenate, Embedding, Reshape\n",
     46     "from keras.preprocessing.sequence import pad_sequences\n",
     47     "from keras.preprocessing.text import Tokenizer\n",
     48     "import keras\n",
     49     "import keras.backend as K\n",
     50     "import tensorflow as tf"
     51    ]
     52   },
     53   {
     54    "cell_type": "code",
     55    "execution_count": 2,
     56    "metadata": {},
     57    "outputs": [],
     58    "source": [
     59     "sns.set_style('whitegrid')\n",
     60     "np.random.seed(42)\n",
     61     "K.clear_session()"
     62    ]
     63   },
     64   {
     65    "cell_type": "markdown",
     66    "metadata": {},
     67    "source": [
     68     "## Load Reviews"
     69    ]
     70   },
     71   {
     72    "cell_type": "markdown",
     73    "metadata": {},
     74    "source": [
     75     "We are going to load the IMDB dataset from the source for manual preprocessing."
     76    ]
     77   },
     78   {
     79    "cell_type": "markdown",
     80    "metadata": {},
     81    "source": [
     82     "Data source: [Stanford IMDB Reviews Dataset](http://ai.stanford.edu/~amaas/data/sentiment/)"
     83    ]
     84   },
     85   {
     86    "cell_type": "code",
     87    "execution_count": 3,
     88    "metadata": {},
     89    "outputs": [],
     90    "source": [
     91     "path = Path('data/aclImdb/')"
     92    ]
     93   },
     94   {
     95    "cell_type": "code",
     96    "execution_count": 4,
     97    "metadata": {},
     98    "outputs": [
     99     {
    100      "data": {
    101       "text/plain": [
    102        "50000"
    103       ]
    104      },
    105      "execution_count": 4,
    106      "metadata": {},
    107      "output_type": "execute_result"
    108     }
    109    ],
    110    "source": [
    111     "files = path.glob('**/*.txt')\n",
    112     "len(list(files))"
    113    ]
    114   },
    115   {
    116    "cell_type": "code",
    117    "execution_count": 5,
    118    "metadata": {},
    119    "outputs": [],
    120    "source": [
    121     "files = path.glob('*/**/*.txt')\n",
    122     "data = []\n",
    123     "for f in files:\n",
    124     "    _, _, data_set, outcome = str(f.parent).split('/')\n",
    125     "    data.append([data_set, int(outcome=='pos'), f.read_text(encoding='latin1')])"
    126    ]
    127   },
    128   {
    129    "cell_type": "code",
    130    "execution_count": 6,
    131    "metadata": {},
    132    "outputs": [],
    133    "source": [
    134     "data = pd.DataFrame(data, columns=['dataset', 'label', 'review']).sample(frac=1.0)"
    135    ]
    136   },
    137   {
    138    "cell_type": "code",
    139    "execution_count": 7,
    140    "metadata": {},
    141    "outputs": [],
    142    "source": [
    143     "train_data = data.loc[data.dataset=='train', ['label', 'review']]\n",
    144     "test_data = data.loc[data.dataset=='test', ['label', 'review']]"
    145    ]
    146   },
    147   {
    148    "cell_type": "code",
    149    "execution_count": 8,
    150    "metadata": {},
    151    "outputs": [
    152     {
    153      "data": {
    154       "text/plain": [
    155        "1    12500\n",
    156        "0    12500\n",
    157        "Name: label, dtype: int64"
    158       ]
    159      },
    160      "execution_count": 8,
    161      "metadata": {},
    162      "output_type": "execute_result"
    163     }
    164    ],
    165    "source": [
    166     "train_data.label.value_counts()"
    167    ]
    168   },
    169   {
    170    "cell_type": "code",
    171    "execution_count": 9,
    172    "metadata": {},
    173    "outputs": [
    174     {
    175      "data": {
    176       "text/plain": [
    177        "1    12500\n",
    178        "0    12500\n",
    179        "Name: label, dtype: int64"
    180       ]
    181      },
    182      "execution_count": 9,
    183      "metadata": {},
    184      "output_type": "execute_result"
    185     }
    186    ],
    187    "source": [
    188     "test_data.label.value_counts()"
    189    ]
    190   },
    191   {
    192    "cell_type": "markdown",
    193    "metadata": {},
    194    "source": [
    195     "## Prepare Data"
    196    ]
    197   },
    198   {
    199    "cell_type": "markdown",
    200    "metadata": {},
    201    "source": [
    202     "### Tokenizer"
    203    ]
    204   },
    205   {
    206    "cell_type": "markdown",
    207    "metadata": {},
    208    "source": [
    209     "Keras provides a tokenizer that we use to convert the text documents to integer-encoded sequences, as shown here:"
    210    ]
    211   },
    212   {
    213    "cell_type": "code",
    214    "execution_count": 10,
    215    "metadata": {},
    216    "outputs": [],
    217    "source": [
    218     "num_words = 10000\n",
    219     "t = Tokenizer(num_words=num_words, \n",
    220     "              lower=True, \n",
    221     "              oov_token=2)\n",
    222     "t.fit_on_texts(train_data.review)"
    223    ]
    224   },
    225   {
    226    "cell_type": "code",
    227    "execution_count": 11,
    228    "metadata": {},
    229    "outputs": [
    230     {
    231      "data": {
    232       "text/plain": [
    233        "88586"
    234       ]
    235      },
    236      "execution_count": 11,
    237      "metadata": {},
    238      "output_type": "execute_result"
    239     }
    240    ],
    241    "source": [
    242     "vocab_size = len(t.word_index) + 1\n",
    243     "vocab_size"
    244    ]
    245   },
    246   {
    247    "cell_type": "code",
    248    "execution_count": 12,
    249    "metadata": {},
    250    "outputs": [],
    251    "source": [
    252     "train_data_encoded = t.texts_to_sequences(train_data.review)\n",
    253     "test_data_encoded = t.texts_to_sequences(test_data.review)"
    254    ]
    255   },
    256   {
    257    "cell_type": "code",
    258    "execution_count": 13,
    259    "metadata": {},
    260    "outputs": [],
    261    "source": [
    262     "max_length = 100"
    263    ]
    264   },
    265   {
    266    "cell_type": "markdown",
    267    "metadata": {},
    268    "source": [
    269     "### Pad Sequences"
    270    ]
    271   },
    272   {
    273    "cell_type": "markdown",
    274    "metadata": {},
    275    "source": [
    276     "We also use the pad_sequences function to convert the list of lists (of unequal length) to stacked sets of padded and truncated arrays for both the train and test datasets:"
    277    ]
    278   },
    279   {
    280    "cell_type": "code",
    281    "execution_count": 14,
    282    "metadata": {},
    283    "outputs": [
    284     {
    285      "data": {
    286       "text/plain": [
    287        "(25000, 100)"
    288       ]
    289      },
    290      "execution_count": 14,
    291      "metadata": {},
    292      "output_type": "execute_result"
    293     }
    294    ],
    295    "source": [
    296     "X_train_padded = pad_sequences(train_data_encoded, \n",
    297     "                            maxlen=max_length, \n",
    298     "                            padding='post',\n",
    299     "                           truncating='post')\n",
    300     "y_train = train_data['label']\n",
    301     "X_train_padded.shape"
    302    ]
    303   },
    304   {
    305    "cell_type": "code",
    306    "execution_count": 15,
    307    "metadata": {
    308     "scrolled": true
    309    },
    310    "outputs": [
    311     {
    312      "data": {
    313       "text/plain": [
    314        "(25000, 100)"
    315       ]
    316      },
    317      "execution_count": 15,
    318      "metadata": {},
    319      "output_type": "execute_result"
    320     }
    321    ],
    322    "source": [
    323     "X_test_padded = pad_sequences(test_data_encoded, \n",
    324     "                            maxlen=max_length, \n",
    325     "                            padding='post',\n",
    326     "                           truncating='post')\n",
    327     "y_test = test_data['label']\n",
    328     "X_test_padded.shape"
    329    ]
    330   },
    331   {
    332    "cell_type": "markdown",
    333    "metadata": {},
    334    "source": [
    335     "## Load Embeddings"
    336    ]
    337   },
    338   {
    339    "cell_type": "markdown",
    340    "metadata": {},
    341    "source": [
    342     "Assuming we have downloaded and unzipped the GloVe data to the location indicated in the code, we now create a dictionary that maps GloVe tokens to 100-dimensional real-valued vectors, as follows:"
    343    ]
    344   },
    345   {
    346    "cell_type": "code",
    347    "execution_count": 16,
    348    "metadata": {},
    349    "outputs": [],
    350    "source": [
    351     "# load the whole embedding into memory\n",
    352     "glove_path = Path('data/glove/glove.6B.100d.txt')\n",
    353     "embeddings_index = dict()\n",
    354     "\n",
    355     "for line in glove_path.open(encoding='latin1'):\n",
    356     "    values = line.split()\n",
    357     "    word = values[0]\n",
    358     "    try:\n",
    359     "        coefs = np.asarray(values[1:], dtype='float32')\n",
    360     "    except:\n",
    361     "        continue\n",
    362     "    embeddings_index[word] = coefs"
    363    ]
    364   },
    365   {
    366    "cell_type": "code",
    367    "execution_count": 17,
    368    "metadata": {},
    369    "outputs": [
    370     {
    371      "name": "stdout",
    372      "output_type": "stream",
    373      "text": [
    374       "Loaded 399,883 word vectors.\n"
    375      ]
    376     }
    377    ],
    378    "source": [
    379     "print('Loaded {:,d} word vectors.'.format(len(embeddings_index)))"
    380    ]
    381   },
    382   {
    383    "cell_type": "markdown",
    384    "metadata": {},
    385    "source": [
    386     "There are around 340,000 word vectors that we use to create an embedding matrix that matches the vocabulary so that the RNN model can access embeddings by the token index:"
    387    ]
    388   },
    389   {
    390    "cell_type": "code",
    391    "execution_count": 18,
    392    "metadata": {},
    393    "outputs": [],
    394    "source": [
    395     "embedding_matrix = np.zeros((vocab_size, 100))\n",
    396     "for word, i in t.word_index.items():\n",
    397     "    embedding_vector = embeddings_index.get(word)\n",
    398     "    if embedding_vector is not None:\n",
    399     "        embedding_matrix[i] = embedding_vector"
    400    ]
    401   },
    402   {
    403    "cell_type": "code",
    404    "execution_count": 19,
    405    "metadata": {},
    406    "outputs": [
    407     {
    408      "data": {
    409       "text/plain": [
    410        "(88586, 100)"
    411       ]
    412      },
    413      "execution_count": 19,
    414      "metadata": {},
    415      "output_type": "execute_result"
    416     }
    417    ],
    418    "source": [
    419     "embedding_matrix.shape"
    420    ]
    421   },
    422   {
    423    "cell_type": "markdown",
    424    "metadata": {},
    425    "source": [
    426     "## Define Model Architecture"
    427    ]
    428   },
    429   {
    430    "cell_type": "markdown",
    431    "metadata": {},
    432    "source": [
    433     "The difference between this and the RNN setup in the previous example is that we are going to pass the embedding matrix to the embedding layer and set it to non-trainable, so that the weights remain fixed during training:"
    434    ]
    435   },
    436   {
    437    "cell_type": "code",
    438    "execution_count": 20,
    439    "metadata": {},
    440    "outputs": [],
    441    "source": [
    442     "embedding_size = 100"
    443    ]
    444   },
    445   {
    446    "cell_type": "code",
    447    "execution_count": 21,
    448    "metadata": {},
    449    "outputs": [
    450     {
    451      "name": "stdout",
    452      "output_type": "stream",
    453      "text": [
    454       "_________________________________________________________________\n",
    455       "Layer (type)                 Output Shape              Param #   \n",
    456       "=================================================================\n",
    457       "embedding_1 (Embedding)      (None, 100, 100)          8858600   \n",
    458       "_________________________________________________________________\n",
    459       "gru_1 (GRU)                  (None, 32)                12768     \n",
    460       "_________________________________________________________________\n",
    461       "dense_1 (Dense)              (None, 1)                 33        \n",
    462       "=================================================================\n",
    463       "Total params: 8,871,401\n",
    464       "Trainable params: 12,801\n",
    465       "Non-trainable params: 8,858,600\n",
    466       "_________________________________________________________________\n"
    467      ]
    468     }
    469    ],
    470    "source": [
    471     "rnn = Sequential([\n",
    472     "    Embedding(input_dim=vocab_size, \n",
    473     "              output_dim= embedding_size, \n",
    474     "              input_length=max_length,\n",
    475     "              weights=[embedding_matrix], \n",
    476     "              trainable=False),\n",
    477     "    GRU(units=32,  dropout=0.2, recurrent_dropout=0.2),\n",
    478     "    Dense(1, activation='sigmoid')\n",
    479     "])\n",
    480     "rnn.summary()"
    481    ]
    482   },
    483   {
    484    "cell_type": "code",
    485    "execution_count": 23,
    486    "metadata": {},
    487    "outputs": [],
    488    "source": [
    489     "rnn.compile(loss='binary_crossentropy', \n",
    490     "            optimizer='RMSProp', \n",
    491     "            metrics=['accuracy'])"
    492    ]
    493   },
    494   {
    495    "cell_type": "code",
    496    "execution_count": 24,
    497    "metadata": {},
    498    "outputs": [],
    499    "source": [
    500     "rnn_path = 'models/imdb.gru_pretrained.weights.best.hdf5'\n",
    501     "checkpointer = ModelCheckpoint(filepath=rnn_path,\n",
    502     "                              monitor='val_loss',\n",
    503     "                              save_best_only=True,\n",
    504     "                              save_weights_only=True,\n",
    505     "                              period=5)"
    506    ]
    507   },
    508   {
    509    "cell_type": "code",
    510    "execution_count": 25,
    511    "metadata": {},
    512    "outputs": [],
    513    "source": [
    514     "early_stopping = EarlyStopping(monitor='val_loss', \n",
    515     "                              patience=5,\n",
    516     "                              restore_best_weights=True)"
    517    ]
    518   },
    519   {
    520    "cell_type": "code",
    521    "execution_count": 26,
    522    "metadata": {
    523     "scrolled": false
    524    },
    525    "outputs": [
    526     {
    527      "name": "stdout",
    528      "output_type": "stream",
    529      "text": [
    530       "Train on 25000 samples, validate on 25000 samples\n",
    531       "Epoch 1/25\n",
    532       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.6392 - acc: 0.6218 - val_loss: 0.5223 - val_acc: 0.7461\n",
    533       "Epoch 2/25\n",
    534       "25000/25000 [==============================] - 62s 2ms/step - loss: 0.5263 - acc: 0.7458 - val_loss: 0.4666 - val_acc: 0.7781\n",
    535       "Epoch 3/25\n",
    536       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.4834 - acc: 0.7722 - val_loss: 0.4407 - val_acc: 0.7918\n",
    537       "Epoch 4/25\n",
    538       "25000/25000 [==============================] - 62s 2ms/step - loss: 0.4550 - acc: 0.7869 - val_loss: 0.4264 - val_acc: 0.7986\n",
    539       "Epoch 5/25\n",
    540       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.4395 - acc: 0.7958 - val_loss: 0.4131 - val_acc: 0.8066\n",
    541       "Epoch 6/25\n",
    542       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.4247 - acc: 0.8037 - val_loss: 0.4040 - val_acc: 0.8096\n",
    543       "Epoch 7/25\n",
    544       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.4113 - acc: 0.8117 - val_loss: 0.4022 - val_acc: 0.8100\n",
    545       "Epoch 8/25\n",
    546       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.4043 - acc: 0.8129 - val_loss: 0.3950 - val_acc: 0.8144\n",
    547       "Epoch 9/25\n",
    548       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3985 - acc: 0.8156 - val_loss: 0.3990 - val_acc: 0.8120\n",
    549       "Epoch 10/25\n",
    550       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3917 - acc: 0.8216 - val_loss: 0.3938 - val_acc: 0.8176\n",
    551       "Epoch 11/25\n",
    552       "25000/25000 [==============================] - 67s 3ms/step - loss: 0.3888 - acc: 0.8233 - val_loss: 0.3930 - val_acc: 0.8179\n",
    553       "Epoch 12/25\n",
    554       "25000/25000 [==============================] - 66s 3ms/step - loss: 0.3817 - acc: 0.8265 - val_loss: 0.3871 - val_acc: 0.8192\n",
    555       "Epoch 13/25\n",
    556       "25000/25000 [==============================] - 66s 3ms/step - loss: 0.3794 - acc: 0.8296 - val_loss: 0.4039 - val_acc: 0.8134\n",
    557       "Epoch 14/25\n",
    558       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3753 - acc: 0.8311 - val_loss: 0.3843 - val_acc: 0.8237\n",
    559       "Epoch 15/25\n",
    560       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3682 - acc: 0.8328 - val_loss: 0.3906 - val_acc: 0.8196\n",
    561       "Epoch 16/25\n",
    562       "25000/25000 [==============================] - 67s 3ms/step - loss: 0.3675 - acc: 0.8374 - val_loss: 0.3822 - val_acc: 0.8262\n",
    563       "Epoch 17/25\n",
    564       "25000/25000 [==============================] - 65s 3ms/step - loss: 0.3641 - acc: 0.8373 - val_loss: 0.3799 - val_acc: 0.8253\n",
    565       "Epoch 18/25\n",
    566       "25000/25000 [==============================] - 64s 3ms/step - loss: 0.3630 - acc: 0.8382 - val_loss: 0.3875 - val_acc: 0.8205\n",
    567       "Epoch 19/25\n",
    568       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3586 - acc: 0.8417 - val_loss: 0.3820 - val_acc: 0.8267\n",
    569       "Epoch 20/25\n",
    570       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3600 - acc: 0.8387 - val_loss: 0.3862 - val_acc: 0.8262\n",
    571       "Epoch 21/25\n",
    572       "25000/25000 [==============================] - 63s 3ms/step - loss: 0.3560 - acc: 0.8395 - val_loss: 0.3847 - val_acc: 0.8249\n",
    573       "Epoch 22/25\n",
    574       "25000/25000 [==============================] - 64s 3ms/step - loss: 0.3542 - acc: 0.8408 - val_loss: 0.3815 - val_acc: 0.8264\n"
    575      ]
    576     },
    577     {
    578      "data": {
    579       "text/plain": [
    580        "<keras.callbacks.History at 0x7f16815803c8>"
    581       ]
    582      },
    583      "execution_count": 26,
    584      "metadata": {},
    585      "output_type": "execute_result"
    586     }
    587    ],
    588    "source": [
    589     "rnn.fit(X_train_padded, \n",
    590     "        y_train, \n",
    591     "        batch_size=32, \n",
    592     "        epochs=25, \n",
    593     "        validation_data=(X_test_padded, y_test), \n",
    594     "        callbacks=[checkpointer, early_stopping],\n",
    595     "        verbose=1)"
    596    ]
    597   },
    598   {
    599    "cell_type": "code",
    600    "execution_count": 29,
    601    "metadata": {},
    602    "outputs": [],
    603    "source": [
    604     "rnn.load_weights(rnn_path)"
    605    ]
    606   },
    607   {
    608    "cell_type": "code",
    609    "execution_count": 30,
    610    "metadata": {},
    611    "outputs": [
    612     {
    613      "data": {
    614       "text/plain": [
    615        "0.910672304"
    616       ]
    617      },
    618      "execution_count": 30,
    619      "metadata": {},
    620      "output_type": "execute_result"
    621     }
    622    ],
    623    "source": [
    624     "y_score = rnn.predict(X_test_padded)\n",
    625     "roc_auc_score(y_score=y_score.squeeze(), y_true=y_test)"
    626    ]
    627   },
    628   {
    629    "cell_type": "code",
    630    "execution_count": null,
    631    "metadata": {},
    632    "outputs": [],
    633    "source": []
    634   }
    635  ],
    636  "metadata": {
    637   "kernelspec": {
    638    "display_name": "Python 3",
    639    "language": "python",
    640    "name": "python3"
    641   },
    642   "language_info": {
    643    "codemirror_mode": {
    644     "name": "ipython",
    645     "version": 3
    646    },
    647    "file_extension": ".py",
    648    "mimetype": "text/x-python",
    649    "name": "python",
    650    "nbconvert_exporter": "python",
    651    "pygments_lexer": "ipython3",
    652    "version": "3.6.8"
    653   },
    654   "toc": {
    655    "base_numbering": 1,
    656    "nav_menu": {},
    657    "number_sections": true,
    658    "sideBar": true,
    659    "skip_h1_title": true,
    660    "title_cell": "Table of Contents",
    661    "title_sidebar": "Contents",
    662    "toc_cell": false,
    663    "toc_position": {},
    664    "toc_section_display": true,
    665    "toc_window_display": false
    666   }
    667  },
    668  "nbformat": 4,
    669  "nbformat_minor": 2
    670 }