{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "**Important: This notebook will only work with fastai-0.7.x. Do not try to run any fastai-1.x code from this path in the repository because it will load fastai-0.7.x**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%reload_ext autoreload\n", "%autoreload 2\n", "%matplotlib inline\n", "\n", "from fastai.nlp import *\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.svm import LinearSVC\n", "from torchtext import vocab, data, datasets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## IMBD dataset and the sentiment classification task" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The [large movie view dataset](http://ai.stanford.edu/~amaas/data/sentiment/) contains a collection of 50,000 reviews from IMDB. The dataset contains an even number of positive and negative reviews. The authors considered only highly polarized reviews. A negative review has a score ≤ 4 out of 10, and a positive review has a score ≥ 7 out of 10. Neutral reviews are not included in the dataset. The dataset is divided into training and test sets. The training set is the same 25,000 labeled reviews.\n", "\n", "The **sentiment classification task** consists of predicting the polarity (positive or negative) of a given text." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To get the dataset, in your terminal run the following commands:\n", "\n", "`wget http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz`\n", "\n", "`gunzip aclImdb_v1.tar.gz`\n", "\n", "`tar -xvf aclImdb_v1.tar`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tokenizing" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sl=1000\n", "vocab_size=200000" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "PATH='data/aclImdb/'\n", "\n", "names = ['neg','pos']\n", "trn,trn_y = texts_labels_from_folders(f'{PATH}train',names)\n", "val,val_y = texts_labels_from_folders(f'{PATH}test',names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is the text of the first review:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"Story of a man who has unnatural feelings for a pig. Starts out with a opening scene that is a terrific example of absurd comedy. A formal orchestra audience is turned into an insane, violent mob by the crazy chantings of it's singers. Unfortunately it stays absurd the WHOLE time with no general narrative eventually making it just too off putting. Even those from the era should be turned off. The cryptic dialogue would make Shakespeare seem easy to a third grader. On a technical level it's better than you might think with some good cinematography by future great Vilmos Zsigmond. Future stars Sally Kirkland and Frederic Forrest can be seen briefly.\"" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "trn[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "trn_y[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[`CountVectorizer`](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html) converts a collection of text documents to a matrix of token counts (part of `sklearn.feature_extraction.text`). Here is how you specify parameters to the CountVectorizer. We will be working with the top 200000 unigrams, bigrams and trigrams." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "veczr = CountVectorizer(ngram_range=(1,3), tokenizer=tokenize, max_features=vocab_size)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the next line `fit_transform(trn)` computes the vocabulary and other hyparameters learned from the training set. It also transforms the training set. Since we have to apply the *same transformation* to your validation set, the second line uses just the method `transform(val)`. `trn_term_doc` and `val_term_doc` are sparse matrices. `trn_term_doc[i]` represents training document $i$ and it is binary (it has a $1$ for each vocabulary n-gram present in document $i$ and $0$ otherwise)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trn_term_doc = veczr.fit_transform(trn)\n", "val_term_doc = veczr.transform(val)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(25000, 200000)" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "trn_term_doc.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'analyzer': 'word',\n", " 'binary': False,\n", " 'decode_error': 'strict',\n", " 'dtype': numpy.int64,\n", " 'encoding': 'utf-8',\n", " 'input': 'content',\n", " 'lowercase': True,\n", " 'max_df': 1.0,\n", " 'max_features': 200000,\n", " 'min_df': 1,\n", " 'ngram_range': (1, 3),\n", " 'preprocessor': None,\n", " 'stop_words': None,\n", " 'strip_accents': None,\n", " 'token_pattern': '(?u)\\\\b\\\\w\\\\w+\\\\b',\n", " 'tokenizer': ,\n", " 'vocabulary': None}" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "veczr.get_params()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# here is the vocabulary\n", "vocab = veczr.get_feature_names()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['! \" and', '! \" as', '! \" at', '! \" but', '! \" for']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "vocab[50:55]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Weighted Naive Bayes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our first model is a version of logistic regression with Naive Bayes features described [here](https://www.aclweb.org/anthology/P12-2018). For every document we compute binarized features as described above. Each feature if multiplied by a log-count ratio (see below for explanation). A logitic regression model is then trained to predict sentiment." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is how to define **log-count ratio** for a feature $f$:\n", "\n", "$\\text{log-count ratio} = \\log \\frac{\\text{ratio of feature $f$ in positive documents}}{\\text{ratio of feature $f$ in negative documents}}$\n", "\n", "where ratio of feature $f$ in positive documents is the number of times a positive document has a feature divided by the number of positive documents." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Here is how we get a model from a bag of words\n", "md = TextClassifierData.from_bow(trn_term_doc, trn_y, val_term_doc, val_y, sl)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\u001b[93m Warning: no model found for 'en'\u001b[0m\n", "\n", " Only loading the 'en' tokenizer.\n", "\n", "\n", "\u001b[93m Warning: no model found for 'en'\u001b[0m\n", "\n", " Only loading the 'en' tokenizer.\n", "\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ef1300f2a7aa4b2f860ef038f700ddc9" } }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 0.068 0.1223 0.9165] \n", "\n" ] } ], "source": [ "learner = md.dotprod_nb_learner()\n", "learner.fit(0.02, 1, wds=1e-5, cycle_len=1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "b0ca3524c5ec4b2d84c6100b8f19c316" } }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "[ 0. 0.0581 0.1073 0.9235] \n", "\n" ] } ], "source": [ "learner = md.dotprod_nb_learner()\n", "learner.fit(0.02, 1, wds=1e-6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### unigram" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is use `CountVectorizer` with a different set of parameters. In particular ngram_range by default is set to (1, 1)so we will get unigram features. Note that we are specifiying our own `tokenize` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "veczr = CountVectorizer(tokenizer=tokenize)\n", "trn_term_doc = veczr.fit_transform(trn)\n", "val_term_doc = veczr.transform(val)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is how to compute the $\\text{log-count ratio}$ `r`. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x=trn_term_doc\n", "y=trn_y\n", "\n", "p = x[y==1].sum(0)+1\n", "q = x[y==0].sum(0)+1\n", "r = np.log((p/p.sum())/(q/q.sum()))\n", "b = np.log(len(p)/len(q))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is the formula for Naive Bayes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.80740000000000001" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pre_preds = val_term_doc @ r.T + b\n", "preds = pre_preds.T>0\n", "(preds==val_y).mean()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.82623999999999997" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pre_preds = val_term_doc.sign() @ r.T + b\n", "preds = pre_preds.T>0\n", "(preds==val_y).mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is how we can fit regularized logistic regression where the features are the unigrams." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.88260000000000005" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m = LogisticRegression(C=0.1, fit_intercept=False, dual=True)\n", "m.fit(x, y)\n", "preds = m.predict(val_term_doc)\n", "(preds==val_y).mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### bigram with NB features" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similar to the model before but with bigram features." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "veczr = CountVectorizer(ngram_range=(1,2), tokenizer=tokenize)\n", "trn_term_doc = veczr.fit_transform(trn)\n", "val_term_doc = veczr.transform(val)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "y=trn_y\n", "x=trn_term_doc.sign()\n", "val_x = val_term_doc.sign()\n", "p = x[y==1].sum(0)+1\n", "q = x[y==0].sum(0)+1\n", "r = np.log((p/p.sum())/(q/q.sum()))\n", "b = np.log(len(p)/len(q))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we fit regularized logistic regression where the features are the bigrams. Bigrams are giving us 2% boost. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.90271999999999997" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m = LogisticRegression(C=0.1, fit_intercept=False)\n", "m.fit(x, y);\n", "\n", "preds = m.predict(val_x)\n", "(preds.T==val_y).mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is the $\\text{log-count ratio}$ `r`. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "matrix([[ 0.6863, 0.6863, -0.7 , ..., 0.6863, -0.7 , -0.7 ]])" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we fit regularized logistic regression where the features are the bigrams multiplied by the $\\text{log-count ratio}$. We are getting an extra boost for the normalization. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x_nb = x.multiply(r)\n", "m = LogisticRegression(dual=True, C=1, fit_intercept=False)\n", "m.fit(x_nb, y);" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.91479999999999995" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "w = m.coef_.T\n", "preds = (val_x_nb @ w + m.intercept_)>0\n", "(preds.T==val_y).mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is an interpolation between Naive Bayes the regulaized logistic regression approach." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.91639999999999999" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "beta=0.25\n", "\n", "val_x_nb = val_x.multiply(r)\n", "w = (1-beta)*m.coef_.mean() + beta*m.coef_.T\n", "preds = (val_x_nb @ w + m.intercept_)>0\n", "(preds.T==val_y).mean()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "w2 = w.T[0]*r.A1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.91479999999999995" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "preds = (val_x @ w2 + m.intercept_)>0\n", "(preds.T==val_y).mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Baselines and Bigrams: Simple, Good Sentiment and Topic Classification. Sida Wang and Christopher D. Manning [pdf](https://www.aclweb.org/anthology/P12-2018)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Unused helpers" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class EzLSTM(nn.LSTM):\n", " def __init__(self, input_size, hidden_size, *args, **kwargs):\n", " super().__init__(input_size, hidden_size, *args, **kwargs)\n", " self.num_dirs = 2 if self.bidirectional else 1\n", " self.input_size = input_size\n", " self.hidden_size = hidden_size\n", " \n", " def forward(self, x):\n", " h0 = c0 = Variable(torch.zeros(self.num_dirs,x.size(1),self.hidden_size)).cuda()\n", " outp,_ = super().forward(x, (h0,c0))\n", " return outp[-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def init_wgts(m, last_l=-2):\n", " c = list(m.children())\n", " for l in c:\n", " if isinstance(l, nn.Embedding): \n", " l.weight.data.uniform_(-0.05,0.05)\n", " elif isinstance(l, (nn.Linear, nn.Conv1d)):\n", " xavier_uniform(l.weight.data, gain=calculate_gain('relu'))\n", " l.bias.data.zero_()\n", " xavier_uniform(c[last_l].weight.data, gain=calculate_gain('linear'));\n", "\n", "class SeqSize(nn.Sequential):\n", " def forward(self, x):\n", " for l in self.children():\n", " x = l(x)\n", " print(x.size())\n", " return x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### End" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 2 }