"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"fig = plt.figure(figsize=(12, 8))\n",
"\n",
"ax = sns.barplot(x=tweets.Sentiment.unique(), y=tweets.Sentiment.value_counts())\n",
"\n",
"ax.set(xlabel='Labels')"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"\n",
"train, test = train_test_split(tweets, test_size=0.2, random_state=42)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"( Sentiment SentimentText\n",
" 0 pos @amyrenea omg so am I lol I fell asleep when i...\n",
" 1 neg @Adrienne_Bailon I want a shout out \n",
" 2 neg @Anonymousboy03 Plans for school stuff & a...\n",
" 3 neg ... has hit a writer's block .. am loosing my ...\n",
" 4 neg ... trying to find people I know! I`m bored, i...\n",
" 5 pos "Rise from your grave!"�finalmente...\n",
" 6 pos @1RedDiamond it is where I live\n",
" 7 neg @anthonystonem But I'm almost as fat as her \n",
" 8 pos @Addicted2Golf I am getting addicted. Almost ...\n",
" 9 pos @Abongachong Ahem, ignore the last tweet. Thou...\n",
" 10 pos *cough* LOL. Okay. @LOXX\n",
" 11 pos @_huny enter the zoom lens \n",
" 12 pos ....ok, sOooooooooo I DID that!! i've got u in...\n",
" 13 pos @28parkave well done you! I need to do my meas...\n",
" 14 neg @alunvaughan I think a lot aren't really in fo...\n",
" 15 pos ..Listening to "Glamourous" by Fergi...\n",
" 16 pos @AlphaNorth 9:30/10. I have a ride today\n",
" 17 pos @AlexAlas I'm in the mood for a Flinstones vit...\n",
" 18 pos @adamrocks my uncle picked up some there yeste...\n",
" 19 neg #inaperfectworld @dwighthoward would be wearin...\n",
" 20 neg stupid texts being late for no reason.\n",
" 21 neg @AlexanderSpit I don't have the energy to put ...\n",
" 22 neg @ajbutie not yet his loss\n",
" 23 neg "StumbleUpon has temporarily run out of s...\n",
" 24 pos ??? MAY SALE!!! 30% OFF EVERYTHING @ RED METAL...\n",
" 25 pos - you're welcome http://aweber.com/b/22u8Z\n",
" 26 pos #Goodsex When your partner follows you on mysp...\n",
" 27 pos "i am a vampire, i am a vampire...but i h...\n",
" 28 neg @@vooveth carpooltunnel i think! how lame &am...\n",
" 29 pos ...It's because you have to know!!! Grand Open...\n",
" ... ... ...\n",
" 39970 pos @copicmarker" facebook.com/copic.marker i...\n",
" 39971 pos I just don't know how to begin this twitter t...\n",
" 39972 pos .@fourchickens I just swan around in them with...\n",
" 39973 pos @_alii yaaaay haha i think it could be a good...\n",
" 39974 pos @615Redbone ham, turkey, cheese, amd mayo plea...\n",
" 39975 neg @andwhenyousing unless adam's 6ft 3 ness beat ...\n",
" 39976 pos @agiftedmind YAAAY \n",
" 39977 pos #favoritelyrics anything by LUPE FIASCO. \n",
" 39978 pos @aj_michalka No problems Twitter rocks im a t...\n",
" 39979 neg @ i wanna go home, so miss my mom \n",
" 39980 neg ...I've got the biggest crush on Kevin James. \n",
" 39981 pos @Alybean I suffer from a very bad case of fing...\n",
" 39982 pos @alliewayfilms No I won't I want to follow you \n",
" 39983 pos #follow @spreadingjoy the name say it all \n",
" 39984 neg i am regretting getting that film developed.....\n",
" 39985 pos @LisaBarone If, thru the miracle of modern sc...\n",
" 39986 neg I keep getting errors on iPhone and it saves ...\n",
" 39987 pos @andrewfaith sorry, old Habits are hard to break \n",
" 39988 neg .I feel so mcuh preasure and no answers in my ...\n",
" 39989 pos @ankita_gaba Get well soon and no working on s...\n",
" 39990 neg @AQuietMadness just block everyone out. Can y...\n",
" 39991 neg @3EG nothing just inside b/c its raining yup ...\n",
" 39992 pos @amabaie Oh no 'm already there I can't be you...\n",
" 39993 neg ... Tried really hard to stay and socialize bu...\n",
" 39994 neg #dontyouhate when you try to be sumbody everyt...\n",
" 39995 pos #robotpickuplines are so funny. check them out. \n",
" 39996 pos @annyo84 awh thankss. yeah, i understand what...\n",
" 39997 pos @AmbiguityX ohh you're in twin cities? i luv ...\n",
" 39998 neg Dinara lost again in Roland Garros. Why the S...\n",
" 39999 pos *yawn* fucking time zones shit. I'm really sic...\n",
" \n",
" [40000 rows x 2 columns],\n",
" Sentiment SentimentText\n",
" 0 pos @aimeesays aww i hope it does fly by because J...\n",
" 1 neg #dontyouhate when you JUST painted yur nails a...\n",
" 2 neg - @EvertB which one? http://bit.ly/10o8LW, htt...\n",
" 3 pos *shriek* Bee almost flew here from window. I'm...\n",
" 4 pos @Alyssa_Milano granted if we lose it is to a w...\n",
" 5 neg @AnG_CaKe i dont have a choice man. there'll b...\n",
" 6 pos #jonaswebcast Cant wait for another one \n",
" 7 neg @AshleyNikole4 awww. Look at u all sad and shit!\n",
" 8 neg why? GOODNIGHT WORLD.\n",
" 9 neg @AliC66 NOT GOING no friends x\n",
" 10 pos @AngelicaPreston He is my favorite person of ...\n",
" 11 pos @amoxyspasm you talking bout us or the actual ...\n",
" 12 neg skool holidays are over and skool sux but we ...\n",
" 13 neg but why not? @kathrynYO\n",
" 14 pos .@MyInnerChild oh shit i'm sorry Jules!!! i'd ...\n",
" 15 neg @ak618 maybe for the best Torres didn't play--...\n",
" 16 pos ..back home \n",
" 17 neg @ak618 no it's the 1 game in the homestand I'...\n",
" 18 neg *sniffles* I wish I could go to Camp Broadway ...\n",
" 19 pos *editing some NEW photos. Late aft lovies. \n",
" 20 neg sad because MTV music awards isn't being aire...\n",
" 21 neg . . . yeah fuck that shit. Also kind of bored ...\n",
" 22 pos church with matt,was...good. I think I'm goin...\n",
" 23 pos (Tip: Good music- and hot tub, if possible- wi...\n",
" 24 neg ... procrastinating in the net \n",
" 25 pos @AdrianneCurry Did you know that Lionel Ritchi...\n",
" 26 pos @andy_lamb yeah that one might have a kick \n",
" 27 pos @adarh I'll next time \n",
" 28 neg @alineab Eeew-off to airport & whoever djt...\n",
" 29 neg @aianna21 And booo, I want twin tiiiiime. It's...\n",
" ... ... ...\n",
" 9970 neg @5by5forever Dang it im jealous! I want to see...\n",
" 9971 neg @ashleybella we'll blast the CD on the way the...\n",
" 9972 neg @ainojonas yes I know I can't. but I just can...\n",
" 9973 neg @aliaargh sorry aly, I dont go to your party \n",
" 9974 pos @ajmclean_team Yep. \n",
" 9975 neg #Blink182 tickets went on sale in Phoenix. 55$...\n",
" 9976 pos @alexzealand Thank ya kindly! I'm thinking o...\n",
" 9977 neg @acidnation stop angryfacing me you shoulda j...\n",
" 9978 neg @ work. on day #6. whts goin on with everyone?\n",
" 9979 pos @AndyGroenink God bless you, man! \n",
" 9980 neg @apollo_b4 I was up... But now I'm in class.\n",
" 9981 neg @andreatrasatti at this point, I guess I would...\n",
" 9982 neg @Alyssa_Milano did you see the new Star Trek m...\n",
" 9983 pos @amybaby63 Yep. 16th June is my last exam (med...\n",
" 9984 pos #or09 MattZ admits to Teh Clumsy.\n",
" 9985 pos @akiville how much u ask for it? \n",
" 9986 pos @acttdanceesingg hey carly! XD my names carly ...\n",
" 9987 pos @alliegirl97 yep lol heard that once from a ga...\n",
" 9988 pos @archreena Nako, matulog ka na. I'll do the pr...\n",
" 9989 pos #followFriday @Angel42579 <-- she likes Vegas\n",
" 9990 pos @Adam9309 good morning my wee darling!...*waving*\n",
" 9991 pos @angiedarintip i'm only gonna watch this cuz i...\n",
" 9992 neg .@paloguitars But I luffs you! Only told you y...\n",
" 9993 pos @alli_cat141 i know! shoes are good! *.*\n",
" 9994 neg @aeayling jk ill take any of them!\n",
" 9995 neg @aisforamylynn you're a badass for having a ba...\n",
" 9996 pos @acts_rox I'm not particular about it being f...\n",
" 9997 pos @@j311stp and the same to you!\n",
" 9998 pos .@nanere Sheila I heart you!! That "Holly...\n",
" 9999 neg not the same without a goodnight....hm. Wish ...\n",
" \n",
" [10000 rows x 2 columns])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train.reset_index(drop=True), test.reset_index(drop=True)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"
\n",
" \n",
"
\n",
"
\n",
"
Sentiment
\n",
"
SentimentText
\n",
"
\n",
" \n",
" \n",
"
\n",
"
39087
\n",
"
pos
\n",
"
@amyrenea omg so am I lol I fell asleep when i...
\n",
"
\n",
"
\n",
"
30893
\n",
"
neg
\n",
"
@Adrienne_Bailon I want a shout out
\n",
"
\n",
"
\n",
"
45278
\n",
"
neg
\n",
"
@Anonymousboy03 Plans for school stuff & a...
\n",
"
\n",
"
\n",
"
16398
\n",
"
neg
\n",
"
... has hit a writer's block .. am loosing my ...
\n",
"
\n",
"
\n",
"
13653
\n",
"
neg
\n",
"
... trying to find people I know! I`m bored, i...
\n",
"
\n",
" \n",
"
\n",
"
"
],
"text/plain": [
" Sentiment SentimentText\n",
"39087 pos @amyrenea omg so am I lol I fell asleep when i...\n",
"30893 neg @Adrienne_Bailon I want a shout out \n",
"45278 neg @Anonymousboy03 Plans for school stuff & a...\n",
"16398 neg ... has hit a writer's block .. am loosing my ...\n",
"13653 neg ... trying to find people I know! I`m bored, i..."
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train.head()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((40000, 2), (10000, 2))"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train.shape, test.shape"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"train.to_csv('datasets/tweets/train_tweets.csv', index=False)\n",
"test.to_csv('datasets/tweets/test_tweets.csv', index=False)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[31mtest_tweets.csv\u001b[m\u001b[m \u001b[31mtrain_tweets.csv\u001b[m\u001b[m \u001b[31mtweets.csv\u001b[m\u001b[m\r\n"
]
}
],
"source": [
"!ls datasets/tweets"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### defining a funtion to clean the tweets by removing non alphanumeric character and links "
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"def tweet_clean(text):\n",
" \n",
" text = re.sub(r'[^A-Za-z0-9]+', ' ', text) \n",
" text = re.sub(r'https?:/\\/\\S+', ' ', text) \n",
" \n",
" return text.strip()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### The tweet column (‘SentimentText’) needs processing and tokenization, so that it can be converted into indices."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"nlp = spacy.load('en', disable=['parser', 'tagger', 'ner'])\n",
"\n",
"def tokenizer(s): \n",
" return [w.text.lower() for w in nlp(tweet_clean(s))]"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"TEXT = torchtext.data.Field(tokenize = tokenizer)\n",
"\n",
"LABEL = torchtext.data.LabelField(dtype = torch.float)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"datafields = [('Sentiment', LABEL), ('SentimentText', TEXT)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We create torchtext dataset,TabularDataset which is specially designed to read csv and tsv files and process them. It is a wrapper around pytorch Dataset with additional features. "
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"trn, tst = torchtext.data.TabularDataset.splits(path = 'datasets/tweets/', \n",
" train = 'train_tweets.csv',\n",
" test = 'test_tweets.csv', \n",
" format = 'csv',\n",
" skip_header = True,\n",
" fields = datafields)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of training examples: 40000\n",
"Number of testing examples: 10000\n"
]
}
],
"source": [
"print(f'Number of training examples: {len(trn)}')\n",
"print(f'Number of testing examples: {len(tst)}')"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Sentiment': 'pos',\n",
" 'SentimentText': ['amyrenea',\n",
" 'omg',\n",
" 'so',\n",
" 'am',\n",
" 'i',\n",
" 'lol',\n",
" 'i',\n",
" 'fell',\n",
" 'asleep',\n",
" 'when',\n",
" 'it',\n",
" 'was',\n",
" 'on',\n",
" 'last',\n",
" 'night',\n",
" 'so',\n",
" 'now',\n",
" 'i',\n",
" 'get',\n",
" 'to',\n",
" 'finish',\n",
" 'it']}"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vars(trn.examples[0])"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Sentiment': 'pos',\n",
" 'SentimentText': ['aimeesays',\n",
" 'aww',\n",
" 'i',\n",
" 'hope',\n",
" 'it',\n",
" 'does',\n",
" 'fly',\n",
" 'by',\n",
" 'because',\n",
" 'jt',\n",
" 'episodes',\n",
" 'are',\n",
" 'usually',\n",
" 'really',\n",
" 'good',\n",
" 'and',\n",
" 'it',\n",
" 's',\n",
" 'early',\n",
" 'but',\n",
" 'so',\n",
" 'far',\n",
" 'this',\n",
" 'ep',\n",
" 'hassn',\n",
" 't',\n",
" 'disappointed']}"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vars(tst.examples[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Load pretrained word vectors and build vocabulary\n",
"Now, instead of having our word embeddings initialized randomly, they are initialized with these pre-trained vectors. We get these vectors simply by specifying which vectors we want and passing it as an argument to build_vocab. TorchText handles downloading the vectors and associating them with the correct words in our vocabulary."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"TEXT.build_vocab(trn, max_size=25000,\n",
" vectors=\"glove.6B.100d\",\n",
" unk_init=torch.Tensor.normal_)\n",
"\n",
"LABEL.build_vocab(trn)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[('i', 25644), ('the', 12219), ('to', 12111), ('you', 10723), ('a', 9197), ('it', 8440), ('and', 6889), ('my', 6208), ('quot', 5582), ('s', 5564), ('that', 5306), ('is', 5203), ('for', 4971), ('in', 4852), ('t', 4844), ('m', 4683), ('me', 4588), ('of', 4331), ('on', 3918), ('have', 3752), ('so', 3612), ('but', 3506), ('be', 2932), ('not', 2887), ('was', 2775), ('just', 2724), ('can', 2523), ('do', 2418), ('are', 2351), ('your', 2320), ('with', 2269), ('good', 2203), ('like', 2173), ('at', 2131), ('no', 2119), ('this', 2093), ('all', 2069), ('up', 2066), ('now', 2063), ('get', 2044), ('we', 1988), ('u', 1890), ('love', 1885), ('lol', 1864), ('too', 1826), ('what', 1760), ('out', 1742), ('know', 1664), ('nt', 1608), ('amp', 1539)]\n"
]
}
],
"source": [
"print(TEXT.vocab.freqs.most_common(50))"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['', '', 'i', 'the', 'to', 'you', 'a', 'it', 'and', 'my']\n"
]
}
],
"source": [
"print(TEXT.vocab.itos[:10])"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"defaultdict(, {'pos': 0, 'neg': 1})\n"
]
}
],
"source": [
"print(LABEL.vocab.stoi)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Loading the data in batches\n",
"For data with variable length sentences torchtext provides BucketIterator() dataloader which is wrapper around pytorch Dataloader. "
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"train_iterator, test_iterator = torchtext.data.BucketIterator.splits(\n",
" (trn, tst),\n",
" batch_size = 64,\n",
" sort_key=lambda x: len(x.SentimentText),\n",
" sort_within_batch=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We'll be using a different RNN architecture called a Long Short-Term Memory (LSTM).\n",
"\n",
"torch.nn.embedding -A simple lookup table that stores embeddings of a fixed dictionary and size.This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.\n",
"\n",
"\n",
"LSTM - Applies a multi-layer long short-term memory (LSTM) RNN to an input sequence.\n",
"\n",
"bidirectional - an RNN processing the words in the sentence from the first to the last (a forward RNN), we have a second RNN processing the words in the sentence from the last to the first (a backward RNN). At time step $t$, the forward RNN is processing word $x_t$, and the backward RNN is processing word $x_{T-t+1}$.\n",
"\n",
"\n",
"Dropout - it works by randomly dropping out (setting to 0) neurons in a layer during a forward pass. The probability that each neuron is dropped out is set by a hyperparameter and each neuron with dropout applied is considered indepenently.This helps in regularization.\n"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {},
"outputs": [],
"source": [
"import torch.nn as nn\n",
"\n",
"class RNN(nn.Module):\n",
" \n",
" def __init__(self, vocab_size, embedding_dim, hidden_dim, \n",
" output_dim, n_layers, bidirectional, dropout):\n",
" \n",
" super().__init__()\n",
" \n",
" self.embedding = nn.Embedding(vocab_size, embedding_dim)\n",
" \n",
" self.rnn = nn.GRU(embedding_dim, hidden_dim, num_layers = n_layers, \n",
" bidirectional = bidirectional, dropout=dropout)\n",
" \n",
" self.fc = nn.Linear(hidden_dim*2, output_dim)\n",
" \n",
" self.dropout = nn.Dropout(dropout)\n",
"\n",
" \n",
" def forward(self, text):\n",
" \n",
" embedded = self.dropout(self.embedding(text))\n",
" \n",
" output, hidden = self.rnn(embedded)\n",
" \n",
" hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1))\n",
" \n",
" return self.fc(hidden.squeeze(0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To ensure the pre-trained vectors can be loaded into the model, the EMBEDDING_DIM must be equal to that of the pre-trained GloVe vectors loaded earlier.\n",
"\n",
"We get our pad token index from the vocabulary, getting the actual string representing the pad token from the field's pad_token attribute, which is pad by default."
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {},
"outputs": [],
"source": [
"input_dim = len(TEXT.vocab)\n",
"\n",
"embedding_dim = 100\n",
"\n",
"hidden_dim = 20\n",
"output_dim = 1\n",
"\n",
"n_layers = 2\n",
"bidirectional = True\n",
"\n",
"dropout = 0.5"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [],
"source": [
"model = RNN(input_dim, \n",
" embedding_dim, \n",
" hidden_dim, \n",
" output_dim, \n",
" n_layers, \n",
" bidirectional, \n",
" dropout)"
]
},
{
"cell_type": "code",
"execution_count": 115,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"RNN(\n",
" (embedding): Embedding(25002, 100)\n",
" (rnn): GRU(100, 20, num_layers=2, dropout=0.5, bidirectional=True)\n",
" (fc): Linear(in_features=40, out_features=1, bias=True)\n",
" (dropout): Dropout(p=0.5)\n",
")"
]
},
"execution_count": 115,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We retrieve the embeddings from the field's vocab, and check they're the correct size, [vocab size, embedding dim]"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"torch.Size([25002, 100])\n"
]
}
],
"source": [
"pretrained_embeddings = TEXT.vocab.vectors\n",
"\n",
"print(pretrained_embeddings.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We then replace the initial weights of the embedding layer with the pre-trained embeddings."
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[ 0.2017, 0.6970, -0.5827, ..., -1.1129, -0.5033, -0.7208],\n",
" [ 0.2141, 0.9815, 1.8029, ..., 0.3049, 1.0668, -0.7111],\n",
" [-0.0465, 0.6197, 0.5665, ..., -0.3762, -0.0325, 0.8062],\n",
" ...,\n",
" [ 1.2380, 1.5805, -0.2643, ..., -0.4007, -0.0272, 0.7074],\n",
" [ 2.3054, -1.1257, 1.1538, ..., 0.2036, 0.5751, -0.3229],\n",
" [-0.8496, -1.0295, 1.6804, ..., -0.7246, -0.3404, 1.6258]])"
]
},
"execution_count": 117,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.embedding.weight.data.copy_(pretrained_embeddings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As our < unk > and < pad > token aren't in the pre-trained vocabulary they have been initialized using unk_init (an $\\mathcal{N}(0,1)$ distribution) when building our vocab. It is preferable to initialize them both to all zeros to explicitly tell our model that, initially, they are irrelevant for determining sentiment."
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],\n",
" [ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],\n",
" [-0.0465, 0.6197, 0.5665, ..., -0.3762, -0.0325, 0.8062],\n",
" ...,\n",
" [ 1.2380, 1.5805, -0.2643, ..., -0.4007, -0.0272, 0.7074],\n",
" [ 2.3054, -1.1257, 1.1538, ..., 0.2036, 0.5751, -0.3229],\n",
" [-0.8496, -1.0295, 1.6804, ..., -0.7246, -0.3404, 1.6258]])\n"
]
}
],
"source": [
"unk_idx = TEXT.vocab.stoi[TEXT.unk_token]\n",
"pad_idx = TEXT.vocab.stoi[TEXT.pad_token]\n",
"\n",
"model.embedding.weight.data[unk_idx] = torch.zeros(embedding_dim)\n",
"model.embedding.weight.data[pad_idx] = torch.zeros(embedding_dim)\n",
"\n",
"print(model.embedding.weight.data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Train the Model\n",
"\n",
"We use Adam optimizer and loss function is BCEWithLogitLoss "
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [],
"source": [
"import torch.optim as optim\n",
"\n",
"optimizer = optim.Adam(model.parameters())\n",
"\n",
"criterion = nn.BCEWithLogitsLoss()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### We define a function for training our model\n",
"as we are now using dropout, we must remember to use model.train() to ensure the dropout is \"turned on\" while training."
]
},
{
"cell_type": "code",
"execution_count": 120,
"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.SentimentText).squeeze(1)\n",
" \n",
" loss = criterion(predictions, batch.Sentiment)\n",
" \n",
" rounded_preds = torch.round(torch.sigmoid(predictions))\n",
" correct = (rounded_preds == batch.Sentiment).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": "code",
"execution_count": 121,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"| Epoch: 01 | Train Loss: 0.645 | Train Acc: 61.55% |\n",
"| Epoch: 02 | Train Loss: 0.541 | Train Acc: 73.29% |\n",
"| Epoch: 03 | Train Loss: 0.499 | Train Acc: 76.19% |\n",
"| Epoch: 04 | Train Loss: 0.470 | Train Acc: 77.93% |\n",
"| Epoch: 05 | Train Loss: 0.447 | Train Acc: 79.41% |\n",
"| Epoch: 06 | Train Loss: 0.428 | Train Acc: 80.52% |\n",
"| Epoch: 07 | Train Loss: 0.411 | Train Acc: 81.66% |\n",
"| Epoch: 08 | Train Loss: 0.394 | Train Acc: 82.52% |\n",
"| Epoch: 09 | Train Loss: 0.377 | Train Acc: 83.41% |\n",
"| Epoch: 10 | Train Loss: 0.363 | Train Acc: 84.44% |\n"
]
}
],
"source": [
"num_epochs = 10\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": [
"### Testing the model"
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Test Loss: 0.493 | Test Acc: 77.05%\n"
]
}
],
"source": [
"epoch_loss = 0\n",
"epoch_acc = 0\n",
"\n",
"model.eval()\n",
"\n",
"with torch.no_grad():\n",
"\n",
" for batch in test_iterator:\n",
"\n",
" predictions = model(batch.SentimentText).squeeze(1)\n",
"\n",
" loss = criterion(predictions, batch.Sentiment)\n",
"\n",
" rounded_preds = torch.round(torch.sigmoid(predictions))\n",
" correct = (rounded_preds == batch.Sentiment).float() \n",
" \n",
" acc = correct.sum()/len(correct)\n",
"\n",
" epoch_loss += loss.item()\n",
" epoch_acc += acc.item()\n",
"\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": "markdown",
"metadata": {},
"source": [
"#### User Input\n",
"We can now use our model to predict the sentiment of any sentence we give it.As it has been trained on tweets, the sentences provided should in a positive or a negative context.\n",
"\n",
"We are expecting tweets with a negative sentiment to return a value close to 1 and positive tweets to return a value close to 0\n"
]
},
{
"cell_type": "code",
"execution_count": 123,
"metadata": {},
"outputs": [],
"source": [
"sentence = 'I hate that show' \n",
"\n",
"#Run again for \"That movie was really nice\"\n",
"#Run again for \"I hate that show but recently it has been quite good\"\n",
"#Run again for \"That movie was decent but kind of fizzled out towards the end\""
]
},
{
"cell_type": "code",
"execution_count": 124,
"metadata": {},
"outputs": [],
"source": [
"tokenized = [tok.text for tok in nlp.tokenizer(sentence)]"
]
},
{
"cell_type": "code",
"execution_count": 125,
"metadata": {},
"outputs": [],
"source": [
"indexed = [TEXT.vocab.stoi[t] for t in tokenized]"
]
},
{
"cell_type": "code",
"execution_count": 126,
"metadata": {},
"outputs": [],
"source": [
"tensor = torch.LongTensor(indexed)"
]
},
{
"cell_type": "code",
"execution_count": 127,
"metadata": {},
"outputs": [],
"source": [
"tensor = tensor.unsqueeze(1)"
]
},
{
"cell_type": "code",
"execution_count": 128,
"metadata": {},
"outputs": [],
"source": [
"prediction = torch.sigmoid(model(tensor))"
]
},
{
"cell_type": "code",
"execution_count": 129,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.8913049101829529"
]
},
"execution_count": 129,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"prediction.item()"
]
},
{
"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
}