{ "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.5.0" }, "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import pandas as pd\n", "\n", "# Some nice default configuration for plots\n", "plt.rcParams['figure.figsize'] = 10, 7.5\n", "plt.rcParams['axes.grid'] = True" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Large Scale Text Classification for Sentiment Analysis" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Outline of the Session" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Limitations of the Vocabulary-Based Vectorizer\n", "- The **Hashing Trick**\n", "- **Online / Streaming** Text Feature Extraction and Classification\n", "- **Parallel** Text Feature Extraction and Classification" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Scalability Issues" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `sklearn.feature_extraction.text.CountVectorizer` and `sklearn.feature_extraction.text.TfidfVectorizer` classes suffer from a number of scalability issues that all stem from the internal usage of the `vocabulary_` attribute (a Python dictionary) used to map the unicode string feature names to the integer feature indices.\n", "\n", "The main scalability issues are:\n", "\n", "- **Memory usage of the text vectorizer**: all the string representations of the features are loaded in memory\n", "- **Parallelization problems for text feature extraction**: the `vocabulary_` would be a shared state: complex synchronization and overhead\n", "- **Impossibility to do online or out-of-core / streaming learning**: the `vocabulary_` needs to be learned from the data: its size cannot be known before making one pass over the full dataset\n", " \n", " \n", "To better understand the issue, let's have a look at how the `vocabulary_` attribute works. At `fit` time the tokens of the corpus are uniquely identified by a integer index and this mapping stored in the vocabulary:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.feature_extraction.text import CountVectorizer\n", "\n", "vectorizer = CountVectorizer(min_df=1)\n", "\n", "vectorizer.fit([\n", " \"The cat sat on the mat.\",\n", "])\n", "vectorizer.vocabulary_" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The vocabulary is used at `transform` time to build the occurence matrix:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "X = vectorizer.transform([\n", " \"The cat sat on the mat.\",\n", " \"This cat is a nice cat.\",\n", "]).toarray()\n", "\n", "print(len(vectorizer.vocabulary_))\n", "print(vectorizer.get_feature_names())\n", "print(X)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's refit with a slightly larger corpus:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "vectorizer = CountVectorizer(min_df=1)\n", "\n", "vectorizer.fit([\n", " \"The cat sat on the mat.\",\n", " \"The quick brown fox jumps over the lazy dog.\",\n", "])\n", "vectorizer.vocabulary_" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `vocabulary_` is (logarithmically) growing with the size of the training corpus. Note that we could not have built the vocabularies in parallel on the 2 text documents as they share some words, hence would require some kind of shared datastructure or synchronization barrier which is complicated to setup, especially if we want to distribute the processing on a cluster.\n", "\n", "With this new vocabulary, the dimensionality of the output space is now larger:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "X = vectorizer.transform([\n", " \"The cat sat on the mat.\",\n", " \"This cat is a nice cat.\",\n", "]).toarray()\n", "\n", "print(len(vectorizer.vocabulary_))\n", "print(vectorizer.get_feature_names())\n", "print(X)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "The Sentiment 140 Dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To illustrate the scalability issues of the vocabulary-based vectorizers, let's load a more realistic dataset for a classical text classification task: sentiment analysis on tweets. The goal is to tell apart negative from positive tweets on a variety of topics." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%run ../fetch_data.py sentiment140" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Assuming that the `../fetch_data.py` script was run successfully the following files should be available:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import os\n", "\n", "sentiment140_folder = os.path.join('..', 'datasets', 'sentiment140')\n", "training_csv_file = os.path.join(sentiment140_folder, 'training.1600000.processed.noemoticon.csv')\n", "testing_csv_file = os.path.join(sentiment140_folder, 'testdata.manual.2009.06.14.csv')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Those files were downloaded from the research archive of the http://www.sentiment140.com/ project. The first file was gathered using the twitter streaming API by running stream queries for the positive \":)\" and negative \":(\" emoticons to collect tweets that are explicitly positive or negative. To make the classification problem non-trivial, the emoticons were stripped out of the text in the CSV files:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "ls -lh ../datasets/sentiment140/training.1600000.processed.noemoticon.csv" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "!head -3 ../datasets/sentiment140/training.1600000.processed.noemoticon.csv" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's parse the CSV files and load everything in memory. As loading everything can take up to 2GB, let's limit the collection to 100K tweets of each (positive and negative) out of the total of 1.6M tweets." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%time\n", "names = ('polarity', 'id', 'date', 'query', 'author', 'text')\n", "data_train = pd.read_csv(training_csv_file, encoding='latin1', names=names)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "data_train.head(5)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "text_train_all = data_train['text']\n", "target_train_all = data_train['polarity'].values" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "len(text_train_all), len(target_train_all)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's display the first samples:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for text in text_train_all[:3]:\n", " print(text + \"\\n\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(target_train_all[:3])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A polarity of \"0\" means negative while a polarity of \"4\" means positive. All the positive tweets are at the end of the file:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for text in text_train_all[-3:]:\n", " print(text + \"\\n\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print(target_train_all[-3:])" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's split the training CSV file into a smaller training set and a validation set with 100k random tweets each:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.cross_validation import train_test_split\n", "\n", "text_train_small, text_validation, target_train_small, target_validation = train_test_split(\n", " text_train_all, target_train_all, test_size=.5, random_state=42)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's open the manually annotated tweet files. The evaluation set also has neutral tweets with a polarity of \"2\" which we ignore in this example. In real a real life setting, modelling a neutral class is extremely important. I could be done by collecting random additional data from twitter, rejecting tweets with strong polarity markers such as smiley for instance. We leave this discussion for future work.\n", "\n", "We can build the final evaluation set with only the positive and negative tweets of the evaluation CSV file:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "data_test = pd.read_csv(testing_csv_file, names=names)\n", "data_test.head(5)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "non_neutral_data_test = data_test[data_test['polarity'] != 2]\n", "\n", "text_test_all = non_neutral_data_test['text']\n", "target_test_all = non_neutral_data_test['polarity']" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "len(text_test_all), len(target_test_all)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "The Hashing Trick" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To workaround the limitations of the vocabulary-based vectorizers, one can use the hashing trick. Instead of building and storing an explicit mapping from the feature names to the feature indices in a Python dict, we can just use a hash function and a modulus operation:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.utils.murmurhash import murmurhash3_bytes_u32\n", "\n", "for word in u\"the cat sat on the mat\".split():\n", " word_bytes = word.encode('utf-8')\n", " print(u\"{0} => {1}\".format(\n", " word, murmurhash3_bytes_u32(word_bytes, 0) % 2 ** 20))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This mapping is completely stateless and the dimensionality of the output space is explicitly fixed in advance (here we use a modulo `2 ** 20` which means roughly 1M dimensions). This makes it possible to workaround the limitations of the vocabulary based vectorizer both for parallelizability and online / out-of-core learning." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `HashingVectorizer` class is an alternative to the `TfidfVectorizer` class with `use_idf=False` that internally uses the murmurhash hash function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.feature_extraction.text import HashingVectorizer\n", "\n", "h_vectorizer = HashingVectorizer(encoding='latin-1')\n", "h_vectorizer" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It shares the same \"preprocessor\", \"tokenizer\" and \"analyzer\" infrastructure:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "analyzer = h_vectorizer.build_analyzer()\n", "analyzer('This is a test sentence.')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can vectorize our datasets into a scipy sparse matrix exactly as we would have done with the `CountVectorizer` or `TfidfVectorizer`, except that we can directly call the `transform` method: there is no need to `fit` as `HashingVectorizer` is a stateless transformer:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%time X_train_small = h_vectorizer.transform(text_train_small)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The dimension of the output is fixed ahead of time to `n_features=2 ** 20` by default (nearly 1M features) to minimize the rate of collision on most classification problem while having reasonably sized linear models (1M weights in the `coef_` attribute):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "X_train_small" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As only the non-zero elements are stored, `n_features` has little impact on the actual size of the data in memory. We can combine the hashing vectorizer with a Passive-Aggressive linear model in a pipeline:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.linear_model import PassiveAggressiveClassifier\n", "from sklearn.pipeline import Pipeline\n", "\n", "h_pipeline = Pipeline((\n", " ('vec', HashingVectorizer(encoding='latin-1')),\n", " ('clf', PassiveAggressiveClassifier(C=1, n_iter=1)),\n", "))\n", "\n", "%time h_pipeline.fit(text_train_small, target_train_small).score(text_validation, target_validation)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's check that the score on the validation set is reasonably in line with the set of manually annotated tweets:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "h_pipeline.score(text_test_all, target_test_all)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As the `text_train_small` dataset is not that big, we can still use a vocabulary based vectorizer to check that the hashing collisions are not causing any significant performance drop on the validation set (**WARNING** this is twice as slow as the hashing vectorizer version, skip this cell if your computer is too slow):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.feature_extraction.text import TfidfVectorizer\n", "\n", "vocabulary_vec = TfidfVectorizer(encoding='latin-1', use_idf=False)\n", "vocabulary_pipeline = Pipeline((\n", " ('vec', vocabulary_vec),\n", " ('clf', PassiveAggressiveClassifier(C=1, n_iter=1)),\n", "))\n", "\n", "%time vocabulary_pipeline.fit(text_train_small, target_train_small).score(text_validation, target_validation)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We get almost the same score but almost twice as slower with also a big, slow to (un)pickle datastructure in memory:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "len(vocabulary_vec.vocabulary_)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More info and reference for the original papers on the Hashing Trick in the answers to this http://metaoptimize.com/qa question: [What is the Hashing Trick?](http://metaoptimize.com/qa/questions/6943/what-is-the-hashing-trick)." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Out-of-Core learning" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Out-of-Core learning is the task of training a machine learning model on a dataset that does not fit in the main memory. This requires the following conditions:\n", " \n", "- a **feature extraction** layer with **fixed output dimensionality**\n", "- knowing the list of all classes in advance (in this case we only have positive and negative tweets)\n", "- a machine learning **algorithm that supports incremental learning** (the `partial_fit` method in scikit-learn).\n", "\n", "Let us simulate an infinite tweeter stream that can generate batches of annotated tweet texts and their polarity. We can do this by recombining randomly pairs of positive or negative tweets from our fixed dataset:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "target_train_small" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "from random import Random\n", "\n", "\n", "class InfiniteStreamGenerator(object):\n", " \"\"\"Simulate random polarity queries on the twitter streaming API\"\"\"\n", " \n", " def __init__(self, texts, targets, seed=0, batchsize=100):\n", " self.texts_pos = [text for text, target in zip(texts, targets)\n", " if target > 2]\n", " self.texts_neg = [text for text, target in zip(texts, targets)\n", " if target <= 2]\n", " self.rng = Random(seed)\n", " self.batchsize = batchsize\n", "\n", " def next_batch(self, batchsize=None):\n", " batchsize = self.batchsize if batchsize is None else batchsize\n", " texts, targets = [], []\n", " for i in range(batchsize):\n", " # Select the polarity randomly\n", " target = self.rng.choice((0, 4))\n", " targets.append(target)\n", " \n", " # Combine 2 random texts of the right polarity\n", " pool = self.texts_pos if target > 2 else self.texts_neg\n", " text = self.rng.choice(pool) + \" \" + self.rng.choice(pool)\n", " texts.append(text)\n", " return texts, targets\n", "\n", "infinite_stream = InfiniteStreamGenerator(text_train_all, target_train_all)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "texts_in_batch, targets_in_batch = infinite_stream.next_batch(batchsize=3)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "for t in texts_in_batch:\n", " print(t + \"\\n\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "targets_in_batch" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now use our infinte tweet source to train an online machine learning algorithm using the hashing vectorizer. Note the use of the `partial_fit` method of the `PassiveAggressiveClassifier` instance in place of the traditional call to the `fit` method that needs access to the full training set.\n", "\n", "From time to time, we evaluate the current predictive performance of the model on our validation set that is guaranteed to not overlap with the infinite training set source:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "n_batches = 1000\n", "validation_scores = []\n", "training_set_size = []\n", "\n", "# Build the vectorizer and the classifier\n", "h_vectorizer = HashingVectorizer(encoding='latin-1')\n", "clf = PassiveAggressiveClassifier(C=1)\n", "\n", "# Extract the features for the validation once and for all\n", "X_validation = h_vectorizer.transform(text_validation)\n", "classes = np.array([0, 4])\n", "\n", "n_samples = 0\n", "for i in range(n_batches):\n", " \n", " texts_in_batch, targets_in_batch = infinite_stream.next_batch() \n", " n_samples += len(texts_in_batch)\n", "\n", " # Vectorize the text documents in the batch\n", " X_batch = h_vectorizer.transform(texts_in_batch)\n", " \n", " # Incrementally train the model on the new batch\n", " clf.partial_fit(X_batch, targets_in_batch, classes=classes)\n", " \n", " if n_samples % 100 == 0:\n", " # Compute the validation score of the current state of the model\n", " score = clf.score(X_validation, target_validation)\n", " validation_scores.append(score)\n", " training_set_size.append(n_samples)\n", "\n", " if i % 100 == 0:\n", " print(\"n_samples: {0}, score: {1:.4f}\".format(n_samples, score))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now plot the collected validation score values, versus the number of samples generated by the infinite source and feed to the model:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.plot(training_set_size, validation_scores)\n", "plt.xlabel(\"Number of samples\")\n", "plt.ylabel(\"Validation score\")\n", "plt.title('Progression of validation score with number of samples');" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Parallelizing Text Classification" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Partitioning the Data and Training in Parallel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As the `HashingVectorizer` is stateless, one can use a separate instance (with the same parameters) in parallel or distributed processes to extract the features on independant partitions of a big text dataset. Each partition of extracted features can then be fed to independent instances of a linear classifier model on each computing node:\n", "\n", "" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Final Linear Model Averaging" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once all the nodes are ready we can average the linear models:\n", " \n", "" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Sample Implementation on the Tweet Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's use IPython parallel to read partitions of the train CSV in different Python processes using the interactive IPython.parallel interface:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.parallel import Client\n", "\n", "client = Client()\n", "len(client)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's tell each engine which partition of the data it will have to handle:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "dv = client.direct_view()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "dv.scatter('partition_ids', range(len(client)), block=True)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%px print(partition_ids)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%px partition_id = partition_ids[0]" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%px print(partition_id)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's send all we need to the engines" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.feature_extraction.text import HashingVectorizer\n", "\n", "h_vectorizer = HashingVectorizer(encoding='latin-1')\n", "dv['h_vectorizer'] = h_vectorizer\n", "dv['names'] = names\n", "dv['training_csv_file'] = training_csv_file\n", "dv['n_partitions'] = len(client)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "%px print(training_csv_file)\n", "%px print(n_partitions)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We are now ready to read the data partition from the CSV file, vectorize it, and train an indepenent model on each IPython.parallel engine:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%px\n", "\n", "import pandas as pd\n", "\n", "max_count = 50000\n", "print(\"Parsing %d items for partition %d...\" % (max_count, partition_id))\n", "\n", "\n", "data = pd.read_csv(training_csv_file, names=names, encoding='latin-1')\n", "data = data[data['id'] % n_partitions == partition_id]\n", "\n", "texts, targets = data['text'], data['polarity'].values\n", "\n", "print(\"Shuffling the positive and negative examples...\")\n", "\n", "from sklearn.utils import shuffle\n", "texts, targets = shuffle(texts, targets, random_state=1)\n", "\n", "print(\"Vectorizing text data...\")\n", "\n", "vectors = h_vectorizer.transform(texts)\n", "\n", "print(\"Fitting a linear model...\")\n", "\n", "from sklearn.linear_model import Perceptron\n", "clf = Perceptron(n_iter=1).fit(vectors, targets)\n", "\n", "print(\"Done!\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "classifiers = dv.gather('clf', block=True)\n", "classifiers" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now compute the average linear model:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from copy import copy\n", "\n", "def average_linear_model(models):\n", " \"\"\"Compute a linear model that is the average of the others\"\"\"\n", " avg = copy(models[0])\n", "\n", " avg.coef_ = np.sum([m.coef_ for m in models], axis=0)\n", " avg.coef_ /= len(models)\n", " \n", " avg.intercept_ = np.sum([m.intercept_ for m in models], axis=0)\n", " avg.intercept_ /= len(models)\n", "\n", " return avg\n", " \n", "\n", "clf = average_linear_model(classifiers)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's compare the score of the average model with the scores of the individual classifiers. The average models can have a better generalization than the individual models being averaged:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "clf.score(h_vectorizer.transform(text_test_all), target_test_all)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "for c in classifiers:\n", " print(c.score(h_vectorizer.transform(text_test_all), target_test_all))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Averaging linear models learned on different datasets that follow the same distribution is a form of Ensemble method. Other Ensemble methods include:\n", " \n", "- Boosted models (see [Gradient Tree Boosting](http://scikit-learn.org/dev/modules/ensemble.html#gradient-tree-boosting) available in 0.13 and [AdaBoost](http://scikit-learn.org/dev/modules/ensemble.html#adaboost) in master),\n", "- Bagging (Bootstrap Aggregating) as done in [Random Forests](http://scikit-learn.org/dev/modules/ensemble.html#random-forests). Decision Trees as the base model\n", "- Other non-bootstrapped, randomized aggregate of Decision Trees such as [Extremely Randomized Trees](http://scikit-learn.org/dev/modules/ensemble.html#extremely-randomized-trees).\n", "- Averaging the probabilistic estimate of a library of randomized and / or heterogeneous linear or non-linear models.\n", "- Stacking, for instance: training a final Random Forest on the probabilistic class assignment output of a library of randomized and / or heterogeneous linear or non-linear models." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Limitations of the Hashing Vectorizer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the Hashing Vectorizer makes it possible to implement streaming and parallel text classification but can also introduce some issues:\n", " \n", "- The collisions can introduce too much noise in the data and degrade prediction quality,\n", "- The `HashingVectorizer` does not provide \"Inverse Document Frequency\" reweighting (lack of a `use_idf=True` option).\n", "- There is no easy way to inverse the mapping and find the feature names from the feature index.\n", "\n", "The collision issues can be controlled by increasing the `n_features` parameters.\n", "\n", "The IDF weighting might be reintroduced by appending a `TfidfTransformer` instance on the output of the vectorizer. However computing the `idf_` statistic used for the feature reweighting will require to do at least one additional pass over the training set before being able to start training the classifier: this breaks the online learning scheme.\n", "\n", "The lack of inverse mapping (the `get_feature_names()` method of `TfidfVectorizer`) is even harder to workaround. That would require extending the `HashingVectorizer` class to add a \"trace\" mode to record the mapping of the most important features to provide statistical debugging information.\n", "\n", "In the mean time to debug feature extraction issues, it is recommended to use `TfidfVectorizer(use_idf=False)` on a small-ish subset of the dataset to simulate a `HashingVectorizer()` instance that have the `get_feature_names()` method and no collision issues." ] } ], "metadata": {} } ] }