{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "***\n", "***\n", "# 基于机器学习的情感分析\n", "***\n", "***\n", "\n", "王成军\n", "\n", "wangchengjun@nju.edu.cn\n", "\n", "计算传播网 http://computational-communication.com" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "情感分析(sentiment analysis)和意见挖掘(opinion mining)虽然相关,但是从社会科学的角度而言,二者截然不同。这里主要是讲情感分析(sentiment or emotion),而非意见挖掘(opinion, 后者通过机器学习效果更可信)。\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "![](./img/emotion.jpg)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# classify emotion\n", "Different types of emotion: anger, disgust, fear, joy, sadness, and surprise. The classification can be performed using different algorithms: e.g., naive Bayes classifier trained on Carlo Strapparava and Alessandro Valitutti’s emotions lexicon.\n", "\n", "# classify polarity\n", "\n", "To classify some text as positive or negative. In this case, the classification can be done by using a naive Bayes algorithm trained on Janyce Wiebe’s subjectivity lexicon." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "![](./img/sentiment.png)\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "# LIWC & TextMind \n", "\n", "http://ccpl.psych.ac.cn/textmind/\n", "\n", "“文心(TextMind)”中文心理分析系统是由中科院心理所计算网络心理实验室研发的,针对中文文本进行语言分析的软件系统,通过“文心”,您可以便捷地分析文本中使用的不同类别语言的程度、偏好等特点。针对中国大陆地区简体环境下的语言特点,参照LIWC2007和正體中文C-LIWC词库,我们开发了“文心(TextMind)”中文心理分析系统。“文心”为用户提供从简体中文自动分词,到语言心理分析的一揽子分析解决方案,其词库、文字和符号等处理方法专门针对简体中文语境,词库分类体系也与LIWC兼容一致。" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Preparing the data" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# NLTK\n", "Anaconda自带的(默认安装的)第三方包。http://www.nltk.org/\n", "\n", "> NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries, and an active discussion forum." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T03:53:54.104554Z", "start_time": "2019-06-14T03:53:53.406875Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "import nltk\n", "\n", "pos_tweets = [('I love this car', 'positive'),\n", " ('This view is amazing', 'positive'),\n", " ('I feel great this morning', 'positive'),\n", " ('I am so excited about the concert', 'positive'),\n", " ('He is my best friend', 'positive')]\n", "\n", "neg_tweets = [('I do not like this car', 'negative'),\n", " ('This view is horrible', 'negative'),\n", " ('I feel tired this morning', 'negative'),\n", " ('I am not looking forward to the concert', 'negative'),\n", " ('He is my enemy', 'negative')]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:29:47.153293Z", "start_time": "2018-06-12T06:29:47.138402Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "[(['love', 'this', 'car'], 'positive'),\n", " (['this', 'view', 'amazing'], 'positive')]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweets = []\n", "for (words, sentiment) in pos_tweets + neg_tweets:\n", " words_filtered = [e.lower() for e in words.split() if len(e) >= 3]\n", " tweets.append((words_filtered, sentiment))\n", "tweets[:2]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:30:39.237513Z", "start_time": "2018-06-12T06:30:39.232883Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "test_tweets = [\n", " (['feel', 'happy', 'this', 'morning'], 'positive'),\n", " (['larry', 'friend'], 'positive'),\n", " (['not', 'like', 'that', 'man'], 'negative'),\n", " (['house', 'not', 'great'], 'negative'),\n", " (['your', 'song', 'annoying'], 'negative')]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Extracting Features\n", "Then we need to get the unique word list as the features for classification.\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:32:13.548332Z", "start_time": "2018-06-12T06:32:13.534455Z" }, "code_folding": [], "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "'friend tired great like amazing this looking horrible forward excited best not concert enemy love view feel the car morning about'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# get the word lists of tweets\n", "def get_words_in_tweets(tweets):\n", " all_words = []\n", " for (words, sentiment) in tweets:\n", " all_words.extend(words)\n", " return all_words\n", "\n", "# get the unique word from the word list\t\n", "def get_word_features(wordlist):\n", " wordlist = nltk.FreqDist(wordlist)\n", " word_features = wordlist.keys()\n", " return word_features\n", "\n", "word_features = get_word_features(get_words_in_tweets(tweets))\n", "' '.join(word_features)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "To create a classifier, we need to decide what features are relevant. To do that, we first need a feature extractor." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:33:32.306348Z", "start_time": "2018-06-12T06:33:32.301310Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "def extract_features(document):\n", " document_words = set(document)\n", " features = {}\n", " for word in word_features:\n", " features['contains(%s)' % word] = (word in document_words)\n", " return features" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "ExecuteTime": { "end_time": "2018-05-04T04:13:21.330901Z", "start_time": "2018-05-04T04:13:21.326403Z" }, "slideshow": { "slide_type": "skip" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function apply_features in module nltk.classify.util:\n", "\n", "apply_features(feature_func, toks, labeled=None)\n", " Use the ``LazyMap`` class to construct a lazy list-like\n", " object that is analogous to ``map(feature_func, toks)``. In\n", " particular, if ``labeled=False``, then the returned list-like\n", " object's values are equal to::\n", " \n", " [feature_func(tok) for tok in toks]\n", " \n", " If ``labeled=True``, then the returned list-like object's values\n", " are equal to::\n", " \n", " [(feature_func(tok), label) for (tok, label) in toks]\n", " \n", " The primary purpose of this function is to avoid the memory\n", " overhead involved in storing all the featuresets for every token\n", " in a corpus. Instead, these featuresets are constructed lazily,\n", " as-needed. The reduction in memory overhead can be especially\n", " significant when the underlying list of tokens is itself lazy (as\n", " is the case with many corpus readers).\n", " \n", " :param feature_func: The function that will be applied to each\n", " token. It should return a featureset -- i.e., a dict\n", " mapping feature names to feature values.\n", " :param toks: The list of tokens to which ``feature_func`` should be\n", " applied. If ``labeled=True``, then the list elements will be\n", " passed directly to ``feature_func()``. If ``labeled=False``,\n", " then the list elements should be tuples ``(tok,label)``, and\n", " ``tok`` will be passed to ``feature_func()``.\n", " :param labeled: If true, then ``toks`` contains labeled tokens --\n", " i.e., tuples of the form ``(tok, label)``. (Default:\n", " auto-detect based on types.)\n", "\n" ] } ], "source": [ "help(nltk.classify.util.apply_features)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "ExecuteTime": { "end_time": "2018-05-04T04:16:47.732010Z", "start_time": "2018-05-04T04:16:47.727431Z" }, "slideshow": { "slide_type": "skip" } }, "outputs": [ { "data": { "text/plain": [ "({'contains(about)': False,\n", " 'contains(amazing)': False,\n", " 'contains(best)': False,\n", " 'contains(car)': True,\n", " 'contains(concert)': False,\n", " 'contains(enemy)': False,\n", " 'contains(excited)': False,\n", " 'contains(feel)': False,\n", " 'contains(forward)': False,\n", " 'contains(friend)': False,\n", " 'contains(great)': False,\n", " 'contains(horrible)': False,\n", " 'contains(like)': False,\n", " 'contains(looking)': False,\n", " 'contains(love)': True,\n", " 'contains(morning)': False,\n", " 'contains(not)': False,\n", " 'contains(the)': False,\n", " 'contains(this)': True,\n", " 'contains(tired)': False,\n", " 'contains(view)': False},\n", " 'positive')" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "training_set[0]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:35:10.046495Z", "start_time": "2018-06-12T06:35:10.041684Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "training_set = nltk.classify.util.apply_features(extract_features,\\\n", " tweets)\n", "classifier = nltk.NaiveBayesClassifier.train(training_set)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "ExecuteTime": { "end_time": "2018-05-04T03:44:50.250229Z", "start_time": "2018-05-04T03:44:50.244533Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# You may want to know how to define the ‘train’ method in NLTK here:\n", "def train(labeled_featuresets, estimator=nltk.probability.ELEProbDist):\n", " # Create the P(label) distribution\n", " label_probdist = estimator(label_freqdist)\n", " # Create the P(fval|label, fname) distribution\n", " feature_probdist = {}\n", " model = NaiveBayesClassifier(label_probdist, feature_probdist)\n", " return model" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:38:45.049773Z", "start_time": "2018-06-12T06:38:45.044493Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "'positive'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweet_positive = 'Harry is my friend'\n", "classifier.classify(extract_features(tweet_positive.split()))" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:39:40.695616Z", "start_time": "2018-06-12T06:39:40.690917Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'negative'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tweet_negative = 'Larry is not my friend'\n", "classifier.classify(extract_features(tweet_negative.split()))" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:41:03.028951Z", "start_time": "2018-06-12T06:41:03.024148Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "'positive'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Don’t be too positive, let’s try another example:\n", "tweet_negative2 = 'Your song is annoying'\n", "classifier.classify(extract_features(tweet_negative2.split()))" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:42:24.246004Z", "start_time": "2018-06-12T06:42:24.236263Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total accuracy: 80.000000% (4/20).\n" ] } ], "source": [ "def classify_tweet(tweet):\n", " return classifier.classify(extract_features(tweet)) \n", " # nltk.word_tokenize(tweet)\n", "\n", "total = accuracy = float(len(test_tweets))\n", "\n", "for tweet in test_tweets:\n", " if classify_tweet(tweet[0]) != tweet[1]:\n", " accuracy -= 1\n", "\n", "print('Total accuracy: %f%% (%d/20).' % (accuracy / total * 100, accuracy))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 使用sklearn的分类器" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "ExecuteTime": { "end_time": "2018-05-04T00:43:19.448307Z", "start_time": "2018-05-04T00:43:19.442616Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ClassifierBasedPOSTagger\n", "ClassifierBasedTagger\n", "ClassifierI\n", "ConditionalExponentialClassifier\n", "DecisionTreeClassifier\n", "MaxentClassifier\n", "MultiClassifierI\n", "NaiveBayesClassifier\n", "PositiveNaiveBayesClassifier\n", "SklearnClassifier\n", "WekaClassifier\n" ] } ], "source": [ "# nltk有哪些分类器呢?\n", "nltk_classifiers = dir(nltk)\n", "for i in nltk_classifiers:\n", " if 'Classifier' in i:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:46:00.563674Z", "start_time": "2018-06-12T06:46:00.551963Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "from sklearn.svm import LinearSVC\n", "from nltk.classify.scikitlearn import SklearnClassifier\n", "classif = SklearnClassifier(LinearSVC())\n", "svm_classifier = classif.train(training_set)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "ExecuteTime": { "end_time": "2018-06-12T06:46:08.293219Z", "start_time": "2018-06-12T06:46:08.287930Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "'negative'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Don’t be too positive, let’s try another example:\n", "tweet_negative2 = 'Your song is annoying'\n", "svm_classifier.classify(extract_features(tweet_negative2.split()))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 作业1:\n", "\n", "使用另外一种sklearn的分类器来对tweet_negative2进行情感分析\n", "\n", "# 作业2:\n", "\n", "使用https://github.com/victorneo/Twitter-Sentimental-Analysis 所提供的推特数据进行情感分析,可以使用其代码 https://github.com/victorneo/Twitter-Sentimental-Analysis/blob/master/classification.py\n", "\n", "![](./img/homework.jpg)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# 推荐阅读:\n", "\n", "movies reviews情感分析 http://nbviewer.jupyter.org/github/rasbt/python-machine-learning-book/blob/master/code/ch08/ch08.ipynb\n", "\n", "Sentiment analysis with machine learning in R http://chengjun.github.io/en/2014/04/sentiment-analysis-with-machine-learning-in-R/\n", "\n", "使用R包sentiment进行情感分析 https://site.douban.com/146782/widget/notes/15462869/note/344846192/\n", "\n", "中文的手机评论的情感分析 https://github.com/computational-class/Review-Helpfulness-Prediction\n", "\n", "基于词典的中文情感倾向分析 https://site.douban.com/146782/widget/notes/15462869/note/355625387/" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Sentiment Analysis using TextBlob" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 安装textblob\n", "https://github.com/sloria/TextBlob\n", " \n", "> pip install -U textblob\n", "\n", "> python -m textblob.download_corpora" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "ExecuteTime": { "end_time": "2018-05-04T00:52:58.216921Z", "start_time": "2018-05-04T00:45:15.483851Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.06000000000000001\n", "-0.34166666666666673\n" ] }, { "data": { "text/plain": [ "TextBlob(\"La amenaza principal de The Blob siempre me ha parecido la mejor película\n", "monstruo: una masa insaciablemente hambrienta, similar a una ameba capaz de penetrar\n", "prácticamente cualquier salvaguardia, capaz de - como un doctor condenado escalofriante\n", "lo describe - \"asimilando carne en contacto.\n", "Las malditas comparaciones con la gelatina pueden ser condenadas, es un concepto con la mayor cantidad de\n", "devastador de posibles consecuencias, a diferencia del escenario gris goo\n", "propuesto por teóricos tecnológicos temerosos de\n", "la inteligencia artificial corre desenfrenada.\")" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from textblob import TextBlob\n", "\n", "text = '''\n", "The titular threat of The Blob has always struck me as the ultimate movie\n", "monster: an insatiably hungry, amoeba-like mass able to penetrate\n", "virtually any safeguard, capable of--as a doomed doctor chillingly\n", "describes it--\"assimilating flesh on contact.\n", "Snide comparisons to gelatin be damned, it's a concept with the most\n", "devastating of potential consequences, not unlike the grey goo scenario\n", "proposed by technological theorists fearful of\n", "artificial intelligence run rampant.\n", "'''\n", "\n", "blob = TextBlob(text)\n", "blob.tags # [('The', 'DT'), ('titular', 'JJ'),\n", " # ('threat', 'NN'), ('of', 'IN'), ...]\n", "\n", "blob.noun_phrases # WordList(['titular threat', 'blob',\n", " # 'ultimate movie monster',\n", " # 'amoeba-like mass', ...])\n", "\n", "for sentence in blob.sentences:\n", " print(sentence.sentiment.polarity)\n", "# 0.060\n", "# -0.341\n", "\n", "blob.translate(to=\"es\") # 'La amenaza titular de The Blob...'" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Sentiment Analysis Using Turicreate" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "In this notebook, I will explain how to develop sentiment analysis classifiers that are based on a bag-of-words model. \n", "Then, I will demonstrate how these classifiers can be utilized to solve Kaggle's \"When Bag of Words Meets Bags of Popcorn\" challenge." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Code Recipe: Creating Sentiment Classifier " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Using GraphLab Turicreate it is very easy and straight foward to create a sentiment classifier based on bag-of-words model. Given a dataset stored as a CSV file, you can construct your sentiment classifier using the following code: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "import turicreate as tc\n", "train_data = tc.SFrame.read_csv(traindata_path,header=True, \n", " delimiter='\\t',quote_char='\"', \n", " column_type_hints = {'id':str, \n", " 'sentiment' : int, \n", " 'review':str } )\n", "train_data['1grams features'] = tc.text_analytics.count_ngrams(\n", " train_data['review'],1)\n", "train_data['2grams features'] = tc.text_analytics.count_ngrams(\n", " train_data['review'],2)\n", "cls = tc.classifier.create(train_data, target='sentiment', \n", " features=['1grams features',\n", " '2grams features'])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "In the rest of this notebook, we will explain this code recipe in details, by demonstrating how this recipe can used to create IMDB movie reviews sentiment classifier." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Set up" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Before we begin constructing the classifiers, we need to import some Python libraries: turicreate (tc), and IPython display utilities." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:50:16.291727Z", "start_time": "2019-06-14T16:50:15.367322Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "import turicreate as tc\n", "from IPython.display import display\n", "from IPython.display import Image\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## IMDB movies reviews Dataset \n", "\n", "> # Bag of Words Meets Bags of Popcorn\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Throughout this notebook, I will use Kaggle's IMDB movies reviews datasets that is available to download from the following link: https://www.kaggle.com/c/word2vec-nlp-tutorial/data. I downloaded labeledTrainData.tsv and testData.tsv files, and unzipped them to the following local files.\n", "\n", "### DeepLearningMovies\n", "\n", "Kaggle's competition for using Google's word2vec package for sentiment analysis\n", "\n", "https://github.com/wendykan/DeepLearningMovies" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:50:47.697332Z", "start_time": "2019-06-14T16:50:47.694256Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "traindata_path = \"/Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv\"\n", "testdata_path = \"/Users/datalab/bigdata/cjc/kaggle_popcorn_data/testData.tsv\"" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "## Loading Data" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We will load the data with IMDB movie reviews to an SFrame using SFrame.read_csv function." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:50:50.443338Z", "start_time": "2019-06-14T16:50:49.571767Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/html": [ "
Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv
" ], "text/plain": [ "Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Parsing completed. Parsed 100 lines in 0.318532 secs.
" ], "text/plain": [ "Parsing completed. Parsed 100 lines in 0.318532 secs." ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv
" ], "text/plain": [ "Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Parsing completed. Parsed 25000 lines in 0.499892 secs.
" ], "text/plain": [ "Parsing completed. Parsed 25000 lines in 0.499892 secs." ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "movies_reviews_data = tc.SFrame.read_csv(traindata_path,header=True, \n", " delimiter='\\t',quote_char='\"', \n", " column_type_hints = {'id':str, \n", " 'sentiment' : str, \n", " 'review':str } )" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "By using the SFrame show function, we can visualize the data and notice that the train dataset consists of 12,500 positive and 12,500 negative, and overall 24,932 unique reviews." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:50:55.267343Z", "start_time": "2019-06-14T16:50:55.212701Z" }, "slideshow": { "slide_type": "slide" } }, "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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idsentimentreview
5814_81With all this stuff going
down at the moment with ...
2381_91"The Classic War of the
Worlds" by Timothy Hines ...
7759_30The film starts with a
manager (Nicholas Bell) ...
3630_40It must be assumed that
those who praised this ...
9495_81Superbly trashy and
wondrously unpretentious ...
8196_81I dont know why people
think this is such a bad ...
7166_20This movie could have
been very good, but c ...
10633_10I watched this video at a
friend's house. I'm glad ...
319_10A friend of mine bought
this film for £1, and ...
8713_101<br /><br />This movie is
full of references. Like ...
\n", "[25000 rows x 3 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.\n", "
" ], "text/plain": [ "Columns:\n", "\tid\tstr\n", "\tsentiment\tstr\n", "\treview\tstr\n", "\n", "Rows: 25000\n", "\n", "Data:\n", "+---------+-----------+-------------------------------+\n", "| id | sentiment | review |\n", "+---------+-----------+-------------------------------+\n", "| 5814_8 | 1 | With all this stuff going ... |\n", "| 2381_9 | 1 | \"The Classic War of the Wo... |\n", "| 7759_3 | 0 | The film starts with a man... |\n", "| 3630_4 | 0 | It must be assumed that th... |\n", "| 9495_8 | 1 | Superbly trashy and wondro... |\n", "| 8196_8 | 1 | I dont know why people thi... |\n", "| 7166_2 | 0 | This movie could have been... |\n", "| 10633_1 | 0 | I watched this video at a ... |\n", "| 319_1 | 0 | A friend of mine bought th... |\n", "| 8713_10 | 1 |

This movie is ... |\n", "+---------+-----------+-------------------------------+\n", "[25000 rows x 3 columns]\n", "Note: Only the head of the SFrame is printed.\n", "You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns." ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "movies_reviews_data" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Constructing Bag-of-Words Classifier " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "One of the common techniques to perform document classification (and reviews classification) is using Bag-of-Words model, in which the frequency of each word in the document is used as a feature for training a classifier. GraphLab's text analytics toolkit makes it easy to calculate the frequency of each word in each review. Namely, by using the count_ngrams function with n=1, we can calculate the frequency of each word in each review. By running the following command:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:51:02.529329Z", "start_time": "2019-06-14T16:51:02.517257Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "movies_reviews_data['1grams features'] = tc.text_analytics.count_ngrams(movies_reviews_data ['review'],1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "By running the last command, we created a new column in movies_reviews_data SFrame object. In this column each value is a dictionary object, where each dictionary's keys are the different words which appear in the corresponding review, and the dictionary's values are the frequency of each word.\n", "We can view the values of this new column using the following command." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:51:05.248555Z", "start_time": "2019-06-14T16:51:05.116080Z" }, "slideshow": { "slide_type": "slide" } }, "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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idsentimentreview1grams features
5814_81With all this stuff going
down at the moment with ...
{'just': 3, 'sickest': 1,
'smooth': 1, 'this': 11, ...
2381_91"The Classic War of the
Worlds" by Timothy Hines ...
{'year': 1, 'others': 1,
'those': 2, 'this': 1, ...
7759_30The film starts with a
manager (Nicholas Bell) ...
{'hair': 1, 'bound': 1,
'this': 1, 'when': 2, ...
3630_40It must be assumed that
those who praised this ...
{'crocuses': 1, 'that':
7, 'batonzilla': 1, ...
9495_81Superbly trashy and
wondrously unpretentious ...
{'unshaven': 1, 'just':
1, 'in': 5, 'when': 2, ...
8196_81I dont know why people
think this is such a bad ...
{'harry': 3, 'this': 4,
'of': 2, 'hurt': 1, ' ...
7166_20This movie could have
been very good, but c ...
{'acting': 1,
'background': 1, 'just': ...
10633_10I watched this video at a
friend's house. I'm glad ...
{'photography': 1,
'others': 1, 'zapruder': ...
319_10A friend of mine bought
this film for £1, and ...
{'just': 1, 'this': 2,
'when': 1, 'as': 5, 's': ...
8713_101<br /><br />This movie is
full of references. Like ...
{'peter': 1, 'ii': 1,
'full': 1, 'others': 1, ...
\n", "[25000 rows x 4 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.\n", "
" ], "text/plain": [ "Columns:\n", "\tid\tstr\n", "\tsentiment\tstr\n", "\treview\tstr\n", "\t1grams features\tdict\n", "\n", "Rows: 25000\n", "\n", "Data:\n", "+---------+-----------+-------------------------------+\n", "| id | sentiment | review |\n", "+---------+-----------+-------------------------------+\n", "| 5814_8 | 1 | With all this stuff going ... |\n", "| 2381_9 | 1 | \"The Classic War of the Wo... |\n", "| 7759_3 | 0 | The film starts with a man... |\n", "| 3630_4 | 0 | It must be assumed that th... |\n", "| 9495_8 | 1 | Superbly trashy and wondro... |\n", "| 8196_8 | 1 | I dont know why people thi... |\n", "| 7166_2 | 0 | This movie could have been... |\n", "| 10633_1 | 0 | I watched this video at a ... |\n", "| 319_1 | 0 | A friend of mine bought th... |\n", "| 8713_10 | 1 |

This movie is ... |\n", "+---------+-----------+-------------------------------+\n", "+-------------------------------+\n", "| 1grams features |\n", "+-------------------------------+\n", "| {'just': 3, 'sickest': 1, ... |\n", "| {'year': 1, 'others': 1, '... |\n", "| {'hair': 1, 'bound': 1, 't... |\n", "| {'crocuses': 1, 'that': 7,... |\n", "| {'unshaven': 1, 'just': 1,... |\n", "| {'harry': 3, 'this': 4, 'o... |\n", "| {'acting': 1, 'background'... |\n", "| {'photography': 1, 'others... |\n", "| {'just': 1, 'this': 2, 'wh... |\n", "| {'peter': 1, 'ii': 1, 'ful... |\n", "+-------------------------------+\n", "[25000 rows x 4 columns]\n", "Note: Only the head of the SFrame is printed.\n", "You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns." ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "movies_reviews_data#[['review','1grams features']]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "We are now ready to construct and evaluate the movie reviews sentiment classifier using the calculated above features. But first, to be able to perform a quick evaluation of the constructed classifier, we need to create labeled train and test datasets. We will create train and test datasets by randomly splitting the train dataset into two parts. The first part will contain 80% of the labeled train dataset and will be used as the training dataset, while the second part will contain 20% of the labeled train dataset and will be used as the testing dataset. We will create these two dataset by using the following command: " ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:51:09.958230Z", "start_time": "2019-06-14T16:51:09.954844Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "train_set, test_set = movies_reviews_data.random_split(0.8, seed=5)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "We are now ready to create a classifier using the following command:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:51:30.848861Z", "start_time": "2019-06-14T16:51:16.305109Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "PROGRESS: Creating a validation set from 5 percent of training data. This may take a while.\n", " You can set ``validation_set=None`` to disable validation tracking.\n", "\n", "PROGRESS: The following methods are available for this type of problem.\n", "PROGRESS: LogisticClassifier, SVMClassifier\n", "PROGRESS: The returned model will be chosen according to validation accuracy.\n" ] }, { "data": { "text/html": [ "
Logistic regression:
" ], "text/plain": [ "Logistic regression:" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of examples          : 19077
" ], "text/plain": [ "Number of examples : 19077" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of classes           : 2
" ], "text/plain": [ "Number of classes : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of feature columns   : 1
" ], "text/plain": [ "Number of feature columns : 1" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of unpacked features : 68246
" ], "text/plain": [ "Number of unpacked features : 68246" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of coefficients      : 68247
" ], "text/plain": [ "Number of coefficients : 68247" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Starting L-BFGS
" ], "text/plain": [ "Starting L-BFGS" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| Iteration | Passes   | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |
" ], "text/plain": [ "| Iteration | Passes | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 0         | 2        | 1.000000  | 1.111660     | 0.942182          | 0.860697            |
" ], "text/plain": [ "| 0 | 2 | 1.000000 | 1.111660 | 0.942182 | 0.860697 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 1         | 4        | 1.000000  | 1.253890     | 0.968444          | 0.865672            |
" ], "text/plain": [ "| 1 | 4 | 1.000000 | 1.253890 | 0.968444 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 2         | 6        | 1.000000  | 1.390344     | 0.990040          | 0.897512            |
" ], "text/plain": [ "| 2 | 6 | 1.000000 | 1.390344 | 0.990040 | 0.897512 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 3         | 7        | 1.000000  | 1.474481     | 0.992923          | 0.899502            |
" ], "text/plain": [ "| 3 | 7 | 1.000000 | 1.474481 | 0.992923 | 0.899502 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 4         | 8        | 1.000000  | 1.563669     | 0.997379          | 0.891542            |
" ], "text/plain": [ "| 4 | 8 | 1.000000 | 1.563669 | 0.997379 | 0.891542 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 9         | 13       | 1.000000  | 2.052863     | 1.000000          | 0.867662            |
" ], "text/plain": [ "| 9 | 13 | 1.000000 | 2.052863 | 1.000000 | 0.867662 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
SVM:
" ], "text/plain": [ "SVM:" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of examples          : 19077
" ], "text/plain": [ "Number of examples : 19077" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of classes           : 2
" ], "text/plain": [ "Number of classes : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of feature columns   : 1
" ], "text/plain": [ "Number of feature columns : 1" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of unpacked features : 68246
" ], "text/plain": [ "Number of unpacked features : 68246" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of coefficients    : 68247
" ], "text/plain": [ "Number of coefficients : 68247" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Starting L-BFGS
" ], "text/plain": [ "Starting L-BFGS" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| Iteration | Passes   | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |
" ], "text/plain": [ "| Iteration | Passes | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 0         | 2        | 1.000000  | 0.125585     | 0.942182          | 0.860697            |
" ], "text/plain": [ "| 0 | 2 | 1.000000 | 0.125585 | 0.942182 | 0.860697 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 1         | 4        | 1.000000  | 0.268260     | 0.973738          | 0.875622            |
" ], "text/plain": [ "| 1 | 4 | 1.000000 | 0.268260 | 0.973738 | 0.875622 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 2         | 5        | 1.000000  | 0.348993     | 0.989411          | 0.881592            |
" ], "text/plain": [ "| 2 | 5 | 1.000000 | 0.348993 | 0.989411 | 0.881592 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 3         | 6        | 1.000000  | 0.433099     | 0.992976          | 0.884577            |
" ], "text/plain": [ "| 3 | 6 | 1.000000 | 0.433099 | 0.992976 | 0.884577 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 4         | 7        | 1.000000  | 0.519594     | 0.996016          | 0.881592            |
" ], "text/plain": [ "| 4 | 7 | 1.000000 | 0.519594 | 0.996016 | 0.881592 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 9         | 12       | 1.000000  | 0.923521     | 0.999685          | 0.886567            |
" ], "text/plain": [ "| 9 | 12 | 1.000000 | 0.923521 | 0.999685 | 0.886567 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "PROGRESS: Model selection based on validation accuracy:\n", "PROGRESS: ---------------------------------------------\n", "PROGRESS: LogisticClassifier : 0.8676616915422886\n", "PROGRESS: SVMClassifier : 0.8865671641791045\n", "PROGRESS: ---------------------------------------------\n", "PROGRESS: Selecting SVMClassifier based on validation set performance.\n" ] } ], "source": [ "model_1 = tc.classifier.create(train_set, target='sentiment', \\\n", " features=['1grams features'])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "We can evaluate the performence of the classifier by evaluating it on the test dataset" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:51:55.289534Z", "start_time": "2019-06-14T16:51:54.504129Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "result1 = model_1.evaluate(test_set)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "In order to get an easy view of the classifier's prediction result, we define and use the following function" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:51:56.666544Z", "start_time": "2019-06-14T16:51:56.656636Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "******************************\n", "Accuracy : 0.8710858072387149\n", "Confusion Matrix: \n", " +--------------+-----------------+-------+\n", "| target_label | predicted_label | count |\n", "+--------------+-----------------+-------+\n", "| 0 | 1 | 374 |\n", "| 1 | 0 | 260 |\n", "| 1 | 1 | 2133 |\n", "| 0 | 0 | 2151 |\n", "+--------------+-----------------+-------+\n", "[4 rows x 3 columns]\n", "\n" ] } ], "source": [ "def print_statistics(result):\n", " print( \"*\" * 30)\n", " print( \"Accuracy : \", result[\"accuracy\"])\n", " print( \"Confusion Matrix: \\n\", result[\"confusion_matrix\"])\n", "print_statistics(result1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "As can be seen in the results above, in just a few relatively straight foward lines of code, we have developed a sentiment classifier that has accuracy of about ~0.88. Next, we demonstrate how we can improve the classifier accuracy even more." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Improving The Classifier" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "One way to improve the movie reviews sentiment classifier is to extract more meaningful features from the reviews. One method to add additional features, which might be meaningful, is to calculate the frequency of every two consecutive words in each review. To calculate the frequency of each two consecutive words in each review, as before, we will use turicreate's count_ngrams function only this time we will set n to be equal 2 (n=2) to create new column named '2grams features'. " ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:52:19.472533Z", "start_time": "2019-06-14T16:52:19.463443Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "movies_reviews_data['2grams features'] = tc.text_analytics.count_ngrams(movies_reviews_data['review'],2)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:52:20.971123Z", "start_time": "2019-06-14T16:52:20.734798Z" } }, "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", " \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", "
idsentimentreview1grams features2grams features
5814_81With all this stuff going
down at the moment with ...
{'just': 3, 'sickest': 1,
'smooth': 1, 'this': 11, ...
{'alone a': 1, 'most
people': 1, 'hope he' ...
2381_91"The Classic War of the
Worlds" by Timothy Hines ...
{'year': 1, 'others': 1,
'those': 2, 'this': 1, ...
{'slightest resemblance':
1, 'which is': 1, 'very ...
7759_30The film starts with a
manager (Nicholas Bell) ...
{'hair': 1, 'bound': 1,
'this': 1, 'when': 2, ...
{'quite boring': 1,
'packs a': 1, 'small ...
3630_40It must be assumed that
those who praised this ...
{'crocuses': 1, 'that':
7, 'batonzilla': 1, ...
{'but i': 1, 'is
represented': 1, 'opera ...
9495_81Superbly trashy and
wondrously unpretentious ...
{'unshaven': 1, 'just':
1, 'in': 5, 'when': 2, ...
{'unpretentious 80': 1,
'sleazy black': 1, 'd ...
8196_81I dont know why people
think this is such a bad ...
{'harry': 3, 'this': 4,
'of': 2, 'hurt': 1, ' ...
{'like that': 1, 'see
this': 1, 'is such': 1, ...
7166_20This movie could have
been very good, but c ...
{'acting': 1,
'background': 1, 'just': ...
{'linked to': 1, 'way
short': 1, 'good but' ...
10633_10I watched this video at a
friend's house. I'm glad ...
{'photography': 1,
'others': 1, 'zapruder': ...
{'curiously ends': 1,
'several clips': 1, ...
319_10A friend of mine bought
this film for £1, and ...
{'just': 1, 'this': 2,
'when': 1, 'as': 5, 's': ...
{'bob thornton': 1, 'in
the': 1, 'taking a': 1, ...
8713_101<br /><br />This movie is
full of references. Like ...
{'peter': 1, 'ii': 1,
'full': 1, 'others': 1, ...
{'in the': 1, 'is a': 1,
'lorre this': 1, 'much ...
\n", "[25000 rows x 5 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.\n", "
" ], "text/plain": [ "Columns:\n", "\tid\tstr\n", "\tsentiment\tstr\n", "\treview\tstr\n", "\t1grams features\tdict\n", "\t2grams features\tdict\n", "\n", "Rows: 25000\n", "\n", "Data:\n", "+---------+-----------+-------------------------------+\n", "| id | sentiment | review |\n", "+---------+-----------+-------------------------------+\n", "| 5814_8 | 1 | With all this stuff going ... |\n", "| 2381_9 | 1 | \"The Classic War of the Wo... |\n", "| 7759_3 | 0 | The film starts with a man... |\n", "| 3630_4 | 0 | It must be assumed that th... |\n", "| 9495_8 | 1 | Superbly trashy and wondro... |\n", "| 8196_8 | 1 | I dont know why people thi... |\n", "| 7166_2 | 0 | This movie could have been... |\n", "| 10633_1 | 0 | I watched this video at a ... |\n", "| 319_1 | 0 | A friend of mine bought th... |\n", "| 8713_10 | 1 |

This movie is ... |\n", "+---------+-----------+-------------------------------+\n", "+-------------------------------+-------------------------------+\n", "| 1grams features | 2grams features |\n", "+-------------------------------+-------------------------------+\n", "| {'just': 3, 'sickest': 1, ... | {'alone a': 1, 'most peopl... |\n", "| {'year': 1, 'others': 1, '... | {'slightest resemblance': ... |\n", "| {'hair': 1, 'bound': 1, 't... | {'quite boring': 1, 'packs... |\n", "| {'crocuses': 1, 'that': 7,... | {'but i': 1, 'is represent... |\n", "| {'unshaven': 1, 'just': 1,... | {'unpretentious 80': 1, 's... |\n", "| {'harry': 3, 'this': 4, 'o... | {'like that': 1, 'see this... |\n", "| {'acting': 1, 'background'... | {'linked to': 1, 'way shor... |\n", "| {'photography': 1, 'others... | {'curiously ends': 1, 'sev... |\n", "| {'just': 1, 'this': 2, 'wh... | {'bob thornton': 1, 'in th... |\n", "| {'peter': 1, 'ii': 1, 'ful... | {'in the': 1, 'is a': 1, '... |\n", "+-------------------------------+-------------------------------+\n", "[25000 rows x 5 columns]\n", "Note: Only the head of the SFrame is printed.\n", "You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns." ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "movies_reviews_data" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "As before, we will construct and evaluate a movie reviews sentiment classifier. However, this time we will use both the '1grams features' and the '2grams features' features" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:53:14.076698Z", "start_time": "2019-06-14T16:52:28.001732Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "PROGRESS: Creating a validation set from 5 percent of training data. This may take a while.\n", " You can set ``validation_set=None`` to disable validation tracking.\n", "\n", "PROGRESS: The following methods are available for this type of problem.\n", "PROGRESS: LogisticClassifier, SVMClassifier\n", "PROGRESS: The returned model will be chosen according to validation accuracy.\n" ] }, { "data": { "text/html": [ "
Logistic regression:
" ], "text/plain": [ "Logistic regression:" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of examples          : 19077
" ], "text/plain": [ "Number of examples : 19077" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of classes           : 2
" ], "text/plain": [ "Number of classes : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of feature columns   : 2
" ], "text/plain": [ "Number of feature columns : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of unpacked features : 1206694
" ], "text/plain": [ "Number of unpacked features : 1206694" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of coefficients      : 1206695
" ], "text/plain": [ "Number of coefficients : 1206695" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Starting L-BFGS
" ], "text/plain": [ "Starting L-BFGS" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| Iteration | Passes   | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |
" ], "text/plain": [ "| Iteration | Passes | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 0         | 3        | 0.500000  | 0.884358     | 0.999266          | 0.866667            |
" ], "text/plain": [ "| 0 | 3 | 0.500000 | 0.884358 | 0.999266 | 0.866667 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 1         | 5        | 0.500000  | 1.542838     | 0.999948          | 0.866667            |
" ], "text/plain": [ "| 1 | 5 | 0.500000 | 1.542838 | 0.999948 | 0.866667 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 2         | 6        | 0.625000  | 1.909261     | 1.000000          | 0.865672            |
" ], "text/plain": [ "| 2 | 6 | 0.625000 | 1.909261 | 1.000000 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 3         | 8        | 0.625000  | 2.436618     | 1.000000          | 0.864677            |
" ], "text/plain": [ "| 3 | 8 | 0.625000 | 2.436618 | 1.000000 | 0.864677 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 4         | 10       | 0.625000  | 2.971373     | 1.000000          | 0.863682            |
" ], "text/plain": [ "| 4 | 10 | 0.625000 | 2.971373 | 1.000000 | 0.863682 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 9         | 18       | 0.976563  | 5.228981     | 1.000000          | 0.862687            |
" ], "text/plain": [ "| 9 | 18 | 0.976563 | 5.228981 | 1.000000 | 0.862687 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
SVM:
" ], "text/plain": [ "SVM:" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of examples          : 19077
" ], "text/plain": [ "Number of examples : 19077" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of classes           : 2
" ], "text/plain": [ "Number of classes : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of feature columns   : 2
" ], "text/plain": [ "Number of feature columns : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of unpacked features : 1206694
" ], "text/plain": [ "Number of unpacked features : 1206694" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of coefficients    : 1206695
" ], "text/plain": [ "Number of coefficients : 1206695" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Starting L-BFGS
" ], "text/plain": [ "Starting L-BFGS" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| Iteration | Passes   | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |
" ], "text/plain": [ "| Iteration | Passes | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 0         | 2        | 1.000000  | 0.710178     | 0.999266          | 0.866667            |
" ], "text/plain": [ "| 0 | 2 | 1.000000 | 0.710178 | 0.999266 | 0.866667 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 1         | 4        | 1.000000  | 1.227603     | 1.000000          | 0.865672            |
" ], "text/plain": [ "| 1 | 4 | 1.000000 | 1.227603 | 1.000000 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 2         | 5        | 1.000000  | 1.524246     | 1.000000          | 0.865672            |
" ], "text/plain": [ "| 2 | 5 | 1.000000 | 1.524246 | 1.000000 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 3         | 6        | 1.000000  | 1.824261     | 1.000000          | 0.865672            |
" ], "text/plain": [ "| 3 | 6 | 1.000000 | 1.824261 | 1.000000 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 4         | 13       | 0.001263  | 3.080125     | 1.000000          | 0.865672            |
" ], "text/plain": [ "| 4 | 13 | 0.001263 | 3.080125 | 1.000000 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 9         | 26       | 0.262737  | 6.006328     | 1.000000          | 0.865672            |
" ], "text/plain": [ "| 9 | 26 | 0.262737 | 6.006328 | 1.000000 | 0.865672 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "PROGRESS: Model selection based on validation accuracy:\n", "PROGRESS: ---------------------------------------------\n", "PROGRESS: LogisticClassifier : 0.8626865671641791\n", "PROGRESS: SVMClassifier : 0.8656716417910447\n", "PROGRESS: ---------------------------------------------\n", "PROGRESS: Selecting SVMClassifier based on validation set performance.\n" ] } ], "source": [ "train_set, test_set = movies_reviews_data.random_split(0.8, seed=5)\n", "model_2 = tc.classifier.create(train_set, target='sentiment', features=['1grams features','2grams features'])\n", "result2 = model_2.evaluate(test_set)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:53:48.981670Z", "start_time": "2019-06-14T16:53:48.974028Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "******************************\n", "Accuracy : 0.8816592110614071\n", "Confusion Matrix: \n", " +--------------+-----------------+-------+\n", "| target_label | predicted_label | count |\n", "+--------------+-----------------+-------+\n", "| 0 | 1 | 343 |\n", "| 1 | 0 | 239 |\n", "| 1 | 1 | 2154 |\n", "| 0 | 0 | 2182 |\n", "+--------------+-----------------+-------+\n", "[4 rows x 3 columns]\n", "\n" ] } ], "source": [ "print_statistics(result2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Indeed, the new constructed classifier seems to be more accurate with an accuracy of about ~0.9." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "## Unlabeled Test File" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "To test how well the presented method works, we will use all the 25,000 labeled IMDB movie reviews in the train dataset to construct a classifier. Afterwards, we will utilize the constructed classifier to predict sentiment for each review in the unlabeled dataset. Lastly, we will create a submission file according to Kaggle's guidelines and submit it. " ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "ExecuteTime": { "end_time": "2019-06-14T16:55:06.281150Z", "start_time": "2019-06-14T16:54:02.968826Z" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/html": [ "
Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv
" ], "text/plain": [ "Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Parsing completed. Parsed 100 lines in 0.282738 secs.
" ], "text/plain": [ "Parsing completed. Parsed 100 lines in 0.282738 secs." ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv
" ], "text/plain": [ "Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Parsing completed. Parsed 25000 lines in 0.507212 secs.
" ], "text/plain": [ "Parsing completed. Parsed 25000 lines in 0.507212 secs." ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "PROGRESS: Creating a validation set from 5 percent of training data. This may take a while.\n", " You can set ``validation_set=None`` to disable validation tracking.\n", "\n", "PROGRESS: The following methods are available for this type of problem.\n", "PROGRESS: LogisticClassifier, SVMClassifier\n", "PROGRESS: The returned model will be chosen according to validation accuracy.\n" ] }, { "data": { "text/html": [ "
Logistic regression:
" ], "text/plain": [ "Logistic regression:" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of examples          : 23750
" ], "text/plain": [ "Number of examples : 23750" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of classes           : 2
" ], "text/plain": [ "Number of classes : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of feature columns   : 2
" ], "text/plain": [ "Number of feature columns : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of unpacked features : 1407914
" ], "text/plain": [ "Number of unpacked features : 1407914" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of coefficients      : 1407915
" ], "text/plain": [ "Number of coefficients : 1407915" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Starting L-BFGS
" ], "text/plain": [ "Starting L-BFGS" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| Iteration | Passes   | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |
" ], "text/plain": [ "| Iteration | Passes | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 0         | 2        | 1.000000  | 0.772874     | 0.998821          | 0.896000            |
" ], "text/plain": [ "| 0 | 2 | 1.000000 | 0.772874 | 0.998821 | 0.896000 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 1         | 4        | 1.000000  | 1.443709     | 0.999916          | 0.894400            |
" ], "text/plain": [ "| 1 | 4 | 1.000000 | 1.443709 | 0.999916 | 0.894400 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 2         | 6        | 0.648072  | 2.077022     | 0.999958          | 0.895200            |
" ], "text/plain": [ "| 2 | 6 | 0.648072 | 2.077022 | 0.999958 | 0.895200 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 3         | 8        | 0.648072  | 2.769055     | 0.999958          | 0.894400            |
" ], "text/plain": [ "| 3 | 8 | 0.648072 | 2.769055 | 0.999958 | 0.894400 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 4         | 10       | 0.648072  | 3.420360     | 0.999958          | 0.894400            |
" ], "text/plain": [ "| 4 | 10 | 0.648072 | 3.420360 | 0.999958 | 0.894400 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 9         | 22       | 0.486054  | 6.816458     | 1.000000          | 0.892800            |
" ], "text/plain": [ "| 9 | 22 | 0.486054 | 6.816458 | 1.000000 | 0.892800 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
SVM:
" ], "text/plain": [ "SVM:" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of examples          : 23750
" ], "text/plain": [ "Number of examples : 23750" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of classes           : 2
" ], "text/plain": [ "Number of classes : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of feature columns   : 2
" ], "text/plain": [ "Number of feature columns : 2" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of unpacked features : 1407914
" ], "text/plain": [ "Number of unpacked features : 1407914" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Number of coefficients    : 1407915
" ], "text/plain": [ "Number of coefficients : 1407915" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Starting L-BFGS
" ], "text/plain": [ "Starting L-BFGS" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
--------------------------------------------------------
" ], "text/plain": [ "--------------------------------------------------------" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| Iteration | Passes   | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |
" ], "text/plain": [ "| Iteration | Passes | Step size | Elapsed Time | Training Accuracy | Validation Accuracy |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 0         | 2        | 1.000000  | 0.724382     | 0.998821          | 0.896000            |
" ], "text/plain": [ "| 0 | 2 | 1.000000 | 0.724382 | 0.998821 | 0.896000 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 1         | 4        | 1.000000  | 1.284643     | 0.999916          | 0.896000            |
" ], "text/plain": [ "| 1 | 4 | 1.000000 | 1.284643 | 0.999916 | 0.896000 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 2         | 5        | 1.000000  | 1.634216     | 0.999958          | 0.896000            |
" ], "text/plain": [ "| 2 | 5 | 1.000000 | 1.634216 | 0.999958 | 0.896000 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 3         | 6        | 1.000000  | 2.002875     | 0.999958          | 0.896000            |
" ], "text/plain": [ "| 3 | 6 | 1.000000 | 2.002875 | 0.999958 | 0.896000 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 4         | 13       | 0.000338  | 3.462338     | 1.000000          | 0.895200            |
" ], "text/plain": [ "| 4 | 13 | 0.000338 | 3.462338 | 1.000000 | 0.895200 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
| 9         | 38       | 4.080042  | 9.019969     | 1.000000          | 0.895200            |
" ], "text/plain": [ "| 9 | 38 | 4.080042 | 9.019969 | 1.000000 | 0.895200 |" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
+-----------+----------+-----------+--------------+-------------------+---------------------+
" ], "text/plain": [ "+-----------+----------+-----------+--------------+-------------------+---------------------+" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "PROGRESS: Model selection based on validation accuracy:\n", "PROGRESS: ---------------------------------------------\n", "PROGRESS: LogisticClassifier : 0.8928\n", "PROGRESS: SVMClassifier : 0.8952\n", "PROGRESS: ---------------------------------------------\n", "PROGRESS: Selecting SVMClassifier based on validation set performance.\n" ] }, { "data": { "text/html": [ "
Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/testData.tsv
" ], "text/plain": [ "Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/testData.tsv" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Parsing completed. Parsed 100 lines in 0.313905 secs.
" ], "text/plain": [ "Parsing completed. Parsed 100 lines in 0.313905 secs." ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/testData.tsv
" ], "text/plain": [ "Finished parsing file /Users/datalab/bigdata/cjc/kaggle_popcorn_data/testData.tsv" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "
Parsing completed. Parsed 25000 lines in 0.560208 secs.
" ], "text/plain": [ "Parsing completed. Parsed 25000 lines in 0.560208 secs." ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "traindata_path = \"/Users/datalab/bigdata/cjc/kaggle_popcorn_data/labeledTrainData.tsv\"\n", "testdata_path = \"/Users/datalab/bigdata/cjc/kaggle_popcorn_data/testData.tsv\"\n", "#creating classifier using all 25,000 reviews\n", "train_data = tc.SFrame.read_csv(traindata_path,header=True, delimiter='\\t',quote_char='\"', \n", " column_type_hints = {'id':str, 'sentiment' : int, 'review':str } )\n", "train_data['1grams features'] = tc.text_analytics.count_ngrams(train_data['review'],1)\n", "train_data['2grams features'] = tc.text_analytics.count_ngrams(train_data['review'],2)\n", "\n", "cls = tc.classifier.create(train_data, target='sentiment', features=['1grams features','2grams features'])\n", "#creating the test dataset\n", "test_data = tc.SFrame.read_csv(testdata_path,header=True, delimiter='\\t',quote_char='\"', \n", " column_type_hints = {'id':str, 'review':str } )\n", "test_data['1grams features'] = tc.text_analytics.count_ngrams(test_data['review'],1)\n", "test_data['2grams features'] = tc.text_analytics.count_ngrams(test_data['review'],2)\n", "\n", "#predicting the sentiment of each review in the test dataset\n", "test_data['sentiment'] = cls.classify(test_data)['class'].astype(int)\n", "\n", "#saving the prediction to a CSV for submission\n", "test_data[['id','sentiment']].save(\"/Users/datalab/bigdata/cjc/kaggle_popcorn_data/predictions.csv\", format=\"csv\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "We then submitted the predictions.csv file to the Kaggle challange website and scored AUC of about 0.88." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "## Further Readings" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Further reading materials can be found in the following links:\n", "\n", "http://en.wikipedia.org/wiki/Bag-of-words_model\n", "\n", "https://dato.com/products/create/docs/generated/graphlab.SFrame.html\n", "\n", "https://dato.com/products/create/docs/graphlab.toolkits.classifier.html\n", "\n", "https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-1-for-beginners-bag-of-words\n", "\n", "Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng, and Christopher Potts. (2011). \"Learning Word Vectors for Sentiment Analysis.\" The 49th Annual Meeting of the Association for Computational Linguistics (ACL 2011).\n" ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python [conda env:anaconda]", "language": "python", "name": "conda-env-anaconda-py" }, "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.5.4" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": false, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "312px", "left": "998px", "top": "111px", "width": "260px" }, "toc_section_display": false, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }