{ "cells": [ { "cell_type": "markdown", "metadata": { "_cell_guid": "403f8973-1fb5-422c-bd82-fb5d7041d8b2", "_uuid": "091313c11c12aaeef8bc25b39a205f79bb2588a6", "collapsed": true }, "source": [ "
\n", "\n", " \n", "## [mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course \n", "\n", "Author: [Yury Kashnitskiy](https://yorko.github.io). Translated and edited by [Serge Oreshkov](https://www.linkedin.com/in/sergeoreshkov/), and [Yuanyuan Pao](https://www.linkedin.com/in/yuanyuanpao/). This material is subject to the terms and conditions of the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license. Free use is permitted for any non-commercial purpose.\n", "\n", "#
Topic 8. Vowpal Wabbit: Learning with Gigabytes of Data\n", "This week, we’ll cover two reasons for Vowpal Wabbit’s exceptional training speed, namely, online learning and hashing trick, in both theory and practice. We will try it out with news, movie reviews, and StackOverflow questions." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "a783ea16-a0be-4a81-9d91-72c9ada412d0", "_uuid": "aba8923437f1bb67ff9615f218dbe3cb19145f4e" }, "source": [ "# Outline\n", "1. [Stochastic gradient descent and online learning](#1.-Stochastic-gradient-descent-and-online-learning)\n", " - 1.1. [SGD](#1.1.-Stochastic-gradient-descent)\n", " - 1.2. [Online approach to learning](#1.2.-Online-approach-to-learning)\n", "2. [Categorical feature processing](#2.-Categorical-feature-processing)\n", " - 2.1. [Label Encoding](#2.1.-Label-Encoding)\n", " - 2.2. [One-Hot Encoding](#2.2.-One-Hot-Encoding)\n", " - 2.3. [Hashing trick](#2.3.-Hashing-trick)\n", "3. [Vowpal Wabbit](#3.-Vowpal-Wabbit)\n", " - 3.1. [News. Binary classification](#3.1.-News.-Binary-classification)\n", " - 3.2. [News. Multiclass classification](#3.2.-News.-Multiclass-classification)\n", " - 3.3. [IMDB movie reviews](#3.3.-IMDB-movie-reviews)\n", " - 3.4. [Classifying gigabytes of StackOverflow questions](#3.4.-Classifying-gigabytes-of-StackOverflow-questions)\n", "4. [Demo assignment](#4.-Demo-assignment)\n", "5. [Useful resources](#5.-Useful-resources)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "64efb6ef-3591-4036-8461-b7b467f404b7", "_uuid": "bd1f11458028d021571d4a77e3de846bf0dee992" }, "outputs": [], "source": [ "import os\n", "import re\n", "import warnings\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import pandas as pd\n", "from scipy.sparse import csr_matrix\n", "from sklearn.datasets import fetch_20newsgroups, load_files\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.metrics import (accuracy_score, classification_report,\n", " confusion_matrix, log_loss, roc_auc_score,\n", " roc_curve)\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.preprocessing import LabelEncoder, OneHotEncoder\n", "from tqdm import tqdm_notebook\n", "\n", "%matplotlib inline\n", "import seaborn as sns" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "warnings.filterwarnings(\"ignore\")" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "ddb2276a-dd17-4229-8a0b-1860056dc08a", "_uuid": "8c3581ddac23e8621f7688aec41bbce23e91bc6c" }, "source": [ "## 1. Stochastic gradient descent and online learning\n", "### 1.1. Stochastic gradient descent\n", "\n", "Despite the fact that gradient descent is one of the first things learned in machine learning and optimization courses, it is one of its modifications, Stochastic Gradient Descent (SGD), that is hard to top.\n", "\n", "Recall that the idea of gradient descent is to minimize some function by making small steps in the direction of the fastest decrease. This method was named due to the following fact from calculus: vector $\\nabla f = (\\frac{\\partial f}{\\partial x_1}, \\ldots \\frac{\\partial f}{\\partial x_n})^\\text{T}$ of partial derivatives of the function $f(x) = f(x_1, \\ldots x_n)$ points to the direction of the fastest function growth. It means that, by moving in the opposite direction (antigradient), it is possible to decrease the function value with the fastest rate.\n", "\n", "\n", "\n", "Here is a snowboarder (me) in Sheregesh, Russia's most popular winter resort. (I highly recommended it if you like skiing or snowboarding). In addition to advertising the beautiful landscapes, this picture depicts the idea of gradient descent. If you want to ride as fast as possible, you need to choose the path of steepest descent. Calculating antigradients can be seen as evaluating the slope at various spots." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "eda14ceb-ab19-4c75-a1ad-bbbbf3acb83d", "_uuid": "7c41b31a7549e4dbcd0c31824d425d18ec6b9fbb" }, "source": [ "**Example**\n", "\n", "The paired regression problem can be solved with gradient descent. Let us predict one variable using another: height with weight. Assume that these variables are linearly dependent. We will use the [SOCR](http://wiki.stat.ucla.edu/socr/index.php/SOCR_Data) dataset. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "84022022-7ce2-4fac-90ae-3cefc5a12961", "_uuid": "0873cf8a28158f2ebdd5b3b42d3026efcd8e6b58" }, "outputs": [], "source": [ "PATH_TO_ALL_DATA = \"../../data/\"\n", "data_demo = pd.read_csv(os.path.join(PATH_TO_ALL_DATA, \"weights_heights.csv\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "094aa0fc-8af4-4a13-88a7-4eedf53fd712", "_uuid": "a60148fd610f423b517a38dad8768f0f6c76d192" }, "outputs": [], "source": [ "plt.scatter(data_demo[\"Weight\"], data_demo[\"Height\"])\n", "plt.xlabel(\"Weight in lb\")\n", "plt.ylabel(\"Height in inches\");" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "1140d0cf-9aef-4d4b-8d74-86795ef71737", "_uuid": "ad436575e565a80eecc4a9fde161065ff1f22f9f" }, "source": [ "Here we have a vector $x$ of dimension $\\ell$ (weight of every person i.e. training sample) and $y$, a vector containing the height of every person in the dataset. \n", "\n", "The task is the following: find weights $w_0$ and $w_1$ such that predicting height as $y_i = w_0 + w_1 x_i$ (where $y_i$ is $i$-th height value, $x_i$ is $i$-th weight value) minimizes the squared error (as well as mean squared error since $\\frac{1}{\\ell}$ doesn't make any difference ):\n", "$$SE(w_0, w_1) = \\frac{1}{2}\\sum_{i=1}^\\ell(y_i - (w_0 + w_1x_{i}))^2 \\rightarrow min_{w_0,w_1}$$\n", "\n", "We will use gradient descent, utilizing the partial derivatives of $SE(w_0, w_1)$ over weights $w_0$ and $w_1$.\n", "An iterative training procedure is then defined by simple update formulas (we change model weights in small steps, proportional to a small constant $\\eta$, towards the antigradient of the function $SE(w_0, w_1)$):\n", "\n", "$$\\begin{array}{rcl} w_0^{(t+1)} = w_0^{(t)} -\\eta \\frac{\\partial SE}{\\partial w_0} |_{t} \\\\ w_1^{(t+1)} = w_1^{(t)} -\\eta \\frac{\\partial SE}{\\partial w_1} |_{t} \\end{array}$$\n", "\n", "Computing the partial derivatives, we get the following: \n", "\n", "$$\\begin{array}{rcl} w_0^{(t+1)} = w_0^{(t)} + \\eta \\sum_{i=1}^{\\ell}(y_i - w_0^{(t)} - w_1^{(t)}x_i) \\\\ w_1^{(t+1)} = w_1^{(t)} + \\eta \\sum_{i=1}^{\\ell}(y_i - w_0^{(t)} - w_1^{(t)}x_i)x_i \\end{array}$$\n", "\n", "This math works quite well as long as the amount of data is not large (we will not discuss issues with local minima, saddle points, choosing the learning rate, moments and other stuff –- these topics are covered very thoroughly in [the Numeric Computation chapter](http://www.deeplearningbook.org/contents/numerical.html) in \"Deep Learning\"). \n", "There is an issue with batch gradient descent -- the gradient evaluation requires the summation of a number of values for every object from the training set. In other words, the algorithm requires a lot of iterations, and every iteration recomputes weights with formula which contains a sum $\\sum_{i=1}^\\ell$ over the whole training set. What happens when we have billions of training samples?\n", "\n", "\n", "\n", "Hence the motivation for stochastic gradient descent! Simply put, we throw away the summation sign and update the weights only over single training samples (or a small number of them). In our case, we have the following:\n", "\n", "$$\\begin{array}{rcl} w_0^{(t+1)} = w_0^{(t)} + \\eta (y_i - w_0^{(t)} - w_1^{(t)}x_i) \\\\ w_1^{(t+1)} = w_1^{(t)} + \\eta (y_i - w_0^{(t)} - w_1^{(t)}x_i)x_i \\end{array}$$\n", "\n", "With this approach, there is no guarantee that we will move in best possible direction at every iteration. Therefore, we may need many more iterations, but we get much faster weight updates." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "dc9f67f3-4110-40b6-b7bd-a2736233d10f", "_uuid": "7d61f90cd77f5fc64646a22cdcaaa3e9ee012ebc" }, "source": [ "Andrew Ng has a good illustration of this in his [machine learning course](https://www.coursera.org/learn/machine-learning). Let's take a look.\n", "\n", "\n", "\n", "These are the contour plots for some function, and we want to find the global minimum of this function. The red curve shows weight changes (in this picture, $\\theta_0$ and $\\theta_1$ correspond to our $w_0$ and $w_1$). According to the properties of a gradient, the direction of change at every point is orthogonal to contour plots. With stochastic gradient descent, weights are changing in a less predictable manner, and it even may seem that some steps are wrong by leading away from minima; however, both procedures converge to the same solution." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "3583f288-f80e-4853-82d6-d3bdc5da50f5", "_uuid": "fbf630784df546a50ad03c698537e2b0980057a0" }, "source": [ "### 1.2. Online approach to learning\n", "Stochastic gradient descent gives us practical guidance for training both classifiers and regressors with large amounts of data up to hundreds of GBs (depending on computational resources).\n", "\n", "Considering the case of paired regression, we can store the training data set $(X,y)$ in HDD without loading it into RAM (where it simply won't fit), read objects one by one, and update the weights of our model:\n", "\n", "$$\\begin{array}{rcl} w_0^{(t+1)} = w_0^{(t)} + \\eta (y_i - w_0^{(t)} - w_1^{(t)}x_i) \\\\ w_1^{(t+1)} = w_1^{(t)} + \\eta (y_i - w_0^{(t)} - w_1^{(t)}x_i)x_i \\end{array}$$\n", "\n", "After working through the whole training dataset, our loss function (for example, quadratic squared root error in regression or logistic loss in classification) will decrease, but it usually takes dozens of passes over the training set to make the loss small enough. \n", "\n", "This approach to learning is called **online learning**, and this name emerged even before machine learning MOOC-s turned mainstream.\n", "\n", "We did not discuss many specifics about SGD here. If you want dive into theory, I highly recommend [\"Convex Optimization\" by Stephen Boyd](https://www.amazon.com/Convex-Optimization-Stephen-Boyd/dp/0521833787). Now, we will introduce the Vowpal Wabbit library, which is good for training simple models with huge data sets thanks to stochastic optimization and another trick, feature hashing." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "abaadfeb-a49c-4fc9-8cc4-c7739e4f9edc", "_uuid": "23782a78c5bac799ed50cc994f3768163fc70a7c" }, "source": [ "In scikit-learn, classifiers and regressors trained with SGD are named `SGDClassifier` and `SGDRegressor` in `sklearn.linear_model`. These are nice implementations of SGD, but we'll focus on VW since it is more performant than sklearn's SGD models in many aspects." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "9bb0708a-2e81-4040-816b-9dee68595d3f", "_uuid": "56b085b90c338a0e436544c2c5345d7a2716f612" }, "source": [ "## 2. Categorical feature processing\n", "\n", "### 2.1. Label Encoding\n", "Many classification and regression algorithms operate in Euclidean or metric space, implying that data is represented with vectors of real numbers. However, in real data, we often have categorical features with discrete values such as yes/no or January/February/.../December. We will see how to process this kind of data, particularly with linear models, and how to deal with many categorical features even when they have many unique values." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "44ebb1ca-8d55-47a1-bfa1-0c1bee8ce99f", "_uuid": "29058442a542088bb018bcf8158fcbbf4e79cef8" }, "source": [ "Let's explore the [UCI bank marketing dataset](https://archive.ics.uci.edu/ml/datasets/bank+marketing) where most of features are categorical." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "be6b51fd-ad36-4265-9086-fde116c6d5e4", "_uuid": "c8f015ed0ce62cdfc232529b9db5e17f1ebf55f5" }, "outputs": [], "source": [ "df = pd.read_csv(os.path.join(PATH_TO_ALL_DATA, \"bank_train.csv\"))\n", "labels = pd.read_csv(\n", " os.path.join(PATH_TO_ALL_DATA, \"bank_train_target.csv\"), header=None\n", ")\n", "\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "d81909b1-6b0f-47f5-9d10-f983fe1edcc7", "_uuid": "d900d6aa25e49a150388a9618b8f36bb76ac8667" }, "source": [ "We can see that most of features are not represented by numbers. This poses a problem because we cannot use most machine learning methods (at least those implemented in scikit-learn) out-of-the-box.\n", "\n", "Let's dive into the \"education\" feature." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "d5cb0f31-1e52-49a0-9bdb-ae3207541710", "_uuid": "136b05d444ff42d4e8521e51066bf9cd22c023fa" }, "outputs": [], "source": [ "df[\"education\"].value_counts().plot.barh();" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "ca94e540-92a0-41bb-a67b-906275c778e9", "_uuid": "284a387b80dba61981db40dabd3fc2f895616011" }, "source": [ "The most straightforward solution is to map each value of this feature into a unique number. For example, we can map `university.degree` to 0, `basic.9y` to 1, and so on. You can use `sklearn.preprocessing.LabelEncoder` to perform this mapping." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "fb569cfb-711b-428d-9a29-5393dff4b348", "_uuid": "05c9087139ca3fcdf3b715b9b30f566bdaf0ad1c" }, "outputs": [], "source": [ "label_encoder = LabelEncoder()" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "e75f24ed-b8ed-41dd-96c2-dcd1f42d7014", "_uuid": "276ccbe10a9744f1cca107fb5b7542a314b961fa" }, "source": [ "The `fit` method of this class finds all unique values and builds the actual mapping between categories and numbers, and the `transform` method converts the categories into numbers. After `fit` is executed, `label_encoder` will have the `classes_` attribute with all unique values of the feature. Let us count them to make sure the transformation was correct." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "c692cf31-3233-4b92-8bb9-de7d7be15315", "_uuid": "efe26525483e1c3ba137e8f1c55f92c76ab4c799" }, "outputs": [], "source": [ "mapped_education = pd.Series(label_encoder.fit_transform(df[\"education\"]))\n", "mapped_education.value_counts().plot.barh()\n", "print(dict(enumerate(label_encoder.classes_)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "4658ebf0-6610-4c6f-88d0-3b1027a5c212", "_uuid": "68fba174918a7c498100b8bb2c4f9822a4c9a659" }, "outputs": [], "source": [ "df[\"education\"] = mapped_education\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "ead4109a-0bc3-476c-be13-59c152e0cb1c", "_uuid": "4c02df6d2afbcd5a47d591004fe9a068e95ecb65" }, "source": [ "Let's apply the transformation to other columns of type `object`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "f6b6056e-3823-4caf-a617-d99ab490512d", "_uuid": "8079ecf58d4fa138d92c21f46b001cb3ed050a0a" }, "outputs": [], "source": [ "categorical_columns = df.columns[df.dtypes == \"object\"].union([\"education\"])\n", "for column in categorical_columns:\n", " df[column] = label_encoder.fit_transform(df[column])\n", "df.head()" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "a79eddaa-26d4-4316-a4d9-ce1a8f024e65", "_uuid": "89931fdf8b27f8e8ba8be53dc33368dc1dc3ad46" }, "source": [ "The main issue with this approach is that we have now introduced some relative ordering where it might not exist. \n", "\n", "For example, we implicitly introduced algebra over the values of the job feature where we can now substract the job of client #2 from the job of client #1 :" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "9e85d727-a23c-4fda-859e-9cfa2491b044", "_uuid": "10efbea02831df6e1e8476a8813aedd227f9d4ae" }, "outputs": [], "source": [ "df.loc[1].job - df.loc[2].job" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "16ea6d8f-8d03-427b-a9f8-f8827cb9b629", "_uuid": "f91a2a86a06fb9b36dd932d4afb08dc7c178983f" }, "source": [ "Does this operation make any sense? Not really. Let's try to train logisitic regression with this feature transformation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "7dede4d6-e787-4232-a1ac-01191a88ec88", "_uuid": "15c8fdb284d4e5166f3f56c4e9d8f1810186ff7c" }, "outputs": [], "source": [ "def logistic_regression_accuracy_on(dataframe, labels):\n", " features = dataframe.as_matrix()\n", " train_features, test_features, train_labels, test_labels = train_test_split(\n", " features, labels\n", " )\n", "\n", " logit = LogisticRegression()\n", " logit.fit(train_features, train_labels)\n", " return classification_report(test_labels, logit.predict(test_features))\n", "\n", "\n", "print(logistic_regression_accuracy_on(df[categorical_columns], labels))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "7ac2b754-b7e9-4bed-b90e-d27db1b72b01", "_uuid": "b2982316ff21f4585188cbb6987df0114cbe4b3f" }, "source": [ "We can see that logistic regression never predicts class 1. In order to use linear models with categorical features, we will use a different approach: One-Hot Encoding.\n", "\n", "### 2.2. One-Hot Encoding\n", "\n", "Suppose that some feature can have one of 10 unique values. One-hot encoding creates 10 new features corresponding to these unique values, all of them *except one* are zeros." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "df17447f-6ff8-4342-b755-c856fb1c7bd6", "_uuid": "6ca824f36f66c8e6889688e8f64c2ca6ec7605df" }, "outputs": [], "source": [ "one_hot_example = pd.DataFrame([{i: 0 for i in range(10)}])\n", "one_hot_example.loc[0, 6] = 1\n", "one_hot_example" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "f4c2d551-d511-4b6a-a161-e80b167b6607", "_uuid": "ea9c96c96b528b9fda95fb0ebc53089e05de3a58" }, "source": [ "This idea is implemented in the `OneHotEncoder` class from `sklearn.preprocessing`. By default `OneHotEncoder` transforms data into a sparse matrix to save memory space because most of the values are zeroes and because we do not want to take up more RAM. However, in this particular example, we do not encounter such problems, so we are going to use a \"dense\" matrix representation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "29d1f40e-cfb4-4ee0-b9ee-8c779b7c803b", "_uuid": "fa7ad1f51154182f467a5df5dd7d43ec111132b8" }, "outputs": [], "source": [ "onehot_encoder = OneHotEncoder(sparse=False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "0d70a254-f732-40c9-b738-67ca6b8d2d24", "_uuid": "ecfb22058b460d751779df0f9492928a317914de" }, "outputs": [], "source": [ "encoded_categorical_columns = pd.DataFrame(\n", " onehot_encoder.fit_transform(df[categorical_columns])\n", ")\n", "encoded_categorical_columns.head()" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "9db91f18-2a19-4c54-ae15-34cc7df16216", "_uuid": "0c162f2cc7d813cef43971aec666aaccc2aaa7b8" }, "source": [ "We have 53 columns that correspond to the number of unique values of categorical features in our data set. When transformed with One-Hot Encoding, this data can be used with linear models:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "84c611df-8c2e-45dc-a108-aab6bf39a530", "_uuid": "cebd716350bc29dabb07f797db16e693fa92a76a" }, "outputs": [], "source": [ "print(logistic_regression_accuracy_on(encoded_categorical_columns, labels))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "361416b2-4279-434a-98bf-82f79de11f3d", "_uuid": "e7976bb1de18e2f63e78c9e7ec72266ca158b9c1" }, "source": [ "### 2.3. Hashing trick\n", "Real data can be volatile, meaning we cannot guarantee that new values of categorical features will not occur. This issue hampers using a trained model on new data. Besides that, `LabelEncoder` requires preliminary analysis of the whole dataset and storage of constructed mappings in memory, which makes it difficult to work with large datasets.\n", "\n", "There is a simple approach to vectorization of categorical data based on hashing and is known as, not-so-surprisingly, the hashing trick. \n", "\n", "Hash functions can help us find unique codes for different feature values, for example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "d9eb2e54-18e7-4056-8f28-f22a044596d8", "_uuid": "01064911e1e0af0b3829b0e0be2a965aa3e8eb3e" }, "outputs": [], "source": [ "for s in (\"university.degree\", \"high.school\", \"illiterate\"):\n", " print(s, \"->\", hash(s))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "381e8137-cf66-418c-835a-84b5882cfdc2", "_uuid": "b93b5bcf1a9ad4a2dc92704bab63f831ea5e19bf" }, "source": [ "We will not use negative values or values of high magnitude, so we restrict the range of values for the hash function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "943fc564-80f0-4350-980a-cce6c6a2e7cd", "_uuid": "b92f7eabc498b8339abed0f8fd400bba5750209a" }, "outputs": [], "source": [ "hash_space = 25\n", "for s in (\"university.degree\", \"high.school\", \"illiterate\"):\n", " print(s, \"->\", hash(s) % hash_space)" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "ae21a334-e53f-4cb1-abfc-fa7ed35ba1ae", "_uuid": "6eda4bc3ccce5ca01700bc95878fc4996b7aabaa" }, "source": [ "Imagine that our data set contains a single (i.e. not married) student, who received a call on Monday. His feature vectors will be created similarly as in the case of One-Hot Encoding but in the space with fixed range for all features:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "c94253b2-3981-4bbd-817f-96c3f660d464", "_uuid": "af62a2ed3770a537bc3168d0a06c6d20b737f887" }, "outputs": [], "source": [ "hashing_example = pd.DataFrame([{i: 0.0 for i in range(hash_space)}])\n", "for s in (\"job=student\", \"marital=single\", \"day_of_week=mon\"):\n", " print(s, \"->\", hash(s) % hash_space)\n", " hashing_example.loc[0, hash(s) % hash_space] = 1\n", "hashing_example" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "4913a8ad-2ecc-4f50-b887-f19b51afdd01", "_uuid": "51d6391d6c180365161865070a0ebf589d2a344e" }, "source": [ "We want to point out that we hash not only feature values but also pairs of **feature name + feature value**. It is important to do this so that we can distinguish the same values of different features." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "48540748-405a-413d-ac0c-5aa0422b9087", "_uuid": "e025f8486b3091090e93c27c082145b5f3e11967" }, "outputs": [], "source": [ "assert hash(\"no\") == hash(\"no\")\n", "assert hash(\"housing=no\") != hash(\"loan=no\")" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "bfb6bdc6-9593-4a8f-a961-24221567c70f", "_uuid": "4ec7bcce511995a7d71a6542bbd71c9086f8f9e0" }, "source": [ "Is it possible to have a collision when using hash codes? Sure, it is possible, but it is a rare case with large enough hashing spaces. Even if collision occurs, regression or classification metrics will not suffer much. In this case, hash collisions work as a form of regularization.\n", "\n", "\n", "\n", "\n", "You may be saying \"WTF?\"; hashing seems counterintuitive. This is true, but these heuristics sometimes are, in fact, the only plausible approach to work with categorical data (what else can you do if you have 30M features?). Moreover, this technique has proven to just work. As you work more with data, you may see this for yourself.\n", "\n", "A good analysis of hash collisions, their dependency on feature space and hashing space dimensions and affecting classification/regression performance is done in [this article](https://booking.ai/dont-be-tricked-by-the-hashing-trick-192a6aae3087) by Booking.com. " ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "d2361062-61d9-4dd6-bac2-cbf2bd0ccebb", "_uuid": "1a565b5d7413123af2b5997cd9f74266187effca" }, "source": [ "## 3. Vowpal Wabbit" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "e6a2e0f9-785e-4cf6-9013-b114099daddd", "_uuid": "01e502198f14273eadcab0f10e090ddbaba07b87" }, "source": [ "[Vowpal Wabbit](https://github.com/JohnLangford/vowpal_wabbit) (VW) is one of the most widespread machine learning libraries used in industry. It is prominent for its training speed and support of many training modes, especially for online learning with big and high-dimentional data. This is one of the major merits of the library. Also, with the hashing trick implemented, Vowpal Wabbit is a perfect choice for working with text data.\n", "\n", "Shell is the main interface for VW." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "24fd028f-416e-43ff-9530-5c8f47bde176", "_uuid": "4cc17ec6551c7e7dcf224a3b03794720d90cb966" }, "outputs": [], "source": [ "!vw --help" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "62f9eb36-c321-43bb-823b-16e0dfa807fd", "_uuid": "e1af0fd07d8be18a75d911a2ca939b8af9839cf2" }, "source": [ "Vowpal Wabbit reads data from files or from standard input stream (stdin) with the following format:\n", "\n", "`[Label] [Importance] [Tag]|Namespace Features |Namespace Features ... |Namespace Features`\n", "\n", "`Namespace=String[:Value]`\n", "\n", "`Features=(String[:Value] )*`\n", "\n", "here [] denotes non-mandatory elements, and (...)\\* means multiple inputs allowed. \n", "\n", "- **Label** is a number. In the case of classification, it is usually 1 and -1; for regression, it is a real float value\n", "- **Importance** is a number. It denotes the sample weight during training. Setting this helps when working with imbalanced data.\n", "- **Tag** is a string without spaces. It is the \"name\" of the sample that VW saves upon prediction. In order to separate Tag from Importance, it is better to start Tag with the ' character.\n", "- **Namespace** is for creating different feature spaces. \n", "- **Features** are object features inside a given **Namespace**. Features have weight 1.0 by default, but it can be changed, for example feature:0.1. \n", "\n", "\n", "The following string matches the VW format:\n", "\n", "```\n", "1 1.0 |Subject WHAT car is this |Organization University of Maryland:0.5 College Park\n", "```\n", "\n", "\n", "Let's check the format by running VW with this training sample:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "5cbedd43-8d8e-4577-9a67-4f2879f0666c", "_uuid": "250fa571012a53fbe15f9b16bd88244dae4f805a" }, "outputs": [], "source": [ "! echo '1 1.0 |Subject WHAT car is this |Organization University of Maryland:0.5 College Park' | vw" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "250ad844-c8bc-4cc6-a1dd-cf4770d7c840", "_uuid": "1d754e1b0d24913b137f42b84ccdf9d46ce53f05" }, "source": [ "VW is a wonderful tool for working with text data. We'll illustrate it with the [20newsgroups dataset](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html), which contains letters from 20 different newsletters.\n", "\n", "\n", "### 3.1. News. Binary classification." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "a37611a4-5bdb-40bb-9b89-bfddd8726ba9", "_uuid": "0f527d54e1a759be5fb53665ae4b768116094b27" }, "outputs": [], "source": [ "# load data with sklearn's function\n", "newsgroups = fetch_20newsgroups(PATH_TO_ALL_DATA)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "7fad47bd-c5fc-4b56-b024-0e866137d07b", "_uuid": "a582c83f4d792d71d12e5063d7539c040b017a67" }, "outputs": [], "source": [ "newsgroups[\"target_names\"]" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "9eab187f-162a-4a1c-bcaa-6e96bbaeb807", "_uuid": "307c3d13c7525e41cba581816a9ef75660d54fb2" }, "source": [ "Lets look at the first document in this collection:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "d571d3d0-fba9-4d2f-a4a9-3a36e80fe456", "_uuid": "039c32b72a84277884c788de8fe2a5e692a4dfb5" }, "outputs": [], "source": [ "text = newsgroups[\"data\"][0]\n", "target = newsgroups[\"target_names\"][newsgroups[\"target\"][0]]\n", "\n", "print(\"-----\")\n", "print(target)\n", "print(\"-----\")\n", "print(text.strip())\n", "print(\"----\")" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "bb940e9e-e2bf-4f39-b8a2-467100548f40", "_uuid": "a464de9c01ff461f95ef1cba04acbe0211723c58" }, "source": [ "Now we convert the data into something Vowpal Wabbit can understand. We will throw away words shorter than 3 symbols. Here, we will skip some important NLP stages such as stemming and lemmatization; however, we will later see that VW solves the problem even without these steps." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "61c25a92-1b0a-45cf-904f-6c35de89575f", "_uuid": "9b480cff8801ad51f371b05f6f63225c758883ca" }, "outputs": [], "source": [ "def to_vw_format(document, label=None):\n", " return (\n", " str(label or \"\")\n", " + \" |text \"\n", " + \" \".join(re.findall(\"\\w{3,}\", document.lower()))\n", " + \"\\n\"\n", " )\n", "\n", "\n", "to_vw_format(text, 1 if target == \"rec.autos\" else -1)" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "a9ff9575-96b8-421c-9ebb-fe5de97b4d79", "_uuid": "0fada3ac4275dc108ea54a0be7efa8ab176ca06f" }, "source": [ "We split the dataset into train and test and write these into separate files. We will consider a document as positive if it corresponds to **rec.autos**. Thus, we are constructing a model which distinguishes articles about cars from other topics: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "297c4ed7-3157-412e-b3af-1bc59084defd", "_uuid": "f5754e324f2165a47ab603e2e5fafa5b681ea1e9" }, "outputs": [], "source": [ "all_documents = newsgroups[\"data\"]\n", "all_targets = [\n", " 1 if newsgroups[\"target_names\"][target] == \"rec.autos\" else -1\n", " for target in newsgroups[\"target\"]\n", "]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "d0cd644c-fdd2-4b46-9ff5-377ef12a3d6e", "_uuid": "623b5b239dda745dc0e79a7b225825eed8f98d09" }, "outputs": [], "source": [ "train_documents, test_documents, train_labels, test_labels = train_test_split(\n", " all_documents, all_targets, random_state=7\n", ")\n", "\n", "with open(os.path.join(PATH_TO_ALL_DATA, \"20news_train.vw\"), \"w\") as vw_train_data:\n", " for text, target in zip(train_documents, train_labels):\n", " vw_train_data.write(to_vw_format(text, target))\n", "with open(os.path.join(PATH_TO_ALL_DATA, \"20news_test.vw\"), \"w\") as vw_test_data:\n", " for text in test_documents:\n", " vw_test_data.write(to_vw_format(text))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "601ec250-c847-4c9e-8d47-ca00b8b659af", "_uuid": "6330fc49440e8801cbfee9aa075df523e845ae23" }, "source": [ "Now, we pass the created training file to Vowpal Wabbit. We solve the classification problem with a hinge loss function (linear SVM). The trained model will be saved in the `20news_model.vw` file:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "80f2960a-2389-4810-9b04-1928b613b4b2", "_uuid": "7a5a15cc11e801a98b493bab026136c9eeb33816" }, "outputs": [], "source": [ "!vw -d $PATH_TO_ALL_DATA/20news_train.vw \\\n", " --loss_function hinge -f $PATH_TO_ALL_DATA/20news_model.vw" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "8d4e9c7a-c55b-4e18-a26a-d9b63db8ad47", "_uuid": "efc30d9b5fa31f0e39eb486e85f6775ac52cb229" }, "source": [ "VW prints a lot of interesting info while training (one can suppress it with the `--quiet` parameter). You can see documentation of the diagnostic output on [GitHub](https://github.com/JohnLangford/vowpal_wabbit/wiki/Tutorial#vws-diagnostic-information). Note how average loss drops while training. For loss computation, VW uses samples it has never seen before, so this measure is usually accurate. Now, we apply our trained model to the test set, saving predictions into a file with the `-p` flag: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "17c99751-4e30-4251-b18f-fe6ed8a34e58", "_uuid": "276f1431b121543e67f668bb5e9d601dd882e98e" }, "outputs": [], "source": [ "!vw -i $PATH_TO_ALL_DATA/20news_model.vw -t -d $PATH_TO_ALL_DATA/20news_test.vw \\\n", "-p $PATH_TO_ALL_DATA/20news_test_predictions.txt" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "b3c2b322-058b-4051-a29e-961e9691947f", "_uuid": "e478d52c8fd3c52b8a46d6e1dd5ebccfd691748e" }, "source": [ "Now we load our predictions, compute AUC, and plot the ROC curve:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "93d9f296-f06b-4d18-94a5-e18ccf88b094", "_uuid": "40b4112f1afa764db10b58b0ab05adfed48ab388" }, "outputs": [], "source": [ "with open(os.path.join(PATH_TO_ALL_DATA, \"20news_test_predictions.txt\")) as pred_file:\n", " test_prediction = [float(label) for label in pred_file.readlines()]\n", "\n", "auc = roc_auc_score(test_labels, test_prediction)\n", "roc_curve = roc_curve(test_labels, test_prediction)\n", "\n", "with plt.xkcd():\n", " plt.plot(roc_curve[0], roc_curve[1])\n", " plt.plot([0, 1], [0, 1])\n", " plt.xlabel(\"FPR\")\n", " plt.ylabel(\"TPR\")\n", " plt.title(\"test AUC = %f\" % (auc))\n", " plt.axis([-0.05, 1.05, -0.05, 1.05]);" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "a302f698-1f6f-4653-a1a1-ef467919ca1e", "_uuid": "5aa3b9722f255cb9db25c8fe5991c1e2c7a17f71" }, "source": [ "The AUC value we get shows that we have achieved high classification quality." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "6cc41756-d83c-48a5-93f6-56c238487b51", "_uuid": "47ea9632a74d49a003c1d876661af0113efd6bd4" }, "source": [ "### 3.2. News. Multiclass classification" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "ad900d77-3eb6-413b-ba95-7d33d036e655", "_uuid": "2fd54a3102db4cf3d3665877acffb3cead417a2f" }, "source": [ "We will use the same news dataset, but, this time, we will solve a multiclass classification problem. `Vowpal Wabbit` is a little picky – it wants labels starting from 1 till K, where K – is the number of classes in the classification task (20 in our case). So we will use LabelEncoder and add 1 afterwards (recall that `LabelEncoder` maps labels into range from 0 to K-1)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "e94dfe85-61d6-42d2-b19e-89923b511535", "_uuid": "30fca7585b9d841b5925ec9b3db9b12ff1bb5142" }, "outputs": [], "source": [ "all_documents = newsgroups[\"data\"]\n", "topic_encoder = LabelEncoder()\n", "all_targets_mult = topic_encoder.fit_transform(newsgroups[\"target\"]) + 1" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "0d4b5845-3bc5-4c2d-ba00-5977b5f108cc", "_uuid": "93289fedab1875334df6632138311299dfe7dc4d" }, "source": [ "**The data is the same, but we have changed the labels, train_labels_mult and test_labels_mult, into label vectors from 1 to 20.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "90e22502-efe9-4a2c-9868-fa6a18ed91b2", "_uuid": "f90ea2c247690e680d26f6d30992daf45ffd0315" }, "outputs": [], "source": [ "train_documents, test_documents, train_labels_mult, test_labels_mult = train_test_split(\n", " all_documents, all_targets_mult, random_state=7\n", ")\n", "\n", "with open(os.path.join(PATH_TO_ALL_DATA, \"20news_train_mult.vw\"), \"w\") as vw_train_data:\n", " for text, target in zip(train_documents, train_labels_mult):\n", " vw_train_data.write(to_vw_format(text, target))\n", "with open(os.path.join(PATH_TO_ALL_DATA, \"20news_test_mult.vw\"), \"w\") as vw_test_data:\n", " for text in test_documents:\n", " vw_test_data.write(to_vw_format(text))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "478ead84-c063-4383-baac-7deaa627d83f", "_uuid": "c0f488bb8182487c1393e5b9f0fdbc301de58a02" }, "source": [ "We train Vowpal Wabbit in multiclass classification mode, passing the `oaa` parameter(\"one against all\") with the number of classes. Also, let's see what parameters our model quality is dependent on (more info can be found in the [official Vowpal Wabbit tutorial](https://github.com/JohnLangford/vowpal_wabbit/wiki/Tutorial)):\n", " - learning rate (-l, 0.5 default) – rate of weight change on every step\n", " - learning rate decay (--power_t, 0.5 default) – it is proven in practice, that, if the learning rate drops with the number of steps in stochastic gradient descent, we approach the minimum loss better\n", " - loss function (--loss_function) – the entire training algorithm depends on it. See [docs](https://github.com/JohnLangford/vowpal_wabbit/wiki/Loss-functions) for loss functions\n", " - Regularization (-l1) – note that VW calculates regularization for every object. That is why we usually set regularization values to about $10^{-20}.$\n", " \n", "Additionally, we can try automatic Vowpal Wabbit parameter tuning with [Hyperopt](https://github.com/hyperopt/hyperopt)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "80ae364e-8332-41db-bdc3-7f642bb24d7a", "_uuid": "97ea9ebcb6ed46b5512f5a9364680e501c2925cf" }, "outputs": [], "source": [ "%%time\n", "!vw --oaa 20 $PATH_TO_ALL_DATA/20news_train_mult.vw -f $PATH_TO_ALL_DATA/20news_model_mult.vw \\\n", "--loss_function=hinge" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "4d78df8b-f6d2-477a-b5be-a5f7364c0e56", "_uuid": "d30d194b2be9521d609d703385f528c24a557aa0" }, "outputs": [], "source": [ "%%time\n", "!vw -i $PATH_TO_ALL_DATA/20news_model_mult.vw -t -d $PATH_TO_ALL_DATA/20news_test_mult.vw \\\n", "-p $PATH_TO_ALL_DATA/20news_test_predictions_mult.txt" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "bf4c66cf-3039-4ac4-a129-e52652c16d8d", "_uuid": "f6911717662ade8c466cc2f3681f356619d8676c" }, "outputs": [], "source": [ "with open(\n", " os.path.join(PATH_TO_ALL_DATA, \"20news_test_predictions_mult.txt\")\n", ") as pred_file:\n", " test_prediction_mult = [float(label) for label in pred_file.readlines()]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "c8cd9521-6c23-412b-959d-19e9f95bd5ee", "_uuid": "c110cfb692d0c280009ca815efa504f5889e28a6" }, "outputs": [], "source": [ "accuracy_score(test_labels_mult, test_prediction_mult)" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "365da3c4-6bcb-40fa-8786-d57415595491", "_uuid": "ab8ac32cc2357207807e8c262177e0347e9f6d71" }, "source": [ "Here is how often the model misclassifies atheism with other topics:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "5b40bd39-4895-4713-be3a-2fea6fa37062", "_uuid": "fefe7d01f98e8cd3af7ce5a3b7d0f859755e5047" }, "outputs": [], "source": [ "M = confusion_matrix(test_labels_mult, test_prediction_mult)\n", "for i in np.where(M[0, :] > 0)[0][1:]:\n", " print(newsgroups[\"target_names\"][i], M[0, i])" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "cab1c6f7-515d-4bf3-9054-5bc25d81be8e", "_uuid": "dc891b0f4124cdc76a2f9db9340d49055a91e1f8" }, "source": [ "### 3.3. IMDB movie reviews\n", "In this part we will do binary classification of [IMDB](http://www.imdb.com) (International Movie DataBase) movie reviews. We will see how fast Vowpal Wabbit performs.\n", "\n", "Using the `load_files` function from `sklearn.datasets`, we load the movie reviews datasets. It's the same dataset we used in topic04 part4 notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "a1827aa1-5bc7-4838-bb01-68792de451b6", "_uuid": "e719b5b6c976cf9daf10a9f3b7c35b4cde79b057" }, "outputs": [], "source": [ "import tarfile\n", "# Download the dataset if not already in place\n", "from io import BytesIO\n", "\n", "import requests\n", "\n", "url = \"http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\"\n", "\n", "\n", "def load_imdb_dataset(extract_path=\"../../data\", overwrite=False):\n", " # check if existed already\n", " if (\n", " os.path.isfile(os.path.join(extract_path, \"aclImdb\", \"README\"))\n", " and not overwrite\n", " ):\n", " print(\"IMDB dataset is already in place.\")\n", " return\n", "\n", " print(\"Downloading the dataset from: \", url)\n", " response = requests.get(url)\n", "\n", " tar = tarfile.open(mode=\"r:gz\", fileobj=BytesIO(response.content))\n", "\n", " data = tar.extractall(extract_path)\n", "\n", "\n", "load_imdb_dataset()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read train data, separate labels." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "PATH_TO_IMDB = \"../../data/aclImdb\"\n", "\n", "reviews_train = load_files(\n", " os.path.join(PATH_TO_IMDB, \"train\"), categories=[\"pos\", \"neg\"]\n", ")\n", "\n", "text_train, y_train = reviews_train.data, reviews_train.target" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "db550541-630a-47a5-8b98-246d94a3fb33", "_uuid": "593032d9be6e7aff583e0c7ba40e3e801b136edf" }, "outputs": [], "source": [ "print(\"Number of documents in training data: %d\" % len(text_train))\n", "print(np.bincount(y_train))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "50ea99f8-6680-4a77-b3fb-a9fb18fd11b3", "_uuid": "6cd9d12d23bec99ee3df859934378ed1a911be22" }, "source": [ "Do the same for the test set." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "ce60fd02-e5d4-40aa-a5db-33556ef7063f", "_uuid": "8fea469dd838a26671f234d54cf82d6f57188e73" }, "outputs": [], "source": [ "reviews_test = load_files(os.path.join(PATH_TO_IMDB, \"test\"), categories=[\"pos\", \"neg\"])\n", "text_test, y_test = reviews_test.data, reviews_test.target" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Number of documents in test data: %d\" % len(text_test))\n", "print(np.bincount(y_test))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "a7f87c80-8d74-47f1-9d47-cd31542da37d", "_uuid": "d37600cecaa2fd716479ed286ca9985380722c40" }, "source": [ "Take a look at examples of reviews and their corresponding labels." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "213017e1-25f0-4d08-8d9c-5341b449b8f6", "_uuid": "aea5acfcef80c4006dbcab233d237d2cd091ab48" }, "outputs": [], "source": [ "text_train[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "23c8ca4d-7287-406a-8381-f9c9c095f1b7", "_uuid": "976c29d60e5fc1da27e36b5c34dd1fa4185cd083" }, "outputs": [], "source": [ "y_train[0] # good review" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "b4cd5590-5952-4388-9960-37702e78be4f", "_uuid": "2fe24a84eb18599fb67664a63e3b2178ee29ee26" }, "outputs": [], "source": [ "text_train[1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "0faa88f7-c96d-4073-9b16-b6d68d31d354", "_uuid": "f64122c2e93648b75494df26b1de4bf01358df35" }, "outputs": [], "source": [ "y_train[1] # bad review" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "23032bfe-25d1-4f79-b24e-a4cb69f44127", "_uuid": "0ce9e75db41712f6f9161f9d6cd8000381a5b3ba" }, "outputs": [], "source": [ "to_vw_format(str(text_train[1]), 1 if y_train[0] == 1 else -1)" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "886409fe-bdbf-4e09-9091-1912143715b9", "_uuid": "844598ae3aa0064ecfb4cb778df0c555a6b91403" }, "source": [ "Now, we prepare training (`movie_reviews_train.vw`), validation (`movie_reviews_valid.vw`), and test (`movie_reviews_test.vw`) sets for Vowpal Wabbit. We will use 70% for training, 30% for the hold-out set." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "c08edd2b-7290-4e70-9072-895e33923d44", "_uuid": "7309769413ef059831390aea012334a5d7482817" }, "outputs": [], "source": [ "train_share = int(0.7 * len(text_train))\n", "train, valid = text_train[:train_share], text_train[train_share:]\n", "train_labels, valid_labels = y_train[:train_share], y_train[train_share:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "a30cddd4-fceb-46ca-87a8-1b7b7d3b36d1", "_uuid": "9154377a268f463e98c17432a84a77d03e68052e" }, "outputs": [], "source": [ "len(train_labels), len(valid_labels)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "6d25382f-b135-47f8-a82c-2568ad02f9ff", "_uuid": "cce438177377598771a890dc94651de5a6a8495e" }, "outputs": [], "source": [ "with open(\n", " os.path.join(PATH_TO_ALL_DATA, \"movie_reviews_train.vw\"), \"w\"\n", ") as vw_train_data:\n", " for text, target in zip(train, train_labels):\n", " vw_train_data.write(to_vw_format(str(text), 1 if target == 1 else -1))\n", "with open(\n", " os.path.join(PATH_TO_ALL_DATA, \"movie_reviews_valid.vw\"), \"w\"\n", ") as vw_train_data:\n", " for text, target in zip(valid, valid_labels):\n", " vw_train_data.write(to_vw_format(str(text), 1 if target == 1 else -1))\n", "with open(os.path.join(PATH_TO_ALL_DATA, \"movie_reviews_test.vw\"), \"w\") as vw_test_data:\n", " for text in text_test:\n", " vw_test_data.write(to_vw_format(str(text)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "cb999742-8ad7-428d-8f66-f015d38de4f8", "_uuid": "8d87247a0d044e81b545e37ffaa59a96712a252f" }, "outputs": [], "source": [ "!head -2 $PATH_TO_ALL_DATA/movie_reviews_train.vw" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "f25cd0d3-1767-41f1-b7bf-096224619bc5", "_uuid": "b63440f7ffebc472ecbe54d8e3aef8c3a3b75fa1" }, "outputs": [], "source": [ "!head -2 $PATH_TO_ALL_DATA/movie_reviews_valid.vw" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "eaa1a658-e6e0-42f1-9c30-14be762fc7d9", "_uuid": "fd4e364bad19a64110f7ec839a56a2776222306c" }, "outputs": [], "source": [ "!head -2 $PATH_TO_ALL_DATA/movie_reviews_test.vw" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "0cedab5e-5896-4439-beeb-96b268382587", "_uuid": "6403759f3d06322ee2b8e4017f181bc9681661ea" }, "source": [ "**Now we launch Vowpal Wabbit with the following arguments:**\n", "\n", " - `-d`, path to training set (corresponding .vw file)\n", " - `--loss_function` – hinge (feel free to experiment here)\n", " - `-f` – path to the output file (which can also be in the .vw format)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "89094f9e-7453-4137-87b0-21df78627ae6", "_uuid": "4e27dea292bfde2224e802d60c00aad0fbac3274" }, "outputs": [], "source": [ "!vw -d $PATH_TO_ALL_DATA/movie_reviews_train.vw --loss_function hinge \\\n", "-f $PATH_TO_ALL_DATA/movie_reviews_model.vw --quiet" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "7653ab5e-de84-47c0-9981-80fbd6a04783", "_uuid": "66ccbe8a95fea95703c28f21af5f6b9a3dcd87f6" }, "source": [ "Next, make the hold-out prediction with the following VW arguments:\n", " - `-i` –path to the trained model (.vw file)\n", " - `-d` – path to the hold-out set (.vw file) \n", " - `-p` – path to a txt-file where the predictions will be stored\n", " - `-t` - tells VW to ignore labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "7fbac967-4a81-4eff-9d31-721a197ed568", "_uuid": "c8ae7e58aeacc3e88910b62aff684ab12fb970e1" }, "outputs": [], "source": [ "!vw -i $PATH_TO_ALL_DATA/movie_reviews_model.vw -t \\\n", "-d $PATH_TO_ALL_DATA/movie_reviews_valid.vw -p $PATH_TO_ALL_DATA/movie_valid_pred.txt --quiet" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "5fa99f83-de1f-42d7-97ba-52da84c086f8", "_uuid": "9664438878f6d1c633bc67ee13266b929bab7dd0" }, "source": [ "Read the predictions from the text file and estimate the accuracy and ROC AUC. Note that VW prints probability estimates of the +1 class. These estimates are distributed from -1 to 1, so we can convert these into binary answers, assuming that positive values belong to class 1." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "609497c1-de20-436d-9910-018316f36e8e", "_uuid": "8cce125db3a615ff84b0892819f1b5f7c680a3e2" }, "outputs": [], "source": [ "with open(os.path.join(PATH_TO_ALL_DATA, \"movie_valid_pred.txt\")) as pred_file:\n", " valid_prediction = [float(label) for label in pred_file.readlines()]\n", "print(\n", " \"Accuracy: {}\".format(\n", " round(\n", " accuracy_score(\n", " valid_labels, [int(pred_prob > 0) for pred_prob in valid_prediction]\n", " ),\n", " 3,\n", " )\n", " )\n", ")\n", "print(\"AUC: {}\".format(round(roc_auc_score(valid_labels, valid_prediction), 3)))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "699aac8c-8b17-4df1-9258-45f997ae0f79", "_uuid": "d19e8357504987994c53d41ea373891aab41afa6" }, "source": [ "Again, do the same for the test set." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "aaa8c5c7-aa05-4cdd-a06e-bf7325972691", "_uuid": "36f5d2d1336d537c95947e884207ecffe18e2d91" }, "outputs": [], "source": [ "!vw -i $PATH_TO_ALL_DATA/movie_reviews_model.vw -t \\\n", "-d $PATH_TO_ALL_DATA/movie_reviews_test.vw \\\n", "-p $PATH_TO_ALL_DATA/movie_test_pred.txt --quiet" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "7a61e739-89f4-44d1-a290-9ad2be4bdffd", "_uuid": "b3cf5f3efa4dbaf05baff4f4900c61665f2d9fee" }, "outputs": [], "source": [ "with open(os.path.join(PATH_TO_ALL_DATA, \"movie_test_pred.txt\")) as pred_file:\n", " test_prediction = [float(label) for label in pred_file.readlines()]\n", "print(\n", " \"Accuracy: {}\".format(\n", " round(\n", " accuracy_score(\n", " y_test, [int(pred_prob > 0) for pred_prob in test_prediction]\n", " ),\n", " 3,\n", " )\n", " )\n", ")\n", "print(\"AUC: {}\".format(round(roc_auc_score(y_test, test_prediction), 3)))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "b5ecbd7f-1bf9-496a-a35f-f82a1ea2db10", "_uuid": "45c4a3badafdf39fc53a6bbc32d2c43b15b88c98" }, "source": [ "Let's try to achieve a higher accuracy by incorporating bigrams." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "c5b25dce-c730-4031-8938-1b9fa64575b6", "_uuid": "98fbb3a6f858b362aef8f797469075eec9072aaf" }, "outputs": [], "source": [ "!vw -d $PATH_TO_ALL_DATA/movie_reviews_train.vw \\\n", "--loss_function hinge --ngram 2 -f $PATH_TO_ALL_DATA/movie_reviews_model2.vw --quiet" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "17ceb519-ab1f-4184-b9c2-9eb925b32ea8", "_uuid": "48aa4c0a6c58be2781ed607a2393de37083345ae" }, "outputs": [], "source": [ "!vw -i$PATH_TO_ALL_DATA/movie_reviews_model2.vw -t -d $PATH_TO_ALL_DATA/movie_reviews_valid.vw \\\n", "-p $PATH_TO_ALL_DATA/movie_valid_pred2.txt --quiet" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "d1c01554-e2b6-4a55-97b9-0d17c8b26686", "_uuid": "be78a33c70c03e1bc9a48a25e804248930fba2c2" }, "outputs": [], "source": [ "with open(os.path.join(PATH_TO_ALL_DATA, \"movie_valid_pred2.txt\")) as pred_file:\n", " valid_prediction = [float(label) for label in pred_file.readlines()]\n", "print(\n", " \"Accuracy: {}\".format(\n", " round(\n", " accuracy_score(\n", " valid_labels, [int(pred_prob > 0) for pred_prob in valid_prediction]\n", " ),\n", " 3,\n", " )\n", " )\n", ")\n", "print(\"AUC: {}\".format(round(roc_auc_score(valid_labels, valid_prediction), 3)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "3015a9e6-f814-4beb-9d37-f8c6a2e2c546", "_uuid": "f1aa2121a7ee92577ad4058b0688f8290d24e1d5" }, "outputs": [], "source": [ "!vw -i $PATH_TO_ALL_DATA/movie_reviews_model2.vw -t -d $PATH_TO_ALL_DATA/movie_reviews_test.vw \\\n", "-p $PATH_TO_ALL_DATA/movie_test_pred2.txt --quiet" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "_cell_guid": "527e0327-b208-47a0-9853-2e1bd06beb38", "_uuid": "22b7b6feb376fcbd44faf942914afaade9368b30" }, "outputs": [], "source": [ "with open(os.path.join(PATH_TO_ALL_DATA, \"movie_test_pred2.txt\")) as pred_file:\n", " test_prediction2 = [float(label) for label in pred_file.readlines()]\n", "print(\n", " \"Accuracy: {}\".format(\n", " round(\n", " accuracy_score(\n", " y_test, [int(pred_prob > 0) for pred_prob in test_prediction2]\n", " ),\n", " 3,\n", " )\n", " )\n", ")\n", "print(\"AUC: {}\".format(round(roc_auc_score(y_test, test_prediction2), 3)))" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "a8c85011-e7d2-42c5-8294-34177d6de387", "_uuid": "63990db5f343a0e9f44c0069091a66d9f35b954b" }, "source": [ "Adding bigrams really helped to improve our model!" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "22c8f4bc-07db-44ab-aed5-cab6db73689d", "_uuid": "b6c7d300b2f4c9d50358345c5145780f201745ea" }, "source": [ "### 3.4. Classifying gigabytes of StackOverflow questions" ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "f3e9b72a-cc49-49c4-b663-b7df4632cf69", "_uuid": "a84523499443d63d08abe83c7a6ebe5bd7c63bf2" }, "source": [ "This section has been moved to Kaggle, please explore [this Kernel](https://www.kaggle.com/kashnitsky/topic-8-online-learning-and-vowpal-wabbit)." ] }, { "cell_type": "markdown", "metadata": { "_cell_guid": "91cbf31e-43a1-482d-af7a-02de3826b00f", "_uuid": "bf8903c882ff92061cb8ad971f097734254ed866" }, "source": [ "## 4. Demo assignment\n", "To better understand stochastic learning, you can complete [this assignment](https://www.kaggle.com/kashnitsky/assignment-8-implementing-online-regressor) where you'll be asked to implement a stochastic gradient regressor from scratch. The assignment is just for you to practice, and goes with a [solution](https://www.kaggle.com/kashnitsky/a8-demo-implementing-online-regressor-solution).\n", "\n", "## 5. Useful resources\n", "- The same notebook as am interactive web-based [Kaggle Kernel](https://www.kaggle.com/kashnitsky/topic-8-online-learning-and-vowpal-wabbit)\n", "- [\"Training while reading\"](https://www.kaggle.com/kashnitsky/training-while-reading-vowpal-wabbit-starter) - an example of the Python wrapper usage\n", "- Main course [site](https://mlcourse.ai), [course repo](https://github.com/Yorko/mlcourse.ai), and YouTube [channel](https://www.youtube.com/watch?v=QKTuw4PNOsU&list=PLVlY_7IJCMJeRfZ68eVfEcu-UcN9BbwiX)\n", "- Course materials as a [Kaggle Dataset](https://www.kaggle.com/kashnitsky/mlcourse)\n", "- Official VW [documentation](https://github.com/JohnLangford/vowpal_wabbit/wiki) on Github\n", "- [\"Awesome Vowpal Wabbit\"](https://github.com/VowpalWabbit/vowpal_wabbit/wiki/Awesome-Vowpal-Wabbit) Wiki\n", "- [Don’t be tricked by the Hashing Trick](https://booking.ai/dont-be-tricked-by-the-hashing-trick-192a6aae3087) - analysis of hash collisions, their dependency on feature space and hashing space dimensions and affecting classification/regression performance\n", "- [\"Numeric Computation\" Chapter](http://www.deeplearningbook.org/contents/numerical.html) of the [Deep Learning book](http://www.deeplearningbook.org/)\n", "- [\"Convex Optimization\" by Stephen Boyd](https://www.amazon.com/Convex-Optimization-Stephen-Boyd/dp/0521833787)\n", "- \"Command-line Tools can be 235x Faster than your Hadoop Cluster\" [post](https://aadrake.com/command-line-tools-can-be-235x-faster-than-your-hadoop-cluster.html)\n", "- Benchmarking various ML algorithms on Criteo 1TB dataset on [GitHub](https://github.com/rambler-digital-solutions/criteo-1tb-benchmark)\n", "- [VW on FastML.com](http://fastml.com/blog/categories/vw/)" ] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 1 }