{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement already satisfied: spacy in /anaconda3/lib/python3.6/site-packages (2.1.4)\n", "Requirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /anaconda3/lib/python3.6/site-packages (from spacy) (1.0.2)\n", "Requirement already satisfied: blis<0.3.0,>=0.2.2 in /anaconda3/lib/python3.6/site-packages (from spacy) (0.2.4)\n", "Requirement already satisfied: thinc<7.1.0,>=7.0.2 in /anaconda3/lib/python3.6/site-packages (from spacy) (7.0.4)\n", "Requirement already satisfied: cymem<2.1.0,>=2.0.2 in /anaconda3/lib/python3.6/site-packages (from spacy) (2.0.2)\n", "Requirement already satisfied: srsly<1.1.0,>=0.0.5 in /anaconda3/lib/python3.6/site-packages (from spacy) (0.0.7)\n", "Requirement already satisfied: requests<3.0.0,>=2.13.0 in /anaconda3/lib/python3.6/site-packages (from spacy) (2.18.4)\n", "Requirement already satisfied: jsonschema<3.1.0,>=2.6.0 in /anaconda3/lib/python3.6/site-packages (from spacy) (2.6.0)\n", "Requirement already satisfied: plac<1.0.0,>=0.9.6 in /anaconda3/lib/python3.6/site-packages (from spacy) (0.9.6)\n", "Requirement already satisfied: numpy>=1.15.0 in /anaconda3/lib/python3.6/site-packages (from spacy) (1.16.4)\n", "Requirement already satisfied: preshed<2.1.0,>=2.0.1 in /anaconda3/lib/python3.6/site-packages (from spacy) (2.0.1)\n", "Requirement already satisfied: wasabi<1.1.0,>=0.2.0 in /anaconda3/lib/python3.6/site-packages (from spacy) (0.2.2)\n", "Requirement already satisfied: tqdm<5.0.0,>=4.10.0 in /anaconda3/lib/python3.6/site-packages (from thinc<7.1.0,>=7.0.2->spacy) (4.32.2)\n", "Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /anaconda3/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (3.0.4)\n", "Requirement already satisfied: idna<2.7,>=2.5 in /anaconda3/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (2.6)\n", "Requirement already satisfied: urllib3<1.23,>=1.21.1 in /anaconda3/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (1.22)\n", "Requirement already satisfied: certifi>=2017.4.17 in /anaconda3/lib/python3.6/site-packages (from requests<3.0.0,>=2.13.0->spacy) (2018.4.16)\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 spacy" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement already satisfied: en_core_web_sm==2.1.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.1.0/en_core_web_sm-2.1.0.tar.gz#egg=en_core_web_sm==2.1.0 in /anaconda3/lib/python3.6/site-packages (2.1.0)\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", "\u001b[38;5;2m✔ Download and installation successful\u001b[0m\n", "You can now load the model via spacy.load('en_core_web_sm')\n", "\u001b[38;5;2m✔ Linking successful\u001b[0m\n", "/anaconda3/lib/python3.6/site-packages/en_core_web_sm -->\n", "/anaconda3/lib/python3.6/site-packages/spacy/data/en\n", "You can now load the model via spacy.load('en')\n" ] } ], "source": [ "!python -m spacy download en" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'2.1.4'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import spacy \n", "\n", "spacy.__version__" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torchtext\n", "from torchtext import datasets\n", "\n", "import re\n", "import pandas as pd\n", "import seaborn as sns\n", "from matplotlib import pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Twitter Sentiment Analysis Dataset\n", "Source: http://thinknook.com/twitter-sentiment-analysis-training-corpus-dataset-2012-09-22/" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
ItemIDSentimentSentimentSourceSentimentText
01negSentiment140is so sad for my APL frie...
12negSentiment140I missed the New Moon trail...
23posSentiment140omg its already 7:30 :O
34negSentiment140.. Omgaga. Im sooo im gunna CRy. I've been at...
45negSentiment140i think mi bf is cheating on me!!! ...
\n", "
" ], "text/plain": [ " ItemID Sentiment SentimentSource \\\n", "0 1 neg Sentiment140 \n", "1 2 neg Sentiment140 \n", "2 3 pos Sentiment140 \n", "3 4 neg Sentiment140 \n", "4 5 neg Sentiment140 \n", "\n", " SentimentText \n", "0 is so sad for my APL frie... \n", "1 I missed the New Moon trail... \n", "2 omg its already 7:30 :O \n", "3 .. Omgaga. Im sooo im gunna CRy. I've been at... \n", "4 i think mi bf is cheating on me!!! ... " ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweets = pd.read_csv('datasets/tweets/tweets.csv', error_bad_lines = False)\n", "\n", "tweets = tweets.head(50000)\n", "tweets.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The dataframe consists of 4 columns and we want to use only ‘Sentiment’ and ‘SentimentText’." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
SentimentSentimentText
0negis so sad for my APL frie...
1negI missed the New Moon trail...
2posomg its already 7:30 :O
3neg.. Omgaga. Im sooo im gunna CRy. I've been at...
4negi think mi bf is cheating on me!!! ...
\n", "
" ], "text/plain": [ " Sentiment SentimentText\n", "0 neg is so sad for my APL frie...\n", "1 neg I missed the New Moon trail...\n", "2 pos omg its already 7:30 :O\n", "3 neg .. Omgaga. Im sooo im gunna CRy. I've been at...\n", "4 neg i think mi bf is cheating on me!!! ..." ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweets = tweets.drop(columns = ['ItemID', 'SentimentSource'], axis = 1)\n", "\n", "tweets.head()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(50000, 2)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweets.shape" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array(['neg', 'pos'], dtype=object)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweets['Sentiment'].unique()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "pos 26921\n", "neg 23079\n", "Name: Sentiment, dtype: int64" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweets.Sentiment.value_counts()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Text(0.5, 0, 'Labels')]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAuAAAAHgCAYAAADkNtiUAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjAsIGh0dHA6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AAAwlwgH1AVX1nN/Z9TVX97rzOD7CvE+AAADCQAAfYR1XVv6mqT1TVtVX1v6vqkJnNj6mqj1fVzVX1gpljXlFVV1fV9VX13xY556FV9dGquq6qPlNV/3LImwHYiwhwgH3Xx5Ic392PTXJhkt+b2fboJE9N8oQkf1BVv1RVJyRZl+S4JMckObaqnrzdOZ+b5LLuPiYLXwN+3ZzfA8BexxfxAOy7Dk/ynqo6NMkBSb44s+3i7v5eku9V1ZVZiO5fTXJCkmunfR6QhSD/6MxxVyfZWFX3SfK/uluAA2zHFXCAfddbk/x5dz8qyQuT/PzMtu2/pa2TVJL/3t3HTI+Hd/e5P7FT90eTPDnJrUnOq6rT5jd9gL2TAAfYd/1CFkI5STZst+3kqvr5qjooyVOycGX7siS/VVUPSJKqOqyqfnH2oKp6WJKvdfc7kvxVksfNcf4AeyVLUAD2Dfevqi0zv78pyWuSvLeq7kzyd0mOnNl+fZIrkxyc5HXd/ZUkX6mqX0ny8apKku8k+Q9Jbp857ilJXlFVP5y2uwIOsJ3q3v6/jAAAwLxYggIAAAMJcAAAGEiAAwDAQAIcAAAGEuAAADCQAAcAgIEEOAAADCTAAQBgoP8Pt1ZeZR5Kh4UAAAAASUVORK5CYII=\n", "text/plain": [ "
" ] }, "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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
SentimentSentimentText
39087pos@amyrenea omg so am I lol I fell asleep when i...
30893neg@Adrienne_Bailon I want a shout out
45278neg@Anonymousboy03 Plans for school stuff &amp; a...
16398neg... has hit a writer's block .. am loosing my ...
13653neg... trying to find people I know! I`m bored, i...
\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 }