{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting torchtext\n",
"\u001b[?25l Downloading https://files.pythonhosted.org/packages/c6/bc/b28b9efb4653c03e597ed207264eea45862b5260f48e9f010b5068d64db1/torchtext-0.3.1-py3-none-any.whl (62kB)\n",
"\u001b[K |████████████████████████████████| 71kB 1.5MB/s eta 0:00:011\n",
"\u001b[?25hRequirement already satisfied: torch in /anaconda3/lib/python3.6/site-packages (from torchtext) (0.4.1)\n",
"Requirement already satisfied: numpy in /anaconda3/lib/python3.6/site-packages (from torchtext) (1.14.5)\n",
"Collecting tqdm (from torchtext)\n",
"\u001b[?25l Downloading https://files.pythonhosted.org/packages/9f/3d/7a6b68b631d2ab54975f3a4863f3c4e9b26445353264ef01f465dc9b0208/tqdm-4.32.2-py2.py3-none-any.whl (50kB)\n",
"\u001b[K |████████████████████████████████| 51kB 7.1MB/s eta 0:00:01\n",
"\u001b[?25hRequirement already satisfied: requests in /anaconda3/lib/python3.6/site-packages (from torchtext) (2.18.4)\n",
"Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /anaconda3/lib/python3.6/site-packages (from requests->torchtext) (3.0.4)\n",
"Requirement already satisfied: idna<2.7,>=2.5 in /anaconda3/lib/python3.6/site-packages (from requests->torchtext) (2.6)\n",
"Requirement already satisfied: urllib3<1.23,>=1.21.1 in /anaconda3/lib/python3.6/site-packages (from requests->torchtext) (1.22)\n",
"Requirement already satisfied: certifi>=2017.4.17 in /anaconda3/lib/python3.6/site-packages (from requests->torchtext) (2018.4.16)\n",
"Installing collected packages: tqdm, torchtext\n",
"Successfully installed torchtext-0.3.1 tqdm-4.32.2\n",
"\u001b[33mWARNING: You are using pip version 19.1, however version 19.1.1 is available.\n",
"You should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n"
]
}
],
"source": [
"!pip install torchtext"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### In this demo we will build a machine learning model to classify sms texts as ham or spam"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import accuracy_score"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### SMS Spam Collection Dataset\n",
"Source: https://www.kaggle.com/uciml/sms-spam-collection-dataset\n",
"\n",
"\n",
"The files contain one message per line. Each line is composed by two columns: v1 contains the label (ham or spam) and v2 contains the raw text."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" v1 | \n",
" v2 | \n",
" Unnamed: 2 | \n",
" Unnamed: 3 | \n",
" Unnamed: 4 | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" ham | \n",
" Go until jurong point, crazy.. Available only ... | \n",
" NaN | \n",
" NaN | \n",
" NaN | \n",
"
\n",
" \n",
" | 1 | \n",
" ham | \n",
" Ok lar... Joking wif u oni... | \n",
" NaN | \n",
" NaN | \n",
" NaN | \n",
"
\n",
" \n",
" | 2 | \n",
" spam | \n",
" Free entry in 2 a wkly comp to win FA Cup fina... | \n",
" NaN | \n",
" NaN | \n",
" NaN | \n",
"
\n",
" \n",
" | 3 | \n",
" ham | \n",
" U dun say so early hor... U c already then say... | \n",
" NaN | \n",
" NaN | \n",
" NaN | \n",
"
\n",
" \n",
" | 4 | \n",
" ham | \n",
" Nah I don't think he goes to usf, he lives aro... | \n",
" NaN | \n",
" NaN | \n",
" NaN | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" v1 v2 Unnamed: 2 \\\n",
"0 ham Go until jurong point, crazy.. Available only ... NaN \n",
"1 ham Ok lar... Joking wif u oni... NaN \n",
"2 spam Free entry in 2 a wkly comp to win FA Cup fina... NaN \n",
"3 ham U dun say so early hor... U c already then say... NaN \n",
"4 ham Nah I don't think he goes to usf, he lives aro... NaN \n",
"\n",
" Unnamed: 3 Unnamed: 4 \n",
"0 NaN NaN \n",
"1 NaN NaN \n",
"2 NaN NaN \n",
"3 NaN NaN \n",
"4 NaN NaN "
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data = pd.read_csv('datasets/ham-spam/spam.csv', encoding='latin-1')\n",
"\n",
"data.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Cleaning Data"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"data = data.drop(columns = ['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis = 1)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" labels | \n",
" text | \n",
"
\n",
" \n",
" \n",
" \n",
" | 0 | \n",
" ham | \n",
" Go until jurong point, crazy.. Available only ... | \n",
"
\n",
" \n",
" | 1 | \n",
" ham | \n",
" Ok lar... Joking wif u oni... | \n",
"
\n",
" \n",
" | 2 | \n",
" spam | \n",
" Free entry in 2 a wkly comp to win FA Cup fina... | \n",
"
\n",
" \n",
" | 3 | \n",
" ham | \n",
" U dun say so early hor... U c already then say... | \n",
"
\n",
" \n",
" | 4 | \n",
" ham | \n",
" Nah I don't think he goes to usf, he lives aro... | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" labels text\n",
"0 ham Go until jurong point, crazy.. Available only ...\n",
"1 ham Ok lar... Joking wif u oni...\n",
"2 spam Free entry in 2 a wkly comp to win FA Cup fina...\n",
"3 ham U dun say so early hor... U c already then say...\n",
"4 ham Nah I don't think he goes to usf, he lives aro..."
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data = data.rename(index = str, columns = {'v1': 'labels', 'v2': 'text'})\n",
"\n",
"data.head()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"train, test = train_test_split(data, test_size = 0.2, random_state = 42)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"( labels text\n",
" 0 ham No I'm in the same boat. Still here at my moms...\n",
" 1 spam (Bank of Granite issues Strong-Buy) EXPLOSIVE ...\n",
" 2 ham They r giving a second chance to rahul dengra.\n",
" 3 ham O i played smash bros <#> religiously.\n",
" 4 spam PRIVATE! Your 2003 Account Statement for 07973...\n",
" 5 ham G says you never answer your texts, confirm/deny\n",
" 6 spam 88066 FROM 88066 LOST 3POUND HELP\n",
" 7 ham Okey dokey, iÛ÷ll be over in a bit just sorti...\n",
" 8 ham Why i come in between you people\n",
" 9 ham Wah lucky man... Then can save money... Hee...\n",
" 10 ham Much better now thanks lol\n",
" 11 ham Madam,regret disturbance.might receive a refer...\n",
" 12 ham I'm coming home 4 dinner.\n",
" 13 ham Ok...\n",
" 14 ham Can Ì_ all decide faster cos my sis going home...\n",
" 15 ham Hi mate its RV did u hav a nice hol just a mes...\n",
" 16 ham Amazing : If you rearrange these letters it gi...\n",
" 17 ham Good Morning plz call me sir\n",
" 18 ham K actually can you guys meet me at the sunoco ...\n",
" 19 ham New Theory: Argument wins d SITUATION, but los...\n",
" 20 ham Oh yeah! And my diet just flew out the window\n",
" 21 ham Watching cartoon, listening music & at eve...\n",
" 22 ham If india win or level series means this is rec...\n",
" 23 ham Armand says get your ass over to epsilon\n",
" 24 ham TELL HER I SAID EAT SHIT.\n",
" 25 ham Oh, then your phone phoned me but it disconnected\n",
" 26 spam Please call our customer service representativ...\n",
" 27 ham Hey sweet, I was wondering when you had a mome...\n",
" 28 ham Purity of friendship between two is not about ...\n",
" 29 spam Not heard from U4 a while. Call me now am here...\n",
" ... ... ...\n",
" 4427 ham Ya had just now.onion roast.\n",
" 4428 ham No de. But call me after some time. Ill tell y...\n",
" 4429 ham Some friends want me to drive em someplace, pr...\n",
" 4430 ham Send to someone else :-)\n",
" 4431 ham Nice line said by a broken heart- Plz don't cu...\n",
" 4432 ham Ha. You donÛ÷t know either. I did a a clever ...\n",
" 4433 spam YOU HAVE WON! As a valued Vodafone customer ou...\n",
" 4434 ham Watch lor. I saw a few swatch one i thk quite ...\n",
" 4435 ham Oops - am at my mum's in somerset... Bit far! ...\n",
" 4436 ham Gettin rdy to ship comp\n",
" 4437 ham Yo, you around? Just got my car back\n",
" 4438 ham Tick, tick, tick .... Where are you ? I could ...\n",
" 4439 ham K.k:)i'm going to tirunelvali this week to see...\n",
" 4440 ham Indians r poor but India is not a poor country...\n",
" 4441 ham PICK UR FONE UP NOW U DUMB?\n",
" 4442 ham Lol I know! They're so dramatic. Schools alrea...\n",
" 4443 ham Cramps stopped. Going back to sleep\n",
" 4444 ham I'm home.\n",
" 4445 ham Thanx 4 the time weåÕve spent 2geva, its bin m...\n",
" 4446 ham Do u still have plumbers tape and a wrench we ...\n",
" 4447 ham wiskey Brandy Rum Gin Beer Vodka Scotch Shampa...\n",
" 4448 ham So what did the bank say about the money?\n",
" 4449 ham Garbage bags, eggs, jam, bread, hannaford whea...\n",
" 4450 ham They don't put that stuff on the roads to keep...\n",
" 4451 ham staff.science.nus.edu.sg/~phyhcmk/teaching/pc1323\n",
" 4452 ham I came hostel. I m going to sleep. Plz call me...\n",
" 4453 ham Sorry, I'll call later\n",
" 4454 ham Prabha..i'm soryda..realy..frm heart i'm sory\n",
" 4455 ham Nt joking seriously i told\n",
" 4456 ham In work now. Going have in few min.\n",
" \n",
" [4457 rows x 2 columns],\n",
" labels text\n",
" 0 ham Funny fact Nobody teaches volcanoes 2 erupt, t...\n",
" 1 ham I sent my scores to sophas and i had to do sec...\n",
" 2 spam We know someone who you know that fancies you....\n",
" 3 ham Only if you promise your getting out as SOON a...\n",
" 4 spam Congratulations ur awarded either å£500 of CD ...\n",
" 5 ham I'll text carlos and let you know, hang on\n",
" 6 ham K.i did't see you.:)k:)where are you now?\n",
" 7 ham No message..no responce..what happend?\n",
" 8 ham Get down in gandhipuram and walk to cross cut ...\n",
" 9 ham You flippin your shit yet?\n",
" 10 ham For real tho this sucks. I can't even cook my ...\n",
" 11 spam Free tones Hope you enjoyed your new content. ...\n",
" 12 ham I'm wif him now buying tix lar...\n",
" 13 ham Call me when u finish then i come n pick u.\n",
" 14 ham Dear how is chechi. Did you talk to her\n",
" 15 ham What's up. Do you want me to come online?\n",
" 16 ham Were somewhere on Fredericksburg\n",
" 17 spam URGENT! Your mobile was awarded a å£1,500 Bonu...\n",
" 18 ham When can Ì_ come out?\n",
" 19 ham K, if u bored up just come to my home..\n",
" 20 ham Can Ì_ call me at 10:10 to make sure dat i've ...\n",
" 21 ham Boy; I love u Grl: Hogolo Boy: gold chain kods...\n",
" 22 ham A bloo bloo bloo I'll miss the first bowl\n",
" 23 ham Yeah sure, give me a couple minutes to track d...\n",
" 24 spam This is the 2nd time we have tried 2 contact u...\n",
" 25 ham No it was cancelled yeah baby! Well that sound...\n",
" 26 ham Its not the same here. Still looking for a job...\n",
" 27 ham Gud gud..k, chikku tke care.. sleep well gud nyt\n",
" 28 ham I'll reach in ard 20 mins ok...\n",
" 29 ham Wat Ì_ doing now?\n",
" ... ... ...\n",
" 1085 spam You are guaranteed the latest Nokia Phone, a 4...\n",
" 1086 ham Then we gotta do it after that\n",
" 1087 ham I'll be late...\n",
" 1088 spam Do you want a new video handset? 750 anytime a...\n",
" 1089 spam Win the newest åÒHarry Potter and the Order of...\n",
" 1090 ham Pls confirm the time to collect the cheque.\n",
" 1091 ham no, i *didn't* mean to post it. I wrote it, an...\n",
" 1092 ham You will be in the place of that man\n",
" 1093 spam Hi babe its Chloe, how r u? I was smashed on s...\n",
" 1094 ham I will see in half an hour\n",
" 1095 ham Lol, oh you got a friend for the dog ?\n",
" 1096 ham Ill call you evening ill some ideas.\n",
" 1097 ham Thursday night? Yeah, sure thing, we'll work i...\n",
" 1098 ham 7 at esplanade.. Do Ì_ mind giving me a lift c...\n",
" 1099 ham My house here e sky quite dark liao... If rain...\n",
" 1100 ham Thankyou so much for the call. I appreciate yo...\n",
" 1101 ham Purity of friendship between two is not about ...\n",
" 1102 ham Ok...\n",
" 1103 ham Carlos took a while (again), we leave in a minute\n",
" 1104 ham Takin a shower now but yeah I'll leave when I'...\n",
" 1105 ham New Theory: Argument wins d SITUATION, but los...\n",
" 1106 spam Sex up ur mobile with a FREE sexy pic of Jorda...\n",
" 1107 ham Hello. No news on job, they are making me wait...\n",
" 1108 ham Ok how you dear. Did you call chechi\n",
" 1109 ham K still are you loving me.\n",
" 1110 ham <DECIMAL> m but its not a common car he...\n",
" 1111 ham Rightio. 11.48 it is then. Well arent we all u...\n",
" 1112 ham Yes i have. So that's why u texted. Pshew...mi...\n",
" 1113 ham Get the door, I'm here\n",
" 1114 spam Kit Strip - you have been billed 150p. Netcoll...\n",
" \n",
" [1115 rows x 2 columns])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train.reset_index(drop=True), test.reset_index(drop=True)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" labels | \n",
" text | \n",
"
\n",
" \n",
" \n",
" \n",
" | 1978 | \n",
" ham | \n",
" No I'm in the same boat. Still here at my moms... | \n",
"
\n",
" \n",
" | 3989 | \n",
" spam | \n",
" (Bank of Granite issues Strong-Buy) EXPLOSIVE ... | \n",
"
\n",
" \n",
" | 3935 | \n",
" ham | \n",
" They r giving a second chance to rahul dengra. | \n",
"
\n",
" \n",
" | 4078 | \n",
" ham | \n",
" O i played smash bros <#> religiously. | \n",
"
\n",
" \n",
" | 4086 | \n",
" spam | \n",
" PRIVATE! Your 2003 Account Statement for 07973... | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" labels text\n",
"1978 ham No I'm in the same boat. Still here at my moms...\n",
"3989 spam (Bank of Granite issues Strong-Buy) EXPLOSIVE ...\n",
"3935 ham They r giving a second chance to rahul dengra.\n",
"4078 ham O i played smash bros <#> religiously.\n",
"4086 spam PRIVATE! Your 2003 Account Statement for 07973..."
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train.head()"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"\n",
"
\n",
" \n",
" \n",
" | \n",
" labels | \n",
" text | \n",
"
\n",
" \n",
" \n",
" \n",
" | 3245 | \n",
" ham | \n",
" Funny fact Nobody teaches volcanoes 2 erupt, t... | \n",
"
\n",
" \n",
" | 944 | \n",
" ham | \n",
" I sent my scores to sophas and i had to do sec... | \n",
"
\n",
" \n",
" | 1044 | \n",
" spam | \n",
" We know someone who you know that fancies you.... | \n",
"
\n",
" \n",
" | 2484 | \n",
" ham | \n",
" Only if you promise your getting out as SOON a... | \n",
"
\n",
" \n",
" | 812 | \n",
" spam | \n",
" Congratulations ur awarded either å£500 of CD ... | \n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" labels text\n",
"3245 ham Funny fact Nobody teaches volcanoes 2 erupt, t...\n",
"944 ham I sent my scores to sophas and i had to do sec...\n",
"1044 spam We know someone who you know that fancies you....\n",
"2484 ham Only if you promise your getting out as SOON a...\n",
"812 spam Congratulations ur awarded either å£500 of CD ..."
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test.head()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((4457, 2), (1115, 2))"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train.shape, test.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Saving Train and test data in csv files"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"train.to_csv('datasets/ham-spam/train.csv', index=False)\n",
"test.to_csv('datasets/ham-spam/test.csv', index=False)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[31mspam.csv\u001b[m\u001b[m \u001b[31mtest.csv\u001b[m\u001b[m \u001b[31mtrain.csv\u001b[m\u001b[m\r\n"
]
}
],
"source": [
"!ls datasets/ham-spam"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"import torch\n",
"import torchtext\n",
"\n",
"from torchtext.data import Field, BucketIterator, TabularDataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### NLTK provides a function called word_tokenize() for splitting strings into tokens (nominally words). It splits tokens based on white space and punctuation."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package punkt to\n",
"[nltk_data] /Users/jananiravi/nltk_data...\n",
"[nltk_data] Package punkt is already up-to-date!\n"
]
}
],
"source": [
"import nltk\n",
"nltk.download('punkt')\n",
"\n",
"from nltk import word_tokenize"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### The parameters of a Field specify how the data should be processed.We use the TEXT field to define how the text should be processed, and the LABEL field to process the labels."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"TEXT = torchtext.data.Field(tokenize = word_tokenize)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"LABEL = torchtext.data.LabelField(dtype = torch.float)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"datafields = [(\"labels\", LABEL), (\"text\", TEXT)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### the following code splits data into the canonical train/test splits as torchtext.datasets objects. It process the data using the Fields we have previously defined."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"trn, tst = torchtext.data.TabularDataset.splits(path = './datasets/ham-spam', \n",
" train = 'train.csv',\n",
" test = 'test.csv' , \n",
" format = 'csv',\n",
" skip_header = True,\n",
" fields = datafields)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[,\n",
" ,\n",
" ,\n",
" ,\n",
" ]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trn[:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We can see how many examples are in each split by checking their length."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of training examples: 4457\n",
"Number of testing examples: 1115\n"
]
}
],
"source": [
"print(f'Number of training examples: {len(trn)}')\n",
"print(f'Number of testing examples: {len(tst)}')"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['labels', 'text'])"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trn[5].__dict__.keys()"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['G', 'says', 'you', 'never', 'answer', 'your', 'texts', ',', 'confirm/deny']"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trn[5].text"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ham'"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"trn[5].labels"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We can also check an example."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'labels': 'ham', 'text': ['G', 'says', 'you', 'never', 'answer', 'your', 'texts', ',', 'confirm/deny']}\n"
]
}
],
"source": [
"print(vars(trn.examples[5]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"#### Next, we have to build a vocabulary. This is a effectively a look up table where every unique word in your data set has a corresponding index (an integer). Each index is used to construct a one-hot vector for each word.\n",
"There are two ways effectively cut down our vocabulary, we can either only take the top $n$ most common words or ignore words that appear less than $m$ times. We'll do the former, only keeping the top 10,500 words.\n",
"The words that appear in examples but we have cut from the are replaced with a special unknown token."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"TEXT.build_vocab(trn, max_size = 10500)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"LABEL.build_vocab(trn)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The vocab size is 10502 because, one of the addition tokens is the unk token and the other is a pad token."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Unique tokens in TEXT vocabulary: 10502\n",
"Unique tokens in LABEL vocabulary: 2\n"
]
}
],
"source": [
"print(f\"Unique tokens in TEXT vocabulary: {len(TEXT.vocab)}\")\n",
"print(f\"Unique tokens in LABEL vocabulary: {len(LABEL.vocab)}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We can also view the most common words in the vocabulary and their frequencies."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('.', 3890), ('to', 1750), ('I', 1571), (',', 1468), ('you', 1460), ('?', 1256), ('!', 1134), ('a', 1067), ('...', 1007), ('the', 946), ('&', 772), ('i', 743), ('and', 669), ('in', 663), ('is', 646), (';', 641), ('u', 628), ('me', 586), (':', 570), ('for', 527), ('my', 494), ('of', 471), ('your', 461), ('it', 456), ('have', 395), ('on', 393), (')', 393), ('2', 390), ('that', 384), (\"'s\", 383), (\"'m\", 320), ('now', 317), ('are', 316), ('do', 311), ('call', 307), ('at', 301), ('or', 298), ('U', 295), ('not', 294), (\"n't\", 281), ('be', 275), ('lt', 267), ('gt', 267), ('with', 267), ('get', 265), ('will', 263), ('so', 252), ('#', 245), ('can', 243), ('ur', 237)]\n"
]
}
],
"source": [
"print(TEXT.vocab.freqs.most_common(50))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We can also see the vocabulary directly using either the stoi (string to int) or itos (int to string) method."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['', '', '.', 'to', 'I', ',', 'you', '?', '!', 'a']\n"
]
}
],
"source": [
"print(TEXT.vocab.itos[:10])"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"defaultdict(, {'ham': 0, 'spam': 1})\n"
]
}
],
"source": [
"print(LABEL.vocab.stoi)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we will create iterators that will iterate over these in the training/evaluation loop, and they return a batch of examples (indexed and converted into tensors) at each iteration.\n",
"#### We'll use a BucketIterator which is a special type of iterator that will return a batch of examples where each example is of a similar length, minimizing the amount of padding per example."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"batch_size = 64\n",
"\n",
"train_iterator, test_iterator = torchtext.data.BucketIterator.splits(\n",
" (trn, tst),\n",
" batch_size = batch_size,\n",
" sort_key = lambda x: len(x.text), \n",
" sort_within_batch = False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Build The Model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- The embedding layer is used to transform our sparse one-hot vector (sparse as most of the elements are 0) into a dense embedding vector\n",
"- The RNN layer is our RNN which takes in our dense vector and the previous hidden state $h_{t-1}$, which it uses to calculate the next hidden state, $h_t$\n",
"- Finally, the linear layer takes the final hidden state and feeds it through a fully connected layer, $f(h_T)$, transforming it to the correct output dimension.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The RNN returns 2 tensors, output of size [sentence length, batch size, hidden dim] and hidden of size [1, batch size, hidden dim]. output is the concatenation of the hidden state from every time step, whereas hidden is simply the final hidden state. We verify this using the assert statement. Note the squeeze method, which is used to remove a dimension of size 1. Finally, we feed the last hidden state, hidden, through the linear layer, fc, to produce a prediction."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"import torch.nn as nn"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"class RNN(nn.Module):\n",
" \n",
" def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim):\n",
" \n",
" super().__init__()\n",
" \n",
" self.embedding = nn.Embedding(input_dim, embedding_dim)\n",
" \n",
" self.rnn = nn.RNN(embedding_dim, hidden_dim)\n",
" \n",
" self.fc = nn.Linear(hidden_dim, output_dim)\n",
" \n",
" def forward(self, text):\n",
" \n",
" embedded = self.embedding(text)\n",
" \n",
" output, hidden = self.rnn(embedded)\n",
" \n",
" hidden_1D = hidden.squeeze(0)\n",
" \n",
" assert torch.equal(output[-1, :, :], hidden_1D)\n",
" \n",
" return self.fc(hidden_1D)"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"class RNN(nn.Module):\n",
" \n",
" def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim):\n",
" \n",
" super().__init__()\n",
" \n",
" self.embedding = nn.Embedding(input_dim, embedding_dim)\n",
" \n",
" self.rnn = nn.LSTM(embedding_dim, hidden_dim)\n",
" \n",
" self.fc = nn.Linear(hidden_dim, output_dim)\n",
" \n",
" def forward(self, text):\n",
" \n",
" embedded = self.embedding(text)\n",
" \n",
" output, (hidden, _) = self.rnn(embedded)\n",
" \n",
" hidden_1D = hidden.squeeze(0)\n",
" \n",
" assert torch.equal(output[-1, :, :], hidden_1D)\n",
" \n",
" return self.fc(hidden_1D)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [],
"source": [
"class RNN(nn.Module):\n",
" \n",
" def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim):\n",
" \n",
" super().__init__()\n",
" \n",
" self.embedding = nn.Embedding(input_dim, embedding_dim)\n",
" \n",
" self.rnn = nn.LSTM(embedding_dim, hidden_dim)\n",
" \n",
" self.fc = nn.Linear(hidden_dim, output_dim)\n",
" \n",
" self.dropout = nn.Dropout(0.3)\n",
" \n",
" def forward(self, text):\n",
" \n",
" embedded = self.embedding(text)\n",
" \n",
" embedded_dropout = self.dropout(embedded)\n",
" \n",
" output, (hidden, _) = self.rnn(embedded_dropout)\n",
" \n",
" hidden_1D = hidden.squeeze(0)\n",
" \n",
" assert torch.equal(output[-1, :, :], hidden_1D)\n",
" \n",
" return self.fc(hidden_1D)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We now create an instance of our RNN class.\n",
"\n",
"- The input dimension is the dimension of the one-hot vectors, which is equal to the vocabulary size.\n",
"- The embedding dimension is the size of the dense word vectors.\n",
"- The hidden dimension is the size of the hidden states\n",
"- The output dimension is usually the number of classes, however in the case of only 2 classes the output value is between 0 and 1 and thus can be 1-dimensional, i.e. a single scalar real number."
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"input_dim = len(TEXT.vocab)\n",
"\n",
"embedding_dim = 100\n",
"\n",
"hidden_dim = 256\n",
"\n",
"output_dim = 1"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [],
"source": [
"model = RNN(input_dim, embedding_dim, hidden_dim, output_dim)"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"import torch.optim as optim\n",
"\n",
"optimizer = optim.Adam(model.parameters(), lr = 1e-6)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### we will use BCEWithLogitsLoss loss as our loss function - Creates a criterion that measures the Binary Cross Entropy between the target and the output\n",
"This loss combines a Sigmoid layer and the BCELoss in one single class."
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"criterion = nn.BCEWithLogitsLoss()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Training\n",
"- For each batch, we first zero the gradients. Each parameter in a model has a grad attribute which stores the gradient calculated by the criterion.\n",
"- We then feed the batch of sentences, batch.text, into the model\n",
"- The loss and accuracy are then calculated using our predictions and the labels, batch.labels, with the loss being averaged over all examples in the batch.\n",
"- We calculate the gradient of each parameter and then update the parameters using the gradients and optimizer algorithm\n",
"- Finally, we return the loss and accuracy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Calculating Accuracy \n",
"We first feeds the predictions through a sigmoid layer, squashing the values between 0 and 1, we then round them to the nearest integer. This rounds any value greater than 0.5 to 1 (spam) and the rest to 0 (ham).\n",
"\n",
"We then calculate how many rounded predictions equal the actual labels and average it across the batch."
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"def train(model, iterator, optimizer, criterion):\n",
" \n",
" epoch_loss = 0\n",
" epoch_acc = 0\n",
" \n",
" model.train()\n",
" \n",
" for batch in iterator:\n",
" \n",
" optimizer.zero_grad()\n",
" \n",
" predictions = model(batch.text).squeeze(1)\n",
" \n",
" loss = criterion(predictions, batch.labels)\n",
" \n",
" rounded_preds = torch.round(torch.sigmoid(predictions))\n",
" correct = (rounded_preds == batch.labels).float() \n",
" \n",
" acc = correct.sum() / len(correct)\n",
" \n",
" loss.backward()\n",
" \n",
" optimizer.step()\n",
" \n",
" epoch_loss += loss.item()\n",
" epoch_acc += acc.item()\n",
" \n",
" return epoch_loss / len(iterator), epoch_acc / len(iterator)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### the loss is decreasing with each epoch and we get a final accuracy of ~85%"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"| Epoch: 01 | Train Loss: 0.625 | Train Acc: 85.87% \n",
"| Epoch: 02 | Train Loss: 0.612 | Train Acc: 85.86% \n",
"| Epoch: 03 | Train Loss: 0.601 | Train Acc: 85.95% \n",
"| Epoch: 04 | Train Loss: 0.590 | Train Acc: 86.02% \n",
"| Epoch: 05 | Train Loss: 0.579 | Train Acc: 85.98% \n"
]
}
],
"source": [
"num_epochs = 5\n",
"\n",
"for epoch in range(num_epochs):\n",
"\n",
" train_loss, train_acc = train(model, train_iterator, optimizer, criterion)\n",
" \n",
" print(f'| Epoch: {epoch+1:02} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}% ')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"evaluate is similar to train, with a few modifications as you don't want to update the parameters when evaluating."
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"epoch_loss = 0\n",
"epoch_acc = 0"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"RNN(\n",
" (embedding): Embedding(10502, 100)\n",
" (rnn): LSTM(100, 256)\n",
" (fc): Linear(in_features=256, out_features=1, bias=True)\n",
" (dropout): Dropout(p=0.3)\n",
")"
]
},
"execution_count": 68,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.eval()"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"| Test Loss: 0.649 | Test Acc: 75.23% |\n"
]
}
],
"source": [
"with torch.no_grad():\n",
"\n",
" for batch in test_iterator:\n",
"\n",
" predictions = model(batch.text).squeeze(1)\n",
"\n",
" loss = criterion(predictions, batch.labels)\n",
"\n",
" rounded_preds = torch.round(torch.sigmoid(predictions))\n",
" \n",
" correct = (rounded_preds == batch.labels).float() \n",
" acc = correct.sum() / len(correct)\n",
"\n",
" epoch_loss += loss.item()\n",
" epoch_acc += acc.item()\n",
"\n",
"test_loss = epoch_loss / len(test_iterator)\n",
"test_acc = epoch_acc / len(test_iterator)\n",
"\n",
"print(f'| Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}% |')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"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.6.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}