{"@attributes":{"version":"2.0"},"channel":{"title":"Frank Fineis","description":"Data Science blogging. Statistics. Data Engineering. Consulting.\n","link":"https:\/\/ffineis.github.io\/","pubDate":"Sun, 02 May 2021 17:07:03 +0000","lastBuildDate":"Sun, 02 May 2021 17:07:03 +0000","generator":"Jekyll v3.9.0","item":[{"title":"The inner workings of the lambdarank objective in LightGBM","description":"<h1 id=\"the-ranking-objective\">The ranking objective<\/h1>\n\n<p>The ability to sort-order items in a list in an optimal way, often referred to as <em>learning to rank<\/em> (or LETOR), is sort of the forgotten middle child supervised machine learning. It\u2019s not directly regression, but some LETOR solutions can involve regression. It\u2019s not exactly binary classification, but several popular LETOR models are closely related to binary classification. Some LETOR models involve assigning probabilities to ranking permutations. And then the metrics for evaluating \u201cwell-ranked\u201d like <a href=\"https:\/\/en.wikipedia.org\/wiki\/Discounted_cumulative_gain\">NDCG<\/a> and <a href=\"http:\/\/citeseerx.ist.psu.edu\/viewdoc\/download?doi=10.1.1.157.4509&amp;rep=rep1&amp;type=pdf\">ERR<\/a> are much more involved than the standard precision, recall, or RMSE just don\u2019t cut it.<\/p>\n\n<p>When I first got involved with LETOR models, I found a lot of the literature to be kind of chaotic. Specifically, the foundational writings on LETOR by Burges<a href=\"4\">[4]<\/a> I found very difficult to follow just from a notational standpoint. I knew that <a href=\"https:\/\/github.com\/microsoft\/LightGBM\">LightGBM<\/a> supported the <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> objective, but it took time to fully grasp the connection between papers about pairwise loss, lambdarank gradients, and LightGBM\u2019s actual LambdaMART implementation in C++. So in this post I\u2019ll try to cover the core principals of what the <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> objective is, and then I\u2019ll dive into exactly what\u2019s going on in the <code class=\"language-plaintext highlighter-rouge\">LambdarankNDCG<\/code> optimization function used by LightGBM to estimate LamdbaMART models.<\/p>\n\n<p>Eventually we\u2019ll be getting into the LightGBM C++ source code available on GitHub <a href=\"https:\/\/github.com\/microsoft\/LightGBM\/tree\/master\/src\">here<\/a>.<\/p>\n\n<h2 id=\"why-learning-to-rank-is-hard\">Why learning to rank is hard<\/h2>\n<p>The number one reason why LETOR is harder than the more traditional supervised learning tasks is that the data is hierarchical. In continuous regression or binary\/multiclass\/multilabel classification, we map one input vector to one output vector. Each input is typically assumed to be distributed $IID$. When we rank items within a list, our units of measure (items) are not independent of each other, but instead are differentially ranked <em>relative<\/em> to each other. It\u2019s not even that the ranking models needs to output probabilities or estimates of some conditional mean $E[Y|X]$ - it only needs to output values that allow us to sort items within a list in an optimal order. A model that outputs the scores ${-\\infty, 0, \\infty}$ for three items (respectively) would provide the exact same ranking as a model that outputs scores ${-0.01, -0.005, -0.001}$ for each of those same products.<\/p>\n\n<p>LETOR training data is often stored in the SVMlight format, which comes from T. Joachim\u2019s SVMRank model and corresponding ML software written in C <a href=\"#1\">[1]<\/a>. The SVMLight format basically reserves the first column for the dependent variable, the second column for what it calls the <code class=\"language-plaintext highlighter-rouge\">qid<\/code>, or the group identifier, and then all other columns are reserved for feature values. So LETOR shares a similar data structure really to how we would need to shape data as input into RNN\/LSTM models: (samples, time steps, $y$). One sample is comprised of multiple products within a single query, like this:<\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th>Y<\/th>\n      <th>qid<\/th>\n      <th>feature_0<\/th>\n      <th>feature_1<\/th>\n      <th>feature_2<\/th>\n      <th>feature_3<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>0<\/td>\n      <td>0<\/td>\n      <td>12.2<\/td>\n      <td>-0.9<\/td>\n      <td>0.23<\/td>\n      <td>103.0<\/td>\n    <\/tr>\n    <tr>\n      <td>1<\/td>\n      <td>0<\/td>\n      <td>13.0<\/td>\n      <td>1.29<\/td>\n      <td>0.98<\/td>\n      <td>93.5<\/td>\n    <\/tr>\n    <tr>\n      <td>2<\/td>\n      <td>0<\/td>\n      <td>14.0<\/td>\n      <td>1.29<\/td>\n      <td>0.98<\/td>\n      <td>93.5<\/td>\n    <\/tr>\n    <tr>\n      <td>0<\/td>\n      <td>0<\/td>\n      <td>11.9<\/td>\n      <td>1<\/td>\n      <td>0.94<\/td>\n      <td>90.2<\/td>\n    <\/tr>\n    <tr>\n      <td>1<\/td>\n      <td>1<\/td>\n      <td>10.0<\/td>\n      <td>0.44<\/td>\n      <td>0.99<\/td>\n      <td>140.51<\/td>\n    <\/tr>\n    <tr>\n      <td>0<\/td>\n      <td>1<\/td>\n      <td>10.1<\/td>\n      <td>0.44<\/td>\n      <td>0.98<\/td>\n      <td>160.88<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<h2 id=\"pairwise-loss-starts-with-binary-classification\">Pairwise loss starts with binary classification<\/h2>\n<p>The <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> LightGBM objective is at its core just a manipulation of the standard binary classification objective, so I\u2019m going to begin with a quick refresher on classification here.<\/p>\n\n<p>Start by considering two items within a query result set, call them items $i$ and $j$. Assume that $Y_{i} &gt; Y_{j}$, i.e. that item $i$ is more relevant than item $j$. Suppose that these items can also be represented by feature vectors $X_{i}$ and $X_{j}$, respectively. A model, referred to as $f(\\cdot)$, minimizes pairwise classification loss by minimizing the number of pairwise inconsistencies. When $Y_{i} &gt; Y_{j}$, a good model will provide us output values $s_{i}, s_{j}$ such that $s_{i} = f(X_{i}) &gt; f(X_{j}) = s_{j}$.<\/p>\n\n<p>Then logically, pairwise loss should be large when $s_{i} - s_{j} &lt; 0$ and small when $s_{i} - s_{j} &gt; 0$. We can use this difference to model the probability in a binary classification model that the pair $(i, j)$ as \u201c$Y=1$\u201d or $(j, i)$ as \u201c$Y=0$\u201d. This classification model will maximize the Bernoulli likelihood, $\\mathcal{L}$, given the data consisting of all pairs $(i, j)$ where $Y_{i} &gt; Y_{j}$. The Bernoulli likelihood parameterized by $\\theta = Pr(y|x)$, is expressed as<\/p>\n\n<p>\\begin{align}\n\\mathcal{L} = \\theta^{y}(1 -\\theta)^{1-y}, \\hspace{5mm} y \\in {0, 1}\n\\end{align}<\/p>\n\n<p>Since $\\log(\\cdot)$ is a monotone transformation - a fancy way of saing that $5 &lt; 6 \\rightarrow \\log(5) &lt; \\log(6)$ - then maximizing Bernoulli likelihood and log-likelihood is the same thing. Log-likelihood, or $\\ell\\ell$ is given by<\/p>\n\n<p>\\begin{align}\n\\ell\\ell = \\log(\\mathcal{L}) = y\\log(\\theta) + (1-y)\\log(1 - \\theta)\n\\end{align}<\/p>\n\n<p>We typically express $Pr(y_{ij}|s_{i}, s_{j})$ via the logistic function: $Pr(y_{ij}|s_{i}, s_{j}) = \\frac{1}{1 + e^{-\\sigma(s_{i} - s_{j})}}$ because it\u2019s easy to differentiate and it gives us a way to smush pairwise model scores $s_{i}-s_{j}$ from $(-\\infty, \\infty)$ to the probability scale [0, 1]. The constant $\\sigma$ it typical to set $\\sigma=1$, but LightGBM exposes this as a hyperparameter named <code class=\"language-plaintext highlighter-rouge\">sigmoid<\/code>, so I\u2019ll keep it in the notation.<\/p>\n\n<p>\\begin{align}\n\\ell\\ell_{ij} &amp;= y_{ij}\\log(\\frac{1}{1 + e^{-\\sigma (s_{i} - s_{j})}}) + (1 - y_{ij})\\log(\\frac{e^{-\\sigma(s_{i} - s_{j})}}{1 + e^{-\\sigma(s_{i} - s_{j})}})\n\\end{align}\n\\begin{align}\n&amp;= -y_{ij}\\log(1 + e^{-\\sigma (s_{i} - s_{j})}) + \\log(e^{-\\sigma (s_{i} - s_{j})}) - \\log(1 + e^{-\\sigma (s_{i} - s_{j})}) - y_{ij}\\log(e^{-\\sigma (s_{i} - s_{j})}) + y_{ij}\\log(1 + e^{-\\sigma (s_{i} - s_{j})})\n\\end{align}\n\\begin{align}\n&amp;= (1 - y_{ij})\\log(e^{-\\sigma (s_{i} - s_{j})}) - y_{ij}\\log(1 + e^{-\\sigma (s_{i} - s_{j})})\n\\end{align}<\/p>\n\n<p>If maximizing $\\ell \\ell_{ij}$ is good, then minimizing $-\\ell \\ell_{ij}$ must also be good. Machine learning practicioners commonly refer to -1 times the loglikelihood as <code class=\"language-plaintext highlighter-rouge\">logloss<\/code>:<\/p>\n\n<p>\\begin{align}\n\\text{logloss}_{ij} = (y_{ij}-1)\\log(e^{-\\sigma (s_{i} - s_{j})}) + y_{ij}\\log(1 + e^{-\\sigma (s_{i} - s_{j})})\n\\end{align}<\/p>\n\n<p>In the literature on pairwise loss for ranking, right here is where I\u2019ve witnessed a slight of hand: we only need to learn from the cases where $y_{ij} = 1$. This is because negative cases are symmetric; when $Y_{i} &gt; Y_{j}$ (meaning that the pair $(i, j)$ has the label $y=1$), this implies that $(j, i)$ has label $y=0$. Training on tied pairs doesn\u2019t help, because the model is trying to discern between relevant and irrelevant items. Therefore, all we really need to keep are the instances of $y_{ij}=1$, and the pairwise logloss expression can be simplified.<\/p>\n\n<p>\\begin{align}\n\\text{logloss}_{ij} = \\log(1 + e^{-\\sigma (s_{i} - s_{j})})\n\\end{align}<\/p>\n\n<p>This loss is also known as \u201cpairwise logistic loss,\u201d \u201cpairwise loss,\u201d and \u201cRankNet loss\u201d (after the siamese neural network used for pairwise ranking first proposed in <a href=\"#2\">[2]<\/a>).<\/p>\n\n<p><img align=\"center\" src=\"..\/..\/..\/..\/images\/pairwise_logistic_loss.png\" alt=\"logistic loss\" width=\"600\" \/><\/p>\n\n<p>It\u2019s not too difficult to understand: when $Y_{i} &gt; Y_{j}$, the model will achieve small loss when it can predict scores $s_{i} - s_{j} &gt; 0$. The loss will be large when $s_{j} &gt; s_{i}$. The gradient of the loss for any $s_{i} - s_{j}$ is also controlled by $\\sigma$. Larger values of $\\sigma$ penalize pairwise inconsistencies than values closer to zero.<\/p>\n\n<h2 id=\"lightgbm-implements-gradient-boosting-with-the-lambdarank-gradient\">LightGBM implements gradient boosting with the lambdarank gradient<\/h2>\n<p>LightGBM is a machine learning library for gradient boosting. The core idea behind gradient boosting is that if you can take the first and second derivatives of a loss function you\u2019re seeking to minimize (or an objective function you\u2019re seeking to maximize), then LightGBM can find a solution for you using gradient boosted decision trees (GBDTs). Gradient boosting is more or less a functional version of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Newton%27s_method_in_optimization\">Newton\u2019s method<\/a>, which is why we need the gradient and hessian. During training it builds a sequence of decision trees each fit to the gradient of the loss function when the model is evaluated on the data at the current boosting iteration.<\/p>\n\n<p>\\begin{align}\n\\frac{\\partial \\text{logloss}_{ij}}{\\partial s_{i}} &amp;= \\frac{-\\sigma e^{-\\sigma(s_{j} - s_{i})}}{1 + e^{-\\sigma(s_{i} - s_{j})}}\n\\end{align}\n\\begin{align}\n&amp;= \\frac{-\\sigma}{1 + e^{\\sigma(s_{i} - s_{j})}} \\hspace{10mm} (\\text{mult by} \\hspace{1mm} \\frac{e^{\\sigma(s_{i} - s_{j})}}{e^{\\sigma(s_{i} - s_{j})}})\n\\end{align}\n\\begin{align}\n&amp;= \\lambda_{ij}\n\\end{align}<\/p>\n\n<p><em>This<\/em> is where the \u201clambda\u201d in <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> comes from.<\/p>\n\n<p>Note a critical shortcoming of the $\\lambda_{ij}$ gradients - <strong>they are completely positionally unaware<\/strong>. The formulation of the pairwise loss that we\u2019ve used to derive the $\\lambda_{ij}$ treats the loss the same whether we\u2019ve incorrectly sorted two items near the top of the query or near the bottom of the query. For example, it would assign the same loss and gradient to the pairs $(1, 3)$ and $(100, 101)$ when $s_{i} - s_{j}$ and $Y_{i}$ and $Y_{j}$ are the same. But most eCommerce or Google\/Bing users spend like 90% of their time near the top of the query, so it\u2019s much more important to optimze the items appearing within the first few positions. A possible correction proposed by Burges in 2006 <a href=\"#4\">[4]<\/a> was to just scale $\\lambda_{ij}$ by the change in NDCG (a positionally-aware ranking metric) that would be incurred if the incorrect pairwise sorting of items $(i, j)$ was used:<\/p>\n\n<p>\\begin{align}\n\\lambda_{ij} = \\log(1 + e^{-\\sigma (s_{i} - s_{j})})|\\Delta NDCG_{ij}|\n\\end{align}<\/p>\n\n<p>This is known as the <strong>lambdarank gradient<\/strong>. The claim is that by using this form of the gradient within a loss minimization procedure, we end up maximizing NDCG. Well, if this decision to scale the original $\\lambda_{ij}$ by $|\\Delta NDCG_{ij}|$ seems kind of arbitrary to you, you are not alone. Several researchers have taken issue with it, viewing it more as a hack than a true gradient of a real loss function <a href=\"#7\">[7]<\/a>. Just know that the term <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> does not refer to a loss function (like some other LightGBM <code class=\"language-plaintext highlighter-rouge\">objective<\/code> strings like <code class=\"language-plaintext highlighter-rouge\">\"mse\"<\/code> or <code class=\"language-plaintext highlighter-rouge\">\"mape\"<\/code>), but to an explicit gradient formulation.<\/p>\n\n<p>Anyway, we have the positionally-aware \u201cgradient\u201d of the pairwise loss function with respect to a single product-product pair $(i, j)$ of differentially-labeled products. LightGBM and GBDTs generally regress decision trees on the loss gradients computed with respect to <em>individual samples<\/em> (or rows of a dataset), not single products within pairs of products.<\/p>\n\n<p>In order to just get the <em>gradient with respect to product i<\/em>, we have to accumulate the gradient across all pairs of products where $i$ is the more-relevant item, and symmetrically, across all pairs where $i$ is the less-relevant item. Let $I$ refer to the set of item pairs $(i, j)$ where the first item is more relevant than the second item.<\/p>\n\n<p>\\begin{align}\n\\lambda_{i} = \\sum_{j:{i, j} \\in I}\\lambda_{ij} - \\sum_{j:{j, i} \\in I}\\lambda_{ij}\n\\end{align}<\/p>\n\n<p>We need to take a quick detour. Confusingly, LightGBM (as well as XGBoost) are known as <strong>gradient boosted<\/strong> tree learning libraries. They actually implement <em>Newton boosting<\/em> <a href=\"#3\">[3]<\/a>. Gradient boosting is premised on taking a <strong>first<\/strong>-order Taylor approximation of the loss function about the current estimates of the loss at each step of the tree-estimation process. But you can get better results by taking higher-order approximations to the loss function, and LightGBM uses a <strong>second<\/strong>-order approximation. In basic gradient boosting, during each boosting iteration we fit a new decision tree directly to $Y = g_{i}^{k}$, where $g_{i}^{k} = \\lambda_{i}^{k}$, the gradient of the loss of the model on iteration $k$. But in Newton boosting, the regression involves both the hessian (designated $h_{i}^{k}$) and the gradient:<\/p>\n\n<p>\\begin{align}\n\\text{tree}_{k+1} = \\arg\\min\\sum_{i=1}^{n}h_{i}^{k}\\big(-\\frac{g_{i}^{k}}{h_{i}^{k}} - \\ell\\ell_{i}^{k}\\big)^{2}\n\\end{align}<\/p>\n\n<p>Since we\u2019ve only derived the first derivative of the loss, let\u2019s find the second derivative by applying the quotient rule:<\/p>\n\n<p>\\begin{align}\n\\frac{\\partial^{2} \\text{logloss}_{ij}}{\\partial s_{i}^{2}} &amp;= \\frac{\\sigma^{2}e^{-\\sigma(s_{j} - s_{i})}|\\Delta NDCG_{ij}|}{(1 + e^{-\\sigma(s_{j} - s_{i})})^{2}}\n\\end{align}\n\\begin{align}\n&amp;= \\frac{-\\sigma}{1 + e^{-\\sigma(s_{j} - s_{i})}}|\\Delta NDCG_{ij}| \\cdot \\frac{-\\sigma e^{-\\sigma(s_{j} - s_{i})}}{1 + e^{-\\sigma(s_{j} - s_{i})}}\n\\end{align}\n\\begin{align}\n&amp;= \\lambda_{ij}\\frac{-\\sigma e^{-\\sigma(s_{j} - s_{i})}}{1 + e^{-\\sigma(s_{j} - s_{i})}}\n\\end{align}<\/p>\n\n<p>And we\u2019re done with the math! Later on we\u2019ll map these components of the gradient and hessian to the actual C++ code used in LightGBM\u2019s actual lambdarank objective source code.<\/p>\n\n<h4 id=\"pointwise-pairwise-or-listwise\"><strong>Pointwise, pairwise, or listwise?<\/strong><\/h4>\n<p>A very confusing aspect of the <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> gradient is that despite being closely related to the gradient of the classic pairwise loss function, a LightGBM <code class=\"language-plaintext highlighter-rouge\">LGBMRanker<\/code> model can score <em>individual<\/em> items within a query. It does not expect for two inputs to be provided as ranking input like <code class=\"language-plaintext highlighter-rouge\">rnk.predict(x1, x2)<\/code>. Further, the calculations required to derive the gradient, $\\frac{\\partial \\text{logloss}}{\\partial s_{i}}$ involves sums over all pairs of items within a query, as if it were a listwise LETOR algorithm.<\/p>\n\n<p>The fact is that the <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> LightGBM gradient is based on pairwise classification, but a lambdaMART model involves fitting decision trees to gradients computed g all pairs of differentially-labeled items within a query. Each individual item (each row in the training data) is assigned its own gradient value, and then LightGBM simply regresses trees on those gradients. This is why we can score individual items like <code class=\"language-plaintext highlighter-rouge\">rnk.predict(x1)<\/code>:<\/p>\n\n<pre><code class=\"language-{python}\">import lightgbm as lgb\nimport numpy as np\n\nnp.random.seed(123)\nX = np.random.normal(size=(100,5))\ny = np.random.choice(range(4), size=100, replace=True)\ngrp = [10] * 10\n\nrnk = lgb.LGBMRanker(objective='lambdarank')  # lambdarank is actually default objective for LGBMRanker\nrnk.fit(X, y, group=grp)\n\nrnk.predict(X[50, :].reshape(1, -1))  # pointwise score for row 50\n<\/code><\/pre>\n\n<blockquote>\n  <p>array([-1.95225947])<\/p>\n<\/blockquote>\n\n<p>Other researchers have tried to develop better intuitions and better categorizations of LETOR models other than pointwise\/pairwise\/listwise. The best exploration of this topic I\u2019ve found is Google\u2019s 2019 paper on <em>Groupwise Scoring Functions<\/em> <a href=\"#5\">[5]<\/a> which provides the foundation for the popular <a href=\"https:\/\/github.com\/tensorflow\/ranking\">Tensorflow Ranking library<\/a>. The paper provides the notion of a <em>scoring function<\/em>, which is different than the objective\/loss function. A LambdaMART model is a <strong>pointwise scoring function<\/strong>, meaning that our LightGBM ranker \u201ctakes a single document at a time as its input, and produces a score for every document separately.\u201d<\/p>\n\n<h2 id=\"how-objective-functions-work-in-lightgbm\">How objective functions work in LightGBM<\/h2>\n<p>You might be used to interacting with LightGBM in R or Python, but it\u2019s actually a C++ library that just happens to have well built-out R and Python APIs. Navigate to <code class=\"language-plaintext highlighter-rouge\">src\/objectives<\/code> and you\u2019ll see the implementations of specific objective\/loss functions such as <code class=\"language-plaintext highlighter-rouge\">rank_objective.cpp<\/code> in addition to <code class=\"language-plaintext highlighter-rouge\">objective_function.cpp<\/code> which implements a objective class <a href=\"https:\/\/en.wikipedia.org\/wiki\/Factory_method_pattern\">factory<\/a>.<\/p>\n\n<p>Each individual objective class <strong>must<\/strong> define a method named <code class=\"language-plaintext highlighter-rouge\">GetGradients<\/code> that can update model <code class=\"language-plaintext highlighter-rouge\">score<\/code> (aka \u201closs\u201d) values, <code class=\"language-plaintext highlighter-rouge\">gradients<\/code>, and <code class=\"language-plaintext highlighter-rouge\">hessians<\/code>. Each objective file may contain multiple objective classes. The  <code class=\"language-plaintext highlighter-rouge\">GDBT<\/code> class contained within <code class=\"language-plaintext highlighter-rouge\">boosting\/gbdt.cpp<\/code> that actually <a href=\"https:\/\/github.com\/microsoft\/LightGBM\/blob\/master\/src\/boosting\/gbdt.cpp#L178\">calls<\/a> <code class=\"language-plaintext highlighter-rouge\">GetGradients<\/code> to fit regression trees within LightGBM\u2019s main training routine.<\/p>\n\n<p>In <code class=\"language-plaintext highlighter-rouge\">rank_objective.cpp<\/code>, <code class=\"language-plaintext highlighter-rouge\">GetGradients<\/code> just iterates over queries in the training set, calling an inner <code class=\"language-plaintext highlighter-rouge\">GetGradientsForOneQuery<\/code> that calculates the pairwise loss and lambdarank gradients\/hessians for each item within each query.<\/p>\n\n<div class=\"language-plaintext highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>void GetGradients(const double* score, score_t* gradients,\n                    score_t* hessians) const override {\n    for (data_size_t i = 0; i &lt; num_queries_; ++i) {\n        const data_size_t start = query_boundaries_[i];\n        const data_size_t cnt = query_boundaries_[i + 1] - query_boundaries_[i];\n        GetGradientsForOneQuery(i, cnt, label_ + start, score + start,\n                                gradients + start, hessians + start);\n        ...\n    }\n}\n\nvirtual void GetGradientsForOneQuery(data_size_t query_id, data_size_t cnt,\n                                     const label_t* label,\n                                     const double* score, score_t* lambdas,\n                                     score_t* hessians) const override {\n    \/\/ score, lambdas, and hessians are modified in-place...\n}\n<\/code><\/pre><\/div><\/div>\n\n<p>There are actually a couple of different ranking objectives offered by LightGBM that each subclass a <code class=\"language-plaintext highlighter-rouge\">RankingObjective<\/code> wrapper class:<\/p>\n<ul>\n  <li><code class=\"language-plaintext highlighter-rouge\">LambdarankNDCG<\/code>: this is the selected objective class when you set <code class=\"language-plaintext highlighter-rouge\">LGBMRanker(objective=\"lambdarank\")<\/code>.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">RankXENDCG<\/code>: Rank-cross-entropy-NDCG loss ($XE_{NDCG}$ for short) is a new attempt to revise the lambdarank gradients through a more theoretically sound argument that involves transforming the model scores $s_{i}$ into probabilities and deriving a special form of multiclass log loss <a href=\"#6\">[6]<\/a>.<\/li>\n<\/ul>\n\n<h2 id=\"connecting-the-math-to-the-code\">Connecting the math to the code<\/h2>\n<p>All of the <code class=\"language-plaintext highlighter-rouge\">lambdarank<\/code> math is located primarily in two methods within the <code class=\"language-plaintext highlighter-rouge\">LambdarankNDCG<\/code> objective class:<\/p>\n<ol>\n  <li><a href=\"https:\/\/github.com\/microsoft\/LightGBM\/blob\/master\/src\/objective\/rank_objective.hpp#L228\"><code class=\"language-plaintext highlighter-rouge\">GetSigmoid<\/code><\/a> performs a look-up operation on a pre-computed, discretized logistic function: \\begin{align}\n\\frac{\\lambda_{ij}}{|\\Delta NDCG_{ij}|} &amp;= \\frac{1}{1 + e^{\\sigma(s_{i} - s_{j})}}\n\\end{align} stored in a vector named <code class=\"language-plaintext highlighter-rouge\">sigmoid_table_<\/code>. Using pre-computed logistic function values reduces the number of floating point operations needed to calculate the gradient and hessian for each row of the dataset during each boosting iteration. <code class=\"language-plaintext highlighter-rouge\">GetGradientsForOneQuery<\/code> passes $(s_{i} - s_{j})$ to <code class=\"language-plaintext highlighter-rouge\">GetSigmoid<\/code>, which applies a scaling factor to transform $(s_{i} - s_{j})$ into an integer value (of type <code class=\"language-plaintext highlighter-rouge\">size_t<\/code> in C++) so that can then be used to look up the corresponding value within <code class=\"language-plaintext highlighter-rouge\">sigmoid_table_<\/code>.<\/li>\n  <li><a href=\"https:\/\/github.com\/microsoft\/LightGBM\/blob\/master\/src\/objective\/rank_objective.hpp#L140\"><code class=\"language-plaintext highlighter-rouge\">GetGradientsForOneQuery<\/code><\/a> processes individual queries. This method launches two <code class=\"language-plaintext highlighter-rouge\">for<\/code> loops, the outer loop iterating from <code class=\"language-plaintext highlighter-rouge\">i=0<\/code> to <code class=\"language-plaintext highlighter-rouge\">truncation_level_<\/code> (a reference to the <a href=\"https:\/\/lightgbm.readthedocs.io\/en\/latest\/Parameters.html#lambdarank_truncation_level\"><code class=\"language-plaintext highlighter-rouge\">lambdarank_truncation_level<\/code><\/a> parameter) and the inner loop iterating from <code class=\"language-plaintext highlighter-rouge\">j=i+1<\/code> to <code class=\"language-plaintext highlighter-rouge\">cnt<\/code>, the latter being the number of items within the query at hand. This is where the math comes in:<\/li>\n<\/ol>\n\n<pre><code class=\"language-C++\">\/\/ calculate lambda for this pair\ndouble p_lambda = GetSigmoid(delta_score);              \/\/ 1 \/ (1 + e^(sigma * (s_i - s_j)))\ndouble p_hessian = p_lambda * (1.0f - p_lambda);        \/\/ Begin hessian calculation.\n\/\/ update\np_lambda *= -sigmoid_ * delta_pair_NDCG;                \/\/ Finish lambdarank gradient: -sigma * |NDCG| \/ (1 + e^(sigma * (s_i - s_j)))\np_hessian *= sigmoid_ * sigmoid_ * delta_pair_NDCG;     \/\/ Finish hessian calculation. See derivation below.\n<\/code><\/pre>\n\n<p>Let\u2019s tie the code together with the math, as I had particularly struggled to understand why <code class=\"language-plaintext highlighter-rouge\">p_hessian =  p_lambda *  (1 - p_lambda)<\/code> was valid:<\/p>\n\n<p>\\begin{align}\n\\text{p_lambda} &amp;= \\frac{1}{1 + e^{\\sigma(s_{i} - s_{j})}}\n\\end{align}\n\\begin{align}\n1 - \\text{p_lambda} &amp;= \\frac{e^{\\sigma(s_{i} - s_{j})}}{1 + e^{\\sigma(s_{i} - s_{j})}}\n\\end{align}\n\\begin{align}\n\\text{p_lambda}(1 - \\text{p_lambda}) &amp;= \\frac{e^{\\sigma(s_{i} - s_{j})}}{(1 + e^{\\sigma(s_{i} - s_{j})})^{2}}\n\\end{align}\n\\begin{align}\n\\Rightarrow \\frac{\\partial^{2}\\text{logloss}}{\\partial s_{i}^{2}} &amp;= \\sigma^{2}|\\Delta NDCG_{ij}|\\text{p_lambda}(1 - \\text{p_lambda})\n\\end{align}<\/p>\n\n<p>And that\u2019s just about it! There are some other tweaks that some LightGBM contributors have made, such as the option to \u201cnormalize\u201d the gradients across different queries (controlled with the <code class=\"language-plaintext highlighter-rouge\">lambdarank_norm<\/code> parameter), which helps prevent the case where one very long query with tons of irrelevant items gets an unfair \u201cbuild-up\u201d of gradient value relative to a shorter query.<\/p>\n\n<h2 id=\"references\">References<\/h2>\n<p><a id=\"1\">[1]<\/a>\nJoachims, 2008. <a href=\"https:\/\/www.cs.cornell.edu\/people\/tj\/svm_light\/\">SVMlight<\/a><\/p>\n\n<p><a id=\"2\">[2]<\/a>\nBurges, et al., 2005. <a href=\"https:\/\/icml.cc\/Conferences\/2005\/proceedings\/papers\/012_LearningToRank_BurgesEtAl.pdf\">Learing to Rank using Gradient Descent<\/a><\/p>\n\n<p><a id=\"3\">[3]<\/a>\nSigrist, 2020. <a href=\"https:\/\/arxiv.org\/pdf\/1808.03064.pdf\">Gradient and Newton Boosting for Classification and Regression<\/a><\/p>\n\n<p><a id=\"4\">[4]<\/a>\nBurges, 2010. <a href=\"https:\/\/www.microsoft.com\/en-us\/research\/uploads\/prod\/2016\/02\/MSR-TR-2010-82.pdf\">From RankNet to LambdaRank to LambdaMART: An Overview<\/a><\/p>\n\n<p><a id=\"5\">[5]<\/a>\nAi, Wang, Bendersky et al., 2019. <a href=\"https:\/\/storage.googleapis.com\/pub-tools-public-publication-data\/pdf\/a995c37352b4b7d13923ca945cdcd03227c9023f.pdf\">Learning Groupwise Scoring Functions Using Deep Neural Networks<\/a><\/p>\n\n<p><a id=\"6\">[6]<\/a>\nBruch, 2021. <a href=\"https:\/\/arxiv.org\/pdf\/1911.09798.pdf\">An Alternative Cross Entropy Loss for Learning-to-Rank<\/a><\/p>\n\n<p><a id=\"7\">[7]<\/a>\nWang, Li, et al., 2018. <a href=\"https:\/\/research.google\/pubs\/pub47258\/\">The LambdaLoss Framework for Ranking Metric Optimization<\/a><\/p>\n","pubDate":"Sat, 01 May 2021 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2021\/05\/01\/lambdarank-lightgbm.html","guid":"https:\/\/ffineis.github.io\/blog\/2021\/05\/01\/lambdarank-lightgbm.html","category":"blog"},{"title":"CSV to model with a one-liner: an end-to-end Sklearn pipeline","description":"<h1 id=\"introduction\">Introduction<\/h1>\n\n<p>Oftentimes us data scientists find ourselves presented with a new, foreign dataset (or set of files that jointly comprise a new dataset), with the goal simply to \u201cbuild a model.\u201d Model interpretability in a case like may fall to the wayside, and this is especially true when the data have been anonymized and we\u2019re really not supposed to understand the meaning of any particular data point or field name.<\/p>\n\n<p>In a high-dimensional setting (hundreds, thousands of potential features to choose from) with little understanding the individual fields, we face three main challenges when it comes to building a model:<\/p>\n\n<ol>\n  <li><strong>Diverse data processing needs<\/strong>: numeric and categorical features require different data processing steps, as do features with a lot of missing data<\/li>\n  <li><strong>Feature selection<\/strong>: sifting signal through the noise without making arbitrary and capricious decisions when it comes to selecting features into a resulting model<\/li>\n  <li><strong>Building a reusable data and modeling pipeline<\/strong>: Getting predictions from a new dataset should not require having to call dozens of custom functions in the correct order in order to transform the data into the format expected by the model. This process needs to be as easy as calling a single <code class=\"language-plaintext highlighter-rouge\">.transform<\/code> method.<\/li>\n<\/ol>\n\n<p>This post is about how I built one Sklearn Pipeline that can take me from <code class=\"language-plaintext highlighter-rouge\">read_csv<\/code> resulting in hundreds of anonymous features to a completely processed data ready for model predictions with the call of single method.<\/p>\n\n<h2 id=\"the-data-the-code\">The data, the code<\/h2>\n\n<p>You\u2019ll need to download the <a href=\"https:\/\/www.kaggle.com\/c\/ieee-fraud-detection\/data\">IEEE-CIS Fraud Detection data<\/a> from Kaggle. All of the code required to follow along is in my GitHub repo: <a href=\"https:\/\/github.com\/ffineis\/ieee-cis-fraud-detection\">ieee-cis-fraud-detection<\/a><\/p>\n\n<p>Files you\u2019ll need:\n<code class=\"language-plaintext highlighter-rouge\">train_transaction.csv<\/code>\n<code class=\"language-plaintext highlighter-rouge\">test_transaction.csv<\/code><\/p>\n\n<p>Note that I\u2019m ignoring the <code class=\"language-plaintext highlighter-rouge\">*_identity.csv<\/code> files. We can get pretty decent performance (90% precision, 50% recall) from the transactions data alone.<\/p>\n\n<h2 id=\"pipelines-and-transformers-dataframe-to-model-matrix-in-one-go\">Pipelines and Transformers: <code class=\"language-plaintext highlighter-rouge\">DataFrame<\/code> to model matrix in one go<\/h2>\n\n<p><a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline\">Sklearn Pipelines<\/a> are structures that allow Data Scientists to concatenate different data transformation tasks (called \u201csteps\u201d) out of Transformer objects. A Pipeline can end in Sklearn Estimator that fits a model.<\/p>\n\n<p>For example, we can define a simple Pipeline that imputes missing values with the median, scales all $X$ variables between 0 and 1, and then fits a Random Forest:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kn\">from<\/span> <span class=\"nn\">sklearn.pipeline<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Pipeline<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">sklearn.impute<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">SimpleImputer<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">sklearn.preprocessing<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">MinMaxScaler<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">sklearn.ensemble<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">RandomForestClassifier<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">pandas<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">read_csv<\/span>\n\n<span class=\"n\">step1<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"s\">'impute'<\/span><span class=\"p\">,<\/span> <span class=\"n\">SimpleImputer<\/span><span class=\"p\">(<\/span><span class=\"n\">strategy<\/span><span class=\"o\">=<\/span><span class=\"s\">'median'<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">step2<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"s\">'01scaler'<\/span><span class=\"p\">,<\/span> <span class=\"n\">MinMaxScaler<\/span><span class=\"p\">())<\/span>\n<span class=\"n\">step3<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"s\">'rf'<\/span><span class=\"p\">,<\/span> <span class=\"n\">RandomForestClassifier<\/span><span class=\"p\">(<\/span><span class=\"n\">n_estimators<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"p\">))<\/span>\n<span class=\"n\">pipeline<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Pipeline<\/span><span class=\"p\">(<\/span><span class=\"n\">steps<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"n\">step1<\/span><span class=\"p\">,<\/span> <span class=\"n\">step2<\/span><span class=\"p\">,<\/span> <span class=\"n\">step3<\/span><span class=\"p\">])<\/span>\n\n<span class=\"n\">X<\/span> <span class=\"o\">=<\/span> <span class=\"n\">read_csv<\/span><span class=\"p\">(<\/span><span class=\"s\">'path\/to\/training\/data.csv'<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">pipeline<\/span><span class=\"p\">.<\/span><span class=\"n\">fit_transform<\/span><span class=\"p\">(<\/span><span class=\"n\">X<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>The real trick to getting started with Pipelines is that all but the final step must have both a <code class=\"language-plaintext highlighter-rouge\">.fit<\/code> and a <code class=\"language-plaintext highlighter-rouge\">.transform<\/code> method (e.g. the <code class=\"language-plaintext highlighter-rouge\">MinMaxScaler<\/code> transformer), but the last step just needs a <code class=\"language-plaintext highlighter-rouge\">.fit<\/code> method. This lets the final step be a an Estimator (a model), instead of a data Transformer.<\/p>\n\n<p>At the end of the day, I really wanted to know just <em>how far<\/em> can I go with Sklearn Pipelines? Can I do all of my data processing tasks within a single transformer Pipeline? Given a new batch of data, I didn\u2019t want to have to recreate the full training data creation process - running a bunch of one-off Data Scientist-defined data processing functions in a very specific order. <strong>My goal: could I go from <code class=\"language-plaintext highlighter-rouge\">pandas.read_csv<\/code> to model predictions in a single line of code?<\/strong><\/p>\n\n<h2 id=\"feature-engineering-diverse-needs\">Feature engineering: diverse needs<\/h2>\n<p>I ended up building <a href=\"https:\/\/github.com\/ffineis\/ieee-cis-fraud-detection\/blob\/master\/code\/feature_pipelines.py\">the following<\/a> data processing Pipeline<\/p>\n\n<p><img align=\"center\" src=\"https:\/\/raw.githubusercontent.com\/ffineis\/ieee-cis-fraud-detection\/master\/data\/output\/processor_pipeline.png\" alt=\"pipeline\" \/><\/p>\n\n<p>This is <strong>end-to-end<\/strong> \u2013 there are only two steps:<\/p>\n<ol>\n  <li>Load a IEEE-CIS Fraud dataset into a <code class=\"language-plaintext highlighter-rouge\">pandas.DataFrame<\/code><\/li>\n  <li>Pass that data to the pipeline and execute <code class=\"language-plaintext highlighter-rouge\">.fit_transform<\/code>. The Pipeline will handle <em>every<\/em> data processing and feature engineering step.<\/li>\n<\/ol>\n\n<p>The main complexities in building a one-stop-shop like this is that we have a diversity of needs because of all of the different types of features present in the IEEE-CIS dataset. Namely, categorical features generally pose a few issues, and as you can see in the Pipeline flowchart above, I had to break up the IEEE data into 5 groups:<\/p>\n\n<ol>\n  <li>Continuous (\u201cnumeric\u201d) features. These features will be processed in their own Pipeline.<\/li>\n  <li>Categorical features will be processed in their own Pipeline.\n    <ul>\n      <li>2.1 String-valued categorical features with low cardinality, e.g. the credit card someone used in a transaction like \u201cmastercard\u201d or \u201cvisa\u201d, with fewer than 20 unique categorical levels.<\/li>\n      <li>2.2. String-valued, high-cardinality features.<\/li>\n      <li>2.3. Numerically-valued, low-cardinality features, e.g. a feature whose levels are numbers that represent categories.<\/li>\n      <li>2.4. Numerically-valued, high-cardinality features.<\/li>\n    <\/ul>\n  <\/li>\n<\/ol>\n\n<p><strong>Imputing missing values<\/strong>: we\u2019ll impute missing values in string-valued categorical features with the string \u2018NA\u2019 and in numerically-valued categorical features with the number 999. We impute numeric features with their respective medians.<\/p>\n\n<p><strong>One-hot encoding<\/strong>: once both string and numerically-valued features have had their missing values imputed, next, we consider features with fewer than 20 unique levels as \u201clow cardinality\u201d. These features will simply be one-hot encode these into binary indicator columns.<\/p>\n\n<p>For \u201chigh cardinality\u201d features we\u2019ll one-hot encode them into a very wide, very sparse binary matrix, and then use the SVD to embed that sparse matrix into a smaller dense matrix. We do this as opposed to constructing potentially thousands or tens of thousands of binary features. This is basically a method of categorical feature embedding.<\/p>\n\n<p>The categorical and continuous pipelines will be concatenated \u201cadditively\u201d or \u201chorizontally\u201d using the <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.pipeline.FeatureUnion.html\">sklearn.pipeline.FeatureUnion<\/a> pipeline composition function. Finally, we add some processing on top of the <em>union<\/em> of the categorical and continuous pipelines to drop redundant (read: highly correlated) features and features with very little variance, like this:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"c1\"># -- continuous feature pipeline\n<\/span><span class=\"n\">num_pipeline<\/span> <span class=\"o\">=<\/span> <span class=\"n\">numeric_feature_pipeline<\/span><span class=\"p\">(<\/span><span class=\"n\">df<\/span>\n                                        <span class=\"p\">,<\/span> <span class=\"n\">numeric_features<\/span><span class=\"o\">=<\/span><span class=\"n\">num_features<\/span><span class=\"p\">)<\/span>\n\n<span class=\"c1\"># -- categorical feature pipeline\n<\/span><span class=\"n\">cat_pipeline<\/span> <span class=\"o\">=<\/span> <span class=\"n\">categorical_feature_pipeline<\/span><span class=\"p\">(<\/span><span class=\"n\">df<\/span>\n                                            <span class=\"p\">,<\/span> <span class=\"n\">categorical_string_features<\/span><span class=\"o\">=<\/span><span class=\"n\">cat_str_features<\/span>\n                                            <span class=\"p\">,<\/span> <span class=\"n\">categorical_numeric_features<\/span><span class=\"o\">=<\/span><span class=\"n\">cat_num_features<\/span>\n                                            <span class=\"p\">,<\/span> <span class=\"n\">high_cardinality_cutoff<\/span><span class=\"o\">=<\/span><span class=\"n\">data_config<\/span><span class=\"p\">.<\/span><span class=\"n\">hi_cardinality_cutoff<\/span><span class=\"p\">)<\/span>\n<span class=\"c1\"># -- the full feature pipeline\n<\/span><span class=\"n\">feature_pipeline<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Pipeline<\/span><span class=\"p\">(<\/span><span class=\"n\">steps<\/span><span class=\"o\">=<\/span><span class=\"p\">[(<\/span><span class=\"s\">'preprocess'<\/span><span class=\"p\">,<\/span> <span class=\"n\">FeatureUnion<\/span><span class=\"p\">([(<\/span><span class=\"s\">'categorical'<\/span><span class=\"p\">,<\/span> <span class=\"n\">cat_pipeline<\/span><span class=\"p\">)<\/span>\n                                                                <span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"s\">'numeric'<\/span><span class=\"p\">,<\/span> <span class=\"n\">num_pipeline<\/span><span class=\"p\">)]))<\/span>\n                                    <span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"s\">'decorrelate'<\/span><span class=\"p\">,<\/span> <span class=\"n\">UncorrelatedFeatureSelector<\/span><span class=\"p\">())<\/span>\n                                    <span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"s\">'nondegenerate'<\/span><span class=\"p\">,<\/span> <span class=\"n\">NonDegenerateFeatureSelector<\/span><span class=\"p\">())])<\/span>\n\n<span class=\"c1\"># -- fit feature pipeline, transform training data\n<\/span><span class=\"n\">X_train<\/span> <span class=\"o\">=<\/span> <span class=\"n\">feature_pipeline<\/span><span class=\"p\">.<\/span><span class=\"n\">fit_transform<\/span><span class=\"p\">(<\/span><span class=\"n\">read_csv<\/span><span class=\"p\">(<\/span><span class=\"s\">'path\/to\/training\/data.csv'<\/span><span class=\"p\">))<\/span>                  \n<\/code><\/pre><\/div><\/div>\n\n<p>While not encountered in this dataset, <strong>ordinal categorical features<\/strong> (features whose levels imply a specific ranking, e.g. \u201ccold\u201d &lt; \u201cwarm\u201d &lt; \u201chot\u201d) require additional special attention.<\/p>\n\n<h2 id=\"step-2-processed-features-into-a-model\">Step 2: processed features into a model<\/h2>\n\n<p>Most examples of Sklearn Pipelines\u2019 final step is an Sklearn Estimator, so that feature engineering steps feed directly into a predictive model. While this makes sense for simple, quick-to-fit Pipelines, the Pipeline I\u2019ve laid out above takes about 8 minutes to fit and transform my training set of ~500,000 training examples. Therefore, we\u2019ll <code class=\"language-plaintext highlighter-rouge\">feature_pipeline<\/code> unto itself, apart from a subsequent model.<\/p>\n\n<h4 id=\"benchmark-classifier\">Benchmark classifier<\/h4>\n<p>It\u2019s generally accepted that Data Scientists should try to avoid needless model complexity if it is precisely that, needless. If a simple, easily-interpreted benchmark model can perform just as well as a more complex, tree- or neural-network-based model, then stick with the benchmark model.<\/p>\n\n<p>The LASSO model is a first stop on your way to building the right predictive model. The LASSO linear model is a penalized regression model that has the benefit of sparsity (it selects only important features from a set of superfluous features) and interpretability (this is a linear model with traditional linear coefficients), and it comes in flavors that support both classification and continuous regression tasks.<\/p>\n\n<p>As is the case with most types of predictive models, the LASSO model comes with a set hyperparameters, the most important of which is <code class=\"language-plaintext highlighter-rouge\">C<\/code>, the inverse of the L1-penalty weight. Smaller values of <code class=\"language-plaintext highlighter-rouge\">C<\/code> result in more sparsity (fewer features selected), and <code class=\"language-plaintext highlighter-rouge\">C<\/code> = infinity is equivalent to a regular old logistic regression. Best practices are to use a search procedure in tandem with cross-validation to pick out the value of <code class=\"language-plaintext highlighter-rouge\">C<\/code> that will allow our model to generalize the best to unseen test-set data. For that, we use Sklearn\u2019s <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/generated\/sklearn.model_selection.GridSearchCV.html\">sklearn.model_selection.GridSearchCV<\/a> cross-validation procedure.<\/p>\n\n<p>The coolest thing about <code class=\"language-plaintext highlighter-rouge\">GridSearchCV<\/code> is that it provides the ability to automatically refit a model on <em>all<\/em> of the training data using the best parameter setting found at the conclusion of the hyperparameter search.<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"c1\"># -- define classifier object and hyperparameter grid\n<\/span><span class=\"n\">model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">LogisticRegression<\/span><span class=\"p\">(<\/span><span class=\"n\">penalty<\/span><span class=\"o\">=<\/span><span class=\"s\">'l1'<\/span>\n                           <span class=\"p\">,<\/span> <span class=\"n\">solver<\/span><span class=\"o\">=<\/span><span class=\"s\">'liblinear'<\/span>\n                           <span class=\"p\">,<\/span> <span class=\"n\">class_weight<\/span><span class=\"o\">=<\/span><span class=\"s\">'balanced'<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">param_grid<\/span> <span class=\"o\">=<\/span> <span class=\"p\">{<\/span><span class=\"s\">'C'<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span><span class=\"mf\">0.1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">10<\/span><span class=\"p\">]}<\/span>\n\n<span class=\"c1\"># -- search grid using cross-validation, refit on all training data \n<\/span><span class=\"n\">gcv<\/span> <span class=\"o\">=<\/span> <span class=\"n\">GridSearchCV<\/span><span class=\"p\">(<\/span><span class=\"n\">model<\/span>\n                   <span class=\"p\">,<\/span> <span class=\"n\">param_grid<\/span><span class=\"o\">=<\/span><span class=\"n\">param_grid<\/span>\n                   <span class=\"p\">,<\/span> <span class=\"n\">cv<\/span><span class=\"o\">=<\/span><span class=\"mi\">3<\/span>\n                   <span class=\"p\">,<\/span> <span class=\"n\">n_jobs<\/span><span class=\"o\">=<\/span><span class=\"mi\">2<\/span>\n                   <span class=\"p\">,<\/span> <span class=\"n\">scoring<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span><span class=\"s\">'f1'<\/span><span class=\"p\">,<\/span> <span class=\"s\">'roc_auc'<\/span><span class=\"p\">,<\/span> <span class=\"s\">'recall'<\/span><span class=\"p\">,<\/span> <span class=\"s\">'precision'<\/span><span class=\"p\">,<\/span> <span class=\"s\">'accuracy'<\/span><span class=\"p\">]<\/span>\n                   <span class=\"p\">,<\/span> <span class=\"n\">refit<\/span><span class=\"o\">=<\/span><span class=\"s\">'f1'<\/span>\n                   <span class=\"p\">,<\/span> <span class=\"n\">verbose<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">gcv<\/span><span class=\"p\">.<\/span><span class=\"n\">fit<\/span><span class=\"p\">(<\/span><span class=\"n\">X_train<\/span>\n        <span class=\"p\">,<\/span> <span class=\"n\">y<\/span><span class=\"o\">=<\/span><span class=\"n\">y_train<\/span><span class=\"p\">)<\/span>\n\n<span class=\"c1\"># -- fitted model on best parameter set\n<\/span><span class=\"n\">best_model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">gcv<\/span><span class=\"p\">.<\/span><span class=\"n\">best_estimator_<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p><img align=\"center\" src=\"https:\/\/raw.githubusercontent.com\/ffineis\/ieee-cis-fraud-detection\/master\/data\/output\/benchmark_gcv_performance.png\" alt=\"lasso gcv performance\" \/><\/p>\n\n<p>As we can see, our hyperparameter search does not accomplish much - cross-validated model performance is constant over our three choices of <code class=\"language-plaintext highlighter-rouge\">C<\/code>. We can generally expect low precision, about 0.1, meaning that most of the LASSO model\u2019s fraud alerts will be false positives, but higher recall, about 0.7, meaning that this model will end up flagging most the fraudulent credit card transactions. It\u2019s way too aggressive!<\/p>\n\n<h4 id=\"ensemble-classifier\">Ensemble classifier<\/h4>\n<p>Unsatisfied with a 10% expected true positive rate, we\u2019ll use more of a black box type model: the extremely randomized trees classifier. Basically, this is a random forest but made up of randomly-constructed trees. Parameter randomization is a common way to fight model overfitting while also gaining the added benefit of training speed-up. For more on the topic of parameter randomization and machine learning, I would recommend reading about the <a href=\"https:\/\/people.eecs.berkeley.edu\/~brecht\/papers\/08.rah.rec.nips.pdf\">Random Kitchen Sinks<\/a> approach.<\/p>\n\n<p>When it comes to tree ensembles, our most important hyperparameters are <code class=\"language-plaintext highlighter-rouge\">max_features<\/code> (number of features to select for each constituent tree), <code class=\"language-plaintext highlighter-rouge\">n_estimators<\/code> (total trees in ensemble), and <code class=\"language-plaintext highlighter-rouge\">max_depth<\/code> (max branch length in any individual tree). Here are some grid-searched average cross-validation metrics from using the <code class=\"language-plaintext highlighter-rouge\">sklearn.ensemble.ExtraTreesClassifier<\/code>:<\/p>\n\n<p><img align=\"center\" src=\"https:\/\/raw.githubusercontent.com\/ffineis\/ieee-cis-fraud-detection\/master\/data\/output\/gcv_performance.png\" alt=\"extratrees gcv performance\" \/><\/p>\n\n<p>This model exchanges recall in order to become much more precise. Instead of labeling everything as fraud, this model misses about 50% of all fraud cases. But when it does label a transaction as fraudulent, there\u2019s a high likelihood (90%+) that it\u2019s actually fraud.<\/p>\n\n<h4 id=\"a-note-about-class-imbalance\">A note about class imbalance<\/h4>\n<p>Only 3.5% of the samples in <code class=\"language-plaintext highlighter-rouge\">training_transactions.csv<\/code> were fraudlent credit card transactions, meaning that any model that always predicted \u201cno fraud\u201d 100% we would exptect to be about 96.5% accurate. This is unacceptable, so we assign class weights to the fraud\/no fraud samples in the training set to increase the penalty of a classifier for predicting false negatives.<\/p>\n\n<p>Sklearn provides a very simple entrypoint for modifying class weights on most of its estimators. I recommend using the setting <code class=\"language-plaintext highlighter-rouge\">'balanced'<\/code> lest you want the individual class weights to become yet another hyperparameter:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"n\">model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ExtraTreesClassifier<\/span><span class=\"p\">(<\/span><span class=\"n\">class_weight<\/span><span class=\"o\">=<\/span><span class=\"s\">'balanced'<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>There are many good Google-able resources for how to train models in the face of severe class imbalance. I always recommend studying a confusion matrix and calculating precision (the rate at which predicted fraud cases are actually fraudulent) and recall (the number of fraudulent cases identified). False positives and false negatives have a variable cost depending on your industry, and the job of the data scientist is often to minimize the total cost incurred by both.<\/p>\n\n<h2 id=\"lessons-learned\">Lessons learned<\/h2>\n<p>At the end of the day, I was able to develop a data pipeline that gave me both decent model performance and the ability to get model predictions from a one-liner:<\/p>\n\n<div class=\"language-plaintext highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>preds = model.predict(pipeline.transform(read_csv('test_transactions.csv')))\n<\/code><\/pre><\/div><\/div>\n\n<ol>\n  <li>Sklearn does not provide a good API for changing data types, and building a custom Transformer to cast all categorical features <code class=\"language-plaintext highlighter-rouge\">astype(str)<\/code> does not play nicely with downstream Transformers, hence my decision to preprocess string- and numerically-valued categorical features separately. Sklearn transformers generally transform input data <em>X<\/em> into numpy arrays, even when <em>X<\/em> is a <code class=\"language-plaintext highlighter-rouge\">pandas.DataFrame<\/code>.<\/li>\n  <li>While you <em>can<\/em> use two <code class=\"language-plaintext highlighter-rouge\">ColumnTransfomers<\/code> in succession, I would not recommend it. The default behavior of a <code class=\"language-plaintext highlighter-rouge\">ColumnTransfomer<\/code> is to apply a Pipeline Transformer to a subset of columns in <em>X<\/em> and return only that transformed feature subset. I\u2019m referring to the parameter <code class=\"language-plaintext highlighter-rouge\">remainder<\/code>, whose default is the string <code class=\"language-plaintext highlighter-rouge\">'drop'<\/code>. You can specify <code class=\"language-plaintext highlighter-rouge\">remainder = 'passthrough'<\/code> and have the transformer return <em>all<\/em> features, both transformed and untransformed. But a more easily-understood way to write feature-specific transforms is to define separate <code class=\"language-plaintext highlighter-rouge\">ColumnTransformers<\/code> for each group of features that requires a separate processing pipeline and then using <code class=\"language-plaintext highlighter-rouge\">FeatureUnion<\/code> to horizontally concatenate them. This approach has the added benefit of selecting, in the end, only the subset of features you intend to use for modeling purposes and excludes any features that were not explicitly passed into the pipeline.<\/li>\n  <li>Related to 2., it is better to explicitly define which features from your data, <em>X<\/em>, will be used for  modeling than implicitly state which features will <em>not<\/em> be used for modeling. For example, the training data contains a date field, <code class=\"language-plaintext highlighter-rouge\">TransactionDT<\/code>. Chaining multiple <code class=\"language-plaintext highlighter-rouge\">ColumnTransformer<\/code> each with <code class=\"language-plaintext highlighter-rouge\">remainder=True<\/code> runs the risk of including <code class=\"language-plaintext highlighter-rouge\">TransactionDT<\/code> unless we specifically exclude that feature. The transaction date in the training set will be <em>prior<\/em> to a future test set (unless we extract date-agnostic features like time of day or day of week), so it makes no sense to keep <code class=\"language-plaintext highlighter-rouge\">TransactionDT<\/code> for predictive purposes. <strong>Instead, define the features you want to use<\/strong>.<\/li>\n<\/ol>\n\n<p>Manual feature selection and engineering can become both time intensive, arbitrary, and based on naive univariate tests between a target variable <em>Y<\/em> and individual covariates <em>X<\/em><sub>i<\/sub>. Two automatic feature selection methods (e.g. those in the <a href=\"https:\/\/scikit-learn.org\/stable\/modules\/feature_selection.html\">sklearn.feature_selection module<\/a>) will most often result in different sets of feature sets.<\/p>\n","pubDate":"Thu, 30 Apr 2020 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2020\/04\/30\/sklearn-pipelines-fraud-detection.html","guid":"https:\/\/ffineis.github.io\/blog\/2020\/04\/30\/sklearn-pipelines-fraud-detection.html","category":"blog"},{"title":"Joining Type II change tables and logistics industry data","description":"<h1 id=\"logistics-industry-101\">Logistics industry 101<\/h1>\n\n<p>Working as a consultant at <a href=\"https:\/\/aptitive.com\/\">Aptitive<\/a>, my longest-standing client was a large North American logistics company. The logistics\nindustry is huge in Chicago, an industry that dates back to a time when Chicago served as major crossroads and trading hub connecting the East Coast to the West,\nthe Great Lakes to the Mississippi River. Logistics is a huge industry nationwide - trucking is the most common profession in 29 states in the US\n<a href=\"https:\/\/www.rtsinc.com\/articles\/why-trucking-still-america-s-number-one-job\">according to the Bureau of Labor Statistics<\/a> - and there is virtually\nno centralization among trucking companies. There isn\u2019t a meaningful Amazon or Apple of hauling freight. This makes the industry\nsimultaneously amenable to technological advancement, but also full of complicated, decentralized data.<\/p>\n\n<p>Here\u2019s what I learned working with my client: the logistics industry is in the midst of a massive transformation, from a federation of \nhuman actors making gut-instinct choices into an automated system driven by subject matter experts who know a thing or two about the complexities of transportation management service data structures.<\/p>\n\n<p>Before we get into code, we\u2019ll need some useful industry terms:<\/p>\n\n<ul>\n  <li>A logistics company\u2019s <strong>customers<\/strong> are their clients who use the logistics firm to move their freight. Confusingly, <strong>customers<\/strong>\nare also referred to in the industry as <strong>shippers<\/strong>.<\/li>\n  <li><strong>Carriers<\/strong> are the people moving freight, e.g. truckers or UPS.<\/li>\n  <li><strong>Freight brokering<\/strong>: In Chicago, there are many logistics brokerage firms who basically serve as a spot market\n for shipping rates. A customer tells the brokerage about their freight, and a broker then quotes the customer a rate. The brokerage makes a profit\n by finding a carrier who submits a bid to move the freight for less money than what the brokerage charged the customer to move the freight.\n Brokering involves reserving an entire truck for the customer\u2019s freight.<\/li>\n  <li><strong>Less-than-truckload shipping<\/strong> (LTL): if brokers reserve <em>entire trucks<\/em>, then LTL shipping is when customer\u2019s freight only takes up a \n portion of a truck, so that multiple customers\u2019 freight can move on the same truck at once. Think of Uber Black vs Uber Pool. LTL usually comes with lower profit margins for a logistics company than brokered loads,\n but LTL is easier to plan for because customers typically book LTL freight far in advance, on a recurring basis.<\/li>\n  <li><strong>Loads<\/strong> are units of customer freight.<\/li>\n  <li>Different <strong>transportation modes<\/strong> for moving loads, like rail, ocean barge, airplane, are configured on a load-by-load basis. The majority of the time we\u2019re \n talking about freight moved by trucks. Trucks-based modes are <em>dry van<\/em> (i.e. a regular, unrefrigerated truck), <em>reefer<\/em> (a refrigerated truck),\n <em>intermodal<\/em> (trailers that can travel by rail and truck), etc.\n<br \/><\/li>\n<\/ul>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/van_vs_ltl.png\" width=\"500px\" height=\"400px\" \/>\n<span>Full truckload freight (top) vs LTL freight (bottom)<\/span>\n<\/div>\n<p><br \/><\/p>\n<ul>\n  <li><strong>Lanes<\/strong> are (origin, destination) pairs that describe where a load is moving. It\u2019s possible to for one load to move across multiple lanes, for example, if\na customer needs freight to be picked up from two separate warehouses and dropped off at a single destination.\n<br \/><\/li>\n<\/ul>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/load_lanes.png\" width=\"600px\" height=\"400px\" \/>\n<span>A load on a single lane (left) vs a multi-lane load (right)<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<p>So, in a sentence:<\/p>\n<blockquote>\n<p>\"Freight brokerages or LTL shippers assign loads a particular mode and then find carriers who can move those loads across lanes.\"<\/p>\n<\/blockquote>\n<p><br \/><\/p>\n\n<h1 id=\"type-i-vs-type-ii-changes-reflecting-changes-in-a-database\">Type I vs Type II changes: reflecting changes in a database<\/h1>\n\n<p>Getting back to data - not all data warehouses are created equally, especially when it comes to their ability to track the history of particular entities\nover time. Here, by <strong>entity<\/strong> I\u2019m referring to any object of business value (a load, a lane, a mode, a carrier, etc.). Now, the history of a load can be quite complicated. A load\ncan be reconfigured by any number of logistics representatives; a load\u2019s transportation mode or total weight might\nneed to be updated if a customer decides to change the contents of the load. The destination may need to change if supply or\ndemand for the customer\u2019s products change in a particular region overnight.<\/p>\n\n<p>Suppose we\u2019re working for our logistics client, and they have just one table called <span style=\"font-family: Courier New;\">Loads<\/span>\ncontaining all of the details for the client\u2019s loads. When a logistics representative needs to change, say, a load\u2019s transportation mode, there are a few different ways to reflect their changes in the <code class=\"language-plaintext highlighter-rouge\">Loads<\/code> table.<\/p>\n\n<h2 id=\"type-i-changes\">Type I changes<\/h2>\n\n<p>Tables that using Type I changes is the easiest, but also the most naive, way to store changes in a database. Type I changes\nare just updates to existing records so that tables retain their one row = one entity rule. If the <code class=\"language-plaintext highlighter-rouge\">Loads<\/code>\ntable uses Type I changes, then one row = one load. Type I tables usually have an <code class=\"language-plaintext highlighter-rouge\">updated_by_user<\/code> and an <code class=\"language-plaintext highlighter-rouge\">updated_date<\/code> that represent \nwhich database user updated some aspect of the load, and when.<\/p>\n\n<p><strong>Example<\/strong>: suppose a <code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code> was created with a weight of 30,000 lbs, but the customer\ndecided they needed an extra 5,000 lbs shipped a couple of days later:<\/p>\n\n<p><br \/><\/p>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/type_i_update.png\" width=\"700px\" height=\"150px\" \/>\n<span>Updating a load's weight in place with a Type I change.<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<p>So Type I changes are updates in place. The main benefit of Type I changes are that they maintain the 1-1 mapping of rows to loads.\nThe drawback is that you lose the ability to track <em>history<\/em>. All you know is which user made the recent change, and when that change happened.\nWe don\u2019t necessary know <em>what<\/em> changes occurred.<\/p>\n\n<p>You could \u201cbeef up\u201d your Type I changes to apply the <code class=\"language-plaintext highlighter-rouge\">updated_by_user<\/code> and <code class=\"language-plaintext highlighter-rouge\">updated_date<\/code> concept to every field, so, adding\n <code class=\"language-plaintext highlighter-rouge\">weight_updated_by_user<\/code> and <code class=\"language-plaintext highlighter-rouge\">weight_updated_date<\/code> fields like this:<\/p>\n\n<p><br \/><\/p>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/type_i_update_obtuse.png\" width=\"1000px\" height=\"150px\" \/>\n<\/div>\n<p><br \/><\/p>\n\n<p>But this is pretty awkward. And moreover, at any given time we\u2019re only retaining the most recent change in each field, so\n  this solution is still only a half-measure towards being able to track the full changelog history of a load.<\/p>\n\n<h2 id=\"type-ii-changes\">Type II changes<\/h2>\n\n<p>Instead of updating individual records, what if we just inserted a new version of each record as those changes arrived? The Type II change\nfor our load that started at 30,000 lbs and increased to 35,000 lbs would would appear\n as a near-duplicate record, but with the updated weight and a <code class=\"language-plaintext highlighter-rouge\">effective_date<\/code> field telling us when the change was in effect.<\/p>\n\n<p><br \/><\/p>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/type_ii_insert.png\" width=\"750px\" height=\"170px\" \/>\n<span>Updating a load's weight with a Type II insert.<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<p>Leveraging Type II changes, the meaning of each record in a table has changed. No longer is one record = one entity. One record is\n one <em>version<\/em> of one entity. Now <code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code> can show up multiple times. The <em>grain<\/em> of the table has changed.<\/p>\n\n<p>We can even figure out the exact time window that each version of each record was good for by using SQL\u2019s <code class=\"language-plaintext highlighter-rouge\">lead<\/code> function\nto tie the <em>next<\/em> version\u2019s <code class=\"language-plaintext highlighter-rouge\">effective_date<\/code> at time <em>t + 1<\/em> to the version at time <em>t<\/em>. That is, a particular\nversion of an entity is only in effect until the next version of that same entity comes in at a later time. In order\nto give each version of each load a [start, end) window, we would do the following:<\/p>\n\n<p><br \/><\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-sql\" data-lang=\"sql\"><span class=\"k\">select<\/span> <span class=\"o\">*<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">effective_date<\/span> <span class=\"k\">as<\/span> <span class=\"n\">start_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">lead<\/span><span class=\"p\">(<\/span><span class=\"n\">effective_date<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">)<\/span> <span class=\"n\">over<\/span> <span class=\"p\">(<\/span><span class=\"n\">partition<\/span> <span class=\"k\">by<\/span> <span class=\"n\">load_id<\/span> <span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">effective_date<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">end_date<\/span>\n<span class=\"k\">from<\/span> <span class=\"n\">Loads<\/span>\n<span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">start_date<\/span> <span class=\"k\">asc<\/span><span class=\"p\">;<\/span><\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th>load_id<\/th>\n      <th>lane_id<\/th>\n      <th>weight<\/th>\n      <th>mode<\/th>\n      <th>start_date<\/th>\n      <th>end_date<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>30000<\/td>\n      <td>V<\/td>\n      <td>03-24-2020 17:10:19<\/td>\n      <td>03-25-2020 10:16:55<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>35000<\/td>\n      <td>V<\/td>\n      <td>03-25-2020 10:16:55<\/td>\n      <td>NULL<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>In this way, we keep track of when exactly each version of a load was in effect. A record whose <code class=\"language-plaintext highlighter-rouge\">end_date<\/code> is <code class=\"language-plaintext highlighter-rouge\">NULL<\/code> indicates that this record is the currently <em>active<\/em> record, because\nit has yet to be superseded by a more recent version.<\/p>\n\n<p>While Type II changes add costs (e.g. need for a bigger server, cloud host wants more money more for storage), this\nstrategy gives our client the ability to recreate each unique version of each load at any given point in time. \nWe have traded power for complexity, namely, in that we have made our table <em>more granular<\/em>.<\/p>\n\n<h1 id=\"joining-in-time-with-type-ii-changes\">Joining in time with Type II changes<\/h1>\n\n<p>We\u2019d like to set our client up with Type II enabled tables. But a problem has arisen. If we were previously joining\ntwo tables on a simple (primary key, foreign key) match, and if Type II changes duplicate each primary\/foreign key\nfor every distinct version of each record, then joining on keys will join every change in table 1 to every change\n in table 2! In data modeling, this is called a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Cartesian_product\">cartesian<\/a> (or cross) join, and it\u2019s a bad thing if it\u2019s not intentional.<\/p>\n\n<p>Suppose we have some sample data that includes a load (<code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code>). This load is assigned to <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code>. This load has three different versions:<\/p>\n\n<ol>\n  <li><code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code> gets created on 3\/27\/2020 with the \u2018V\u2019 (short for \u201cdry <strong>v<\/strong>an\u201d) transportation mode.<\/li>\n  <li>This load\u2019s mode gets changed on 3\/28\/2020 to \u2018R\u2019 (short for \u201c<strong>re<\/strong>frigerated\u201d).<\/li>\n  <li>Two days later (on 3\/30\/2020), a logistics representative realizes that the load is not actually a reefer load after all,\nbut still actually a dry van load.<\/li>\n<\/ol>\n\n<p>Also suppose that there are two versions of <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code>:<\/p>\n<ol>\n  <li>This lane was supposed to represent the lane between Tulsa, Oklahoma (<code class=\"language-plaintext highlighter-rouge\">city_id 10<\/code>) and Portland, Maine (<code class=\"language-plaintext highlighter-rouge\">city_id 18<\/code>). But when the lane was created\non 3\/10\/2020, it is assigned <code class=\"language-plaintext highlighter-rouge\">destination_city_id = 17<\/code>.<\/li>\n  <li>On 3\/29\/2020 a user realizes the mistake: <code class=\"language-plaintext highlighter-rouge\">city_id 17<\/code> is Portland, Oregon, not Portland, Maine. Hey, honest mistake. They\ncreate a new version of <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code> with the correct destination.<\/li>\n<\/ol>\n\n<p>Now a logistics analyst wants to join the <code class=\"language-plaintext highlighter-rouge\">Loads<\/code> and <code class=\"language-plaintext highlighter-rouge\">Lanes<\/code> tables (suppose tgat <code class=\"language-plaintext highlighter-rouge\">lane_id<\/code> is a foreign key contained in the <code class=\"language-plaintext highlighter-rouge\">Loads<\/code> table). They notice the cartesian:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-sql\" data-lang=\"sql\"><span class=\"k\">select<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"k\">mode<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">origin_city_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">destination_city_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">effective_date<\/span> <span class=\"k\">as<\/span> <span class=\"n\">load_effective_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">effective_date<\/span> <span class=\"k\">as<\/span> <span class=\"n\">lane_effective_date<\/span>\n<span class=\"k\">from<\/span> <span class=\"n\">Loads<\/span> <span class=\"n\">l<\/span>\n<span class=\"k\">inner<\/span> <span class=\"k\">join<\/span> <span class=\"n\">Lanes<\/span> <span class=\"k\">as<\/span> <span class=\"n\">ln<\/span>\n    <span class=\"k\">on<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span>\n<span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">load_effective_date<\/span> <span class=\"k\">asc<\/span><span class=\"p\">;<\/span><\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th>load_id<\/th>\n      <th>lane_id<\/th>\n      <th>mode<\/th>\n      <th>origin_city_id<\/th>\n      <th>destination_city_id<\/th>\n      <th>load_effective_date<\/th>\n      <th>lane_effective_date<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>V<\/td>\n      <td>10<\/td>\n      <td>17<\/td>\n      <td>03-27-2020 00:00:00<\/td>\n      <td>03-10-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>V<\/td>\n      <td>10<\/td>\n      <td>18<\/td>\n      <td>03-27-2020 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>R<\/td>\n      <td>10<\/td>\n      <td>17<\/td>\n      <td>03-28-2020 00:00:00<\/td>\n      <td>03-10-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>R<\/td>\n      <td>10<\/td>\n      <td>18<\/td>\n      <td>03-28-2020 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>V<\/td>\n      <td>10<\/td>\n      <td>17<\/td>\n      <td>03-30-2020 00:00:00<\/td>\n      <td>03-10-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>V<\/td>\n      <td>10<\/td>\n      <td>18<\/td>\n      <td>03-30-2020 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>All of the changes in <code class=\"language-plaintext highlighter-rouge\">Loads<\/code> are being applied to all of the changes in <code class=\"language-plaintext highlighter-rouge\">Lanes<\/code>! Since the first version of <code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code>\nis only effective between 3\/27\/2020 and 3\/28\/2020 and the updated version of <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code> is effective only starting\non 3\/29\/2020, so the original version of this load could not possibly have been tied to the updated version of the lane.<\/p>\n\n<p><br \/><\/p>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/load_lane_cartesian.png\" width=\"1100px\" height=\"140px\" \/>\n<span>Joining Type II data without using effective windows leads to undesirable cartesians.<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<h2 id=\"joining-using-effective-windows\">Joining using effective windows<\/h2>\n\n<p>Clearly, we need to be able to join not only on primary\/foreign keys but to be able to join across time. To do this,\neach <code class=\"language-plaintext highlighter-rouge\">load_id<\/code> and each <code class=\"language-plaintext highlighter-rouge\">lane_id<\/code> need an <em>effective window<\/em> explaining the time period each record is good for. There should really only be four records:<\/p>\n\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/load_123_lane_555.png\" width=\"700px\" height=\"300px\" \/>\n<span>The complete history of load_id 123 while joined to lane_id 555.<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<ul>\n  <li>(1 record) The original version of <code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code> joins to the original version of <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code><\/li>\n  <li>(2 records) The second version of <code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code> (with <code class=\"language-plaintext highlighter-rouge\">mode = 'R'<\/code>) should be joined to both versions of <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code> (with <code class=\"language-plaintext highlighter-rouge\">destination_city_id = 17<\/code> <em>and<\/em> <code class=\"language-plaintext highlighter-rouge\">18<\/code>)<\/li>\n  <li>(1 record) The final version of <code class=\"language-plaintext highlighter-rouge\">load_id 123<\/code> (returning to <code class=\"language-plaintext highlighter-rouge\">mode = 'V'<\/code>) should be joined to the final version of <code class=\"language-plaintext highlighter-rouge\">lane_id 555<\/code>.<\/li>\n<\/ul>\n\n<p>The easiest way tack on effective windows to each table is to use <a href=\"https:\/\/www.sqlshack.com\/sql-server-common-table-expressions-cte\/\">common table expressions<\/a> (CTEs). CTEs\nallow you to write and name select statements and use them as if they were database tables. Most SQL dialects support CTEs in some form. Now,\n we\u2019ll continue to join <code class=\"language-plaintext highlighter-rouge\">Loads<\/code> to <code class=\"language-plaintext highlighter-rouge\">Lanes<\/code> using <code class=\"language-plaintext highlighter-rouge\">Loads.lane_id = Lanes.lane_id<\/code>, but now we filter down to <code class=\"language-plaintext highlighter-rouge\">load_id<\/code> records whose effective windows overlap\n with corresponding <code class=\"language-plaintext highlighter-rouge\">lane_id<\/code> effective windows.<\/p>\n\n<p><br \/><\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-sql\" data-lang=\"sql\"><span class=\"k\">with<\/span> <span class=\"n\">cte_loads<\/span> <span class=\"k\">as<\/span> <span class=\"p\">(<\/span>\n    <span class=\"k\">select<\/span> <span class=\"o\">*<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">effective_date<\/span> <span class=\"k\">as<\/span> <span class=\"n\">load_start_date<\/span>\n    <span class=\"c1\">-- cast NULL effective_dates (indicating current record) to far in the future.<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">nvl<\/span><span class=\"p\">(<\/span><span class=\"n\">lead<\/span><span class=\"p\">(<\/span><span class=\"n\">effective_date<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">),<\/span> <span class=\"s1\">'2099-01-01'<\/span><span class=\"p\">::<\/span><span class=\"nb\">date<\/span><span class=\"p\">)<\/span> <span class=\"n\">over<\/span> <span class=\"p\">(<\/span><span class=\"n\">partition<\/span> <span class=\"k\">by<\/span> <span class=\"n\">load_id<\/span> <span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">effective_date<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">load_end_date<\/span>\n    <span class=\"k\">from<\/span> <span class=\"n\">Loads<\/span><span class=\"p\">)<\/span>\n    \n<span class=\"p\">,<\/span> <span class=\"n\">cte_lanes<\/span> <span class=\"k\">as<\/span> <span class=\"p\">(<\/span>\n    <span class=\"k\">select<\/span> <span class=\"o\">*<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">effective_date<\/span> <span class=\"k\">as<\/span> <span class=\"n\">lane_start_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">nvl<\/span><span class=\"p\">(<\/span><span class=\"n\">lead<\/span><span class=\"p\">(<\/span><span class=\"n\">effective_date<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">),<\/span> <span class=\"s1\">'2099-01-01'<\/span><span class=\"p\">::<\/span><span class=\"nb\">date<\/span><span class=\"p\">)<\/span> <span class=\"n\">over<\/span> <span class=\"p\">(<\/span><span class=\"n\">partition<\/span> <span class=\"k\">by<\/span> <span class=\"n\">lane_id<\/span> <span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">effective_date<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">lane_end_date<\/span>\n    <span class=\"k\">from<\/span> <span class=\"n\">Lanes<\/span><span class=\"p\">)<\/span>\n    \n<span class=\"k\">select<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"k\">mode<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">origin_city_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">destination_city_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_start_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_end_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_start_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_end_date<\/span>\n<span class=\"k\">from<\/span> <span class=\"n\">cte_loads<\/span> <span class=\"n\">l<\/span>\n<span class=\"k\">inner<\/span> <span class=\"k\">join<\/span> <span class=\"n\">cte_lanes<\/span> <span class=\"k\">as<\/span> <span class=\"n\">ln<\/span>\n    <span class=\"c1\">-- join on primary\/foreign key match<\/span>\n    <span class=\"k\">on<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span>\n    <span class=\"c1\">-- join on effective window overlap<\/span>\n    <span class=\"k\">and<\/span> <span class=\"p\">((<\/span><span class=\"n\">load_start_date<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"n\">lane_start_date<\/span> <span class=\"k\">and<\/span> <span class=\"n\">load_start_date<\/span> <span class=\"o\">&lt;<\/span> <span class=\"n\">lane_end_date<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">or<\/span> <span class=\"p\">(<\/span><span class=\"n\">load_end_date<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"n\">lane_start_date<\/span> <span class=\"k\">and<\/span> <span class=\"n\">load_end_date<\/span> <span class=\"o\">&lt;<\/span> <span class=\"n\">lane_end_date<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">or<\/span> <span class=\"p\">(<\/span><span class=\"n\">lane_start_date<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"n\">load_start_date<\/span> <span class=\"k\">and<\/span> <span class=\"n\">lane_start_date<\/span> <span class=\"o\">&lt;<\/span> <span class=\"n\">load_end_date<\/span><span class=\"p\">)<\/span>\n        <span class=\"k\">or<\/span> <span class=\"p\">(<\/span><span class=\"n\">lane_end_date<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"n\">load_start_date<\/span> <span class=\"k\">and<\/span> <span class=\"n\">lane_end_date<\/span> <span class=\"o\">&lt;<\/span> <span class=\"n\">load_end_date<\/span><span class=\"p\">))<\/span>\n<span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">load_start_date<\/span> <span class=\"k\">asc<\/span><span class=\"p\">;<\/span><\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th>load_id<\/th>\n      <th>lane_id<\/th>\n      <th>mode<\/th>\n      <th>origin_city_id<\/th>\n      <th>destination_city_id<\/th>\n      <th>load_start_date<\/th>\n      <th>load_end_date<\/th>\n      <th>lane_start_date<\/th>\n      <th>lane_end_date<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>V<\/td>\n      <td>10<\/td>\n      <td>17<\/td>\n      <td>03-27-2020 00:00:00<\/td>\n      <td>03-28-2020 00:00:00<\/td>\n      <td>03-10-2020 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>R<\/td>\n      <td>10<\/td>\n      <td>17<\/td>\n      <td>03-28-2020 00:00:00<\/td>\n      <td>03-30-2020 00:00:00<\/td>\n      <td>03-10-2020 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>R<\/td>\n      <td>10<\/td>\n      <td>18<\/td>\n      <td>03-28-2020 00:00:00<\/td>\n      <td>03-30-2020 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n      <td>01-01-2099 00:00:00<\/td>\n    <\/tr>\n    <tr>\n      <td>123<\/td>\n      <td>555<\/td>\n      <td>V<\/td>\n      <td>10<\/td>\n      <td>18<\/td>\n      <td>03-30-2020 00:00:00<\/td>\n      <td>01-01-2099 00:00:00<\/td>\n      <td>03-29-2020 00:00:00<\/td>\n      <td>01-01-2099 00:00:00<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>Now we only join together versions of loads to versions lanes that would have been possible to occur over time.<\/p>\n\n<p>What is going on in this join condition? Well, there are only four possible ways that two 2-sided windows can intersect,\nso that\u2019s what each of the lines in the <code class=\"language-plaintext highlighter-rouge\">and<\/code> join condition above are addressing:<\/p>\n\n<p><br \/><\/p>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/effective_window_overlap.png\" width=\"1000px\" height=\"200px\" \/>\n<span>The four possible ways for two effective windows to overlap.<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<p>Awesome, now our client\u2019s analysts can track the full history of all loads and lanes, and now they can even\ndo things like track how many mistakes were made on each load, or how long it took for a load to change from\nbetween any two statuses; Type II data is much richer than a naive <code class=\"language-plaintext highlighter-rouge\">updated_date<\/code> timestamp.<\/p>\n\n<p><br \/><\/p>\n\n<h2 id=\"selecting-only-currently-valid-records-from-type-ii-table-joins\">Selecting only currently-valid records from Type II table joins<\/h2>\n\n<p>The effective window join pattern presented above is great for querying the entire temporal history of changelog\ndata across separate tables, but what if we just want a current snapshot of the joined Type II tables? That is,\nwe only want joined changelog records that apply at the current moment in time, not those from the past.<\/p>\n\n<p>Logically, two joined Type II records are only valid at the current moment in time if the latest <code class=\"language-plaintext highlighter-rouge\">start_date<\/code>\nof either constituent record is <em>before<\/em> the <code class=\"language-plaintext highlighter-rouge\">current_timestamp<\/code> while simultaneously the earliest <code class=\"language-plaintext highlighter-rouge\">end_date<\/code> of either constituent\nrecord is <em>after<\/em> the current point in time.<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-sql\" data-lang=\"sql\"><span class=\"k\">with<\/span> <span class=\"n\">cte_loads<\/span> <span class=\"k\">as<\/span> <span class=\"p\">(...)<\/span>\n    \n<span class=\"p\">,<\/span> <span class=\"n\">cte_lanes<\/span> <span class=\"k\">as<\/span> <span class=\"p\">(...)<\/span>\n    \n<span class=\"k\">select<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"k\">mode<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">origin_city_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">destination_city_id<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_start_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">load_end_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_start_date<\/span>\n    <span class=\"p\">,<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_end_date<\/span>\n<span class=\"k\">from<\/span> <span class=\"n\">cte_loads<\/span> <span class=\"n\">l<\/span>\n<span class=\"k\">inner<\/span> <span class=\"k\">join<\/span> <span class=\"n\">cte_lanes<\/span> <span class=\"k\">as<\/span> <span class=\"n\">ln<\/span>\n    <span class=\"k\">on<\/span> <span class=\"n\">l<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ln<\/span><span class=\"p\">.<\/span><span class=\"n\">lane_id<\/span>\n    <span class=\"k\">and<\/span> <span class=\"n\">greatest<\/span><span class=\"p\">(<\/span><span class=\"n\">load_start_date<\/span><span class=\"p\">,<\/span> <span class=\"n\">lane_start_date<\/span><span class=\"p\">)<\/span> <span class=\"o\">&lt;=<\/span> <span class=\"k\">current_timestamp<\/span>\n    <span class=\"k\">and<\/span> <span class=\"n\">least<\/span><span class=\"p\">(<\/span><span class=\"n\">load_end_date<\/span><span class=\"p\">,<\/span> <span class=\"n\">lane_end_date<\/span><span class=\"p\">)<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"k\">current_timestamp<\/span>\n<span class=\"k\">order<\/span> <span class=\"k\">by<\/span> <span class=\"n\">load_start_date<\/span> <span class=\"k\">asc<\/span><span class=\"p\">;<\/span><\/code><\/pre><\/figure>\n\n<p>Now this query limits our results to only the version of loads that join to lanes (in time) whose joint\neffective windows include the current time. What I\u2019m describing looks like this:<\/p>\n\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"\/images\/effective_window_current_timestamp.png\" width=\"450px\" height=\"200px\" \/>\n<\/div>\n<p><br \/><\/p>\n\n<p>Now our client\u2019s logistics analysts can freely select either a completely versioned history of all loads and lanes,\n or, only what the state of loads and lanes look like at the current point in time.<\/p>\n\n<p><br \/><\/p>\n\n<h1 id=\"end\">End<\/h1>\n\n<p>Thanks for reading! Don\u2019t hesitate to get in touch if your organization is having trouble implementing, scaling, or migrating to fully-versioned data.<\/p>\n\n","pubDate":"Thu, 26 Mar 2020 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2020\/03\/26\/tracking-data-changes-over-time.html","guid":"https:\/\/ffineis.github.io\/blog\/2020\/03\/26\/tracking-data-changes-over-time.html","category":"blog"},{"title":"How bad is it? Exploring racial disparities in NCAA quarterbacking with an ETL pipeline","description":"<p>I am not an avid sports fan, let alone well-versed in the who\u2019s-who of college football. But last fall, I was at the gym while ESPN was running through clips of the morning\u2019s SEC (Southeastern Conference) games; they cycled through three games. It struck me as odd that all six teams on TV had white quarterbacks. The Fall of 2017 was the height of the kneeling NFL player phenomena, and statistics about the racial composition of the NFL were everywhere.<\/p>\n\n<p>Perhaps the most widely reported statistic surrounding the NFL and race is that the league is comprised of about 70% African American players. Colin Kaepernick really kicked off the discussion of race as it pertains to football, and he\u2019s a quarterback, which is inarguably the most important position on a football team. He was only one of the 5 starting black quarterbacks in the NFL (out of 32) in 2017. The question of racial dispairities quarterbacking is important - what does this say about what team management, football fans, and league commissioners tend to value in the person representing and commanding their respective teams?<\/p>\n\n<p><br \/><\/p>\n<div style=\"align: center; text-align:center;\">\n<img align=\"center\" src=\"https:\/\/m.media-amazon.com\/images\/M\/MV5BN2QxZTZlY2MtNWRmZS00M2Q1LWExYjAtOWZjMzM3ZDI1YjViXkEyXkFqcGdeQXVyNjcyODE2MTE@._V1_SY1000_CR0,0,666,1000_AL_.jpg\" width=\"300px\" height=\"400px\" \/>\n<span>Netflix's QB1 showcases a select few college-bound football prodigies.<\/span>\n<\/div>\n<p><br \/><\/p>\n\n<p>So let\u2019s explore it - how lopsided is white quarterbacking in D1 college football, and is it worse than the NFL? Is this a general problem affecting college football as a whole, or is it localized to certain conferences? Maybe it\u2019s just \u201ca few bad apples [teams]\u201d that tend to only have white quarterbacks? All of the SQL, Python, and R code that I\u2019m going to reference is available in my <a href=\"https:\/\/github.com\/ffineis\/ncaa_quarterbacks\">ncaa_quarterbacks GitHub repository<\/a>, go check it out!<\/p>\n\n<h2 id=\"etl-best-practices\">ETL best practices?<\/h2>\n<p>You - perhaps you\u2019re a data scientist, maybe you\u2019re a grad student - put a lot of effort into finding data sources and developing cool functions to munge websites or databases for their data, transforming it into a form that\u2019s useful for you, and then asking something important from the fruit of your labor. Are users more interested in feature A or feature B? In which neighborhoods is the rate of people swapping out public transit for rideshare?<\/p>\n\n<p>That is, you\u2019re usually engaged in some sort of data ETL process - <em>E<\/em>xtraction, <em>T<\/em>ransformation, and <em>L<\/em>oading - for the purposes of being able to answer these questions. ETL always feeds some sort of downstream analysis or someone else\u2019s data dependencies. There are lots of ways to refer to ETL processes, the nomenclature usually just changes depending on the scale of the ETL. People at companies who write the code to pull data from dozens of databases and generate reports on a recurring basis tend to call their work \u201cdata pipelining.\u201d Companies often refer to this process, which could encompass several teams, as just \u201cETL\u201d. The smaller-scale work that involves eviscerating websites for their free data is called \u201cweb scraping\u201d or \u201cweb munging,\u201d but that\u2019s usually still captured under ETL.<\/p>\n\n<p>Here are some best practices (not that I\u2019m some sort of authority) that I\u2019ve found to be useful guiding principles when managing a data pipelining project such as our college football project. Overall, scrapes (extractions) should be robust to small changes in the data source (for us, a website) and therefore modular, and other people should be able to reproduce your efforts!<\/p>\n\n<ol>\n  <li>Use a database to store your data extractions instead of keeping the fruit of your scraping labor in individual files or directories.<\/li>\n  <li>Separate your data ETL processes and code from any ensuing data analysis motivating the ETL in the first place.<\/li>\n  <li>Make your database do the heavy work of data analysis instead of the ETL code. Use R or Python to filter\/reshape\/pivot\/clean data.<\/li>\n  <li>Reuse your code. Variance between websites is not so large that every site needs its an entirely fresh codebase, and code for loading data into a database should be completely independent of the tables\/indices\/documents you\u2019re trying to modify within the database.<\/li>\n<\/ol>\n\n<h2 id=\"building-the-database\">Building the database<\/h2>\n\n<p>The best reason for maintaining your extractions in a database is so that you can maintain the relationships between the different entities in your data. 2 months from now, are you going to remember how the data in <code class=\"language-plaintext highlighter-rouge\">players_positions.csv<\/code> relates to <code class=\"language-plaintext highlighter-rouge\">teams_players.csv<\/code>? Probably not, but a decent database management tool like JetBrains\u2019 DataGrip will plot you a picture called an ER diagram, telling you how your different pieces of data fit together:<\/p>\n\n<p><br \/>\n<img align=\"center\" src=\"https:\/\/github.com\/ffineis\/ncaa_quarterbacks\/raw\/master\/etc\/college_football_db.png\" \/>\n<em>Our \u201ccollege_football\u201d MySQL database ER diagram<\/em>\n<br \/><\/p>\n\n<p>Each rectangle in the ER diagram is a table, and the arrows display primary key\/foreign key relationships - how data in one table is linked to in another table. For example, each team has players, and each player has a position. We don\u2019t need to store which player played which position on which team during which year all together in one table. We just need one table that holds references to other tables that represent (player, position, team, year) combinations. For example, maybe (player_id = 12, team_id = 4, position_id = 20, year = 2015) means \u201cKody Cook played quarterback for Kansas State in 2015.\u201d<\/p>\n\n<p>Launch the <strong>college_football<\/strong> MySQL database like this:<\/p>\n<ol>\n  <li>Make sure you have <code class=\"language-plaintext highlighter-rouge\">mysql<\/code> installed. Mac users can try installation with <code class=\"language-plaintext highlighter-rouge\">brew install mysql<\/code>.<\/li>\n  <li>Ensure your MySQL server daemon is running (<a href=\"http:\/\/osxdaily.com\/2014\/11\/26\/start-stop-mysql-commands-mac-os-x\/\">Mac instructions<\/a>)<\/li>\n  <li>Run the <code class=\"language-plaintext highlighter-rouge\">ncaa_quarterbacks\/sql\/deploy_db.sh<\/code> shell script.<\/li>\n<\/ol>\n\n<div class=\"language-bash highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"nb\">cd <\/span>ncaa_quarterbacks\/sql\n.\/deploy_db.sh &lt;your username&gt; &lt;database password&gt;\n<\/code><\/pre><\/div><\/div>\n\n<p>This will construct a database with 7 tables, one for each entity or relationship we\u2019ll need: conferences, teams, players, positions, player statistics, conference-team relationships, and team-player-position relationships.<\/p>\n\n<h2 id=\"extracting-transforming-and-loading-data-with-python\">Extracting, transforming, and loading data with python<\/h2>\n<p>Scraping a decade\u2019s worth of every college football player\u2019s performance takes a bit of time and computing power - we do have 10 years\u2019 worth of football games that span 12 conferences and include over 50,000 unique players and their performance statistics. Keeping this data in a few text files is a bad idea. But with a SQL database we can run the scrape once, load data into the database, and then query data from the database as needed. The database will enforce the relationships between players, teams, and statistics.<\/p>\n\n<p>To run an ETL job, you should have three types of code - extraction code, transformation code, and loading code. In the (<code class=\"language-plaintext highlighter-rouge\">ncaa_quarterbacks<\/code>)[https:\/\/github.com\/ffineis\/ncaa_quarterbacks] repository I\u2019ve combined the transformation code with the loading code, but the transformation code is clearly outlined and flows straight into a load into the database.<\/p>\n\n<h3 id=\"extraction--transformation-code\">Extraction + Transformation code<\/h3>\n<p>The <code class=\"language-plaintext highlighter-rouge\">ncaa_quarterbacks<\/code> extraction code lives in <code class=\"language-plaintext highlighter-rouge\">code\/scrapers<\/code>. It\u2019s easiest, if possible, to just transform your scraped data into your database\u2019s conventions right off the bat. For example, store scraped conferences in a pandas.DataFrame with a <code class=\"language-plaintext highlighter-rouge\">conference_name<\/code> column.<\/p>\n<ul>\n  <li><code class=\"language-plaintext highlighter-rouge\">conference_scrape.py<\/code> contains a function to extract the names of different conferences and the years each conference was active.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">team_scrape.py<\/code> contains a function to extract team information: names and roster URLs. Teams are nested within conferences.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">player_scrape.py<\/code> contains a function to extract players from roster URLs (players are nested within teams) and another function to extract a player\u2019s statistics once we know they\u2019re on a roster.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">run_scrape.py<\/code> is a script that iterates over each year (<a href=\"cfbstats.com\">cfbstats.com<\/a> has data starting from 2008), pulling the conferences, teams, and player information for that year. Since there are many statistics to scrape for each of the thousands of players in an NCAA football program, teams are processed in parallel for any given year. Each table is represented, for now, just as a pandas.DataFrame. All of that data is put into a dictionary (keys are years) which gets dumped to a single serialized python file. Loading code unpacks this data and sends it up to our database.<\/li>\n<\/ul>\n\n<p>Any web scraping Python code will likely center upon using the <code class=\"language-plaintext highlighter-rouge\">requests<\/code> library to download the website\u2019s contents and then using <code class=\"language-plaintext highlighter-rouge\">BeautifulSoup4<\/code> to extract the content\u2019s meaning.<\/p>\n\n<h3 id=\"loading-code\">Loading code<\/h3>\n<p>There are really only two things main tasks you\u2019ll ever be concerned with when it comes to ETL and SQL: <em>(1)<\/em> inserting new data that did not exist previously, and <em>(2)<\/em> updating old values with fresher ones. Doing either is pretty easy with the popular and foundational <code class=\"language-plaintext highlighter-rouge\">SQLAlchemy<\/code> toolkit.<\/p>\n\n<p>The way I use SQLAlchemy is <em>not<\/em> as a <a href=\"http:\/\/zetcode.com\/db\/sqlalchemy\/exprlang\/\">SQL expression language<\/a> but more simply as a means to upload\/download data and to execute raw SQL code. While this does not harnesses the full power of the SQLAlchemy toolkit, it lets me run actual SQL code, which is probably easier for most of my colleagues to understand if we haven\u2019t all been exposed to the SQLAlchemy API.<\/p>\n\n<p>The basic workflow for loading data from python into our database is pretty simple:<\/p>\n<ol>\n  <li>Move a pandas.DataFrame into the database by creating a temporary <strong>staging table<\/strong> with the <code class=\"language-plaintext highlighter-rouge\">to_sql<\/code> DataFrame method.\n<br \/><br \/><img align=\"center\" src=\"\/images\/loader_etl_process_1.png\" \/><br \/><br \/><\/li>\n  <li>Write SQL commands to either insert new data into an existing table from the staging table or to update data within an existing table from the staging table. For example, perhaps we\u2019re inserting new players into the <code class=\"language-plaintext highlighter-rouge\">players<\/code> table, or we\u2019re updating some particular (existing) players\u2019 <code class=\"language-plaintext highlighter-rouge\">hometown<\/code> data.\n<br \/><br \/><img align=\"center\" src=\"\/images\/loader_etl_process_2.png\" \/><br \/><br \/><\/li>\n  <li>Drop the staging table.<\/li>\n<\/ol>\n\n<p>All of the loader code is further wrapped within SQL transactions, so that if any part of the load fails, all changes made to the database during the transaction get automatically rolled back. Checkout the <code class=\"language-plaintext highlighter-rouge\">make_staging_table<\/code>, <code class=\"language-plaintext highlighter-rouge\">insert<\/code>, and <code class=\"language-plaintext highlighter-rouge\">update<\/code> functions within <code class=\"language-plaintext highlighter-rouge\">code\/sql\/mysql_helpers.py<\/code> for more details on the Python and SQL underlying the loading. Note the reusability of this code - for every table I want to insert new data into or to update, I really only need the <code class=\"language-plaintext highlighter-rouge\">insert<\/code> or the <code class=\"language-plaintext highlighter-rouge\">update<\/code> - this allows the loading code to be completely independent of the actual data being inserted or updated.<\/p>\n\n<h3 id=\"labeling-quarterbacks\">Labeling quarterbacks<\/h3>\n<p>The <code class=\"language-plaintext highlighter-rouge\">run_load.py<\/code> takes the .pkl file resulting from the <code class=\"language-plaintext highlighter-rouge\">run_scrape.py<\/code> scrape and loads the scraped DataFrames into the <code class=\"language-plaintext highlighter-rouge\">college_football<\/code> database. After that, I downloaded 3 photos for each of the scraped 1652 quarterbacks from Google Images with the <code class=\"language-plaintext highlighter-rouge\">run_qb_photo_scrape.py<\/code> script, and  labeled them with a binary \u201cis_caucasian\u201d variable (1 = caucasian). I put the labels in a text file and used <code class=\"language-plaintext highlighter-rouge\">mysql_helpers.py<\/code>.<\/p>\n\n<p><strong>Full disclosure<\/strong> - my labeling is based off of only a few images (and Google searches when the images were ambiguous), and my labeling could definitely be error prone! For many players it\u2019s difficult to tell whether they\u2019re caucasian, and in most of their photos they\u2019re wearing full football uniforms. This is a sensitive issue, and I fully acknowledge my inability to fully recognize someone\u2019s racial or ethnic background from such niave methods. Therefore my results are an estimate of the true level of whiteness among NCAA quarterbacks.<\/p>\n\n<h2 id=\"results\">Results<\/h2>\n\n<p>About <strong>71.1% of the quarterbacks appear to be white guys<\/strong>. If we assume that the non-African American quarterbacks from 2017 were all white guys (safe assumption - Latino and Asian quarterbacks have been few and far between), then 84.3% of the NFL quarterbacks were white. So the problem appears slightly less acute at the college level - and this pattern has held up over the last 10 years - but NCAA quarterbacking is still heavily disproportionately a white position.<\/p>\n\n<p>The Big Ten had the whitest quaterbacking, the Atlantic Athletic Conference the least white.<\/p>\n\n<p><br \/>\n<img align=\"center\" src=\"\/images\/qb_whiteness_trends.png\" width=\"600px\" height=\"500px\" \/>\n<em>Trends in per-conference QB whiteness<\/em>\n<br \/><\/p>\n\n<p>In terms of individual schools, here were the top ten most \u201cwhitely-quarterbacked\u201d teams from 2008 to 2017. All of them played exclusively white quarterbacks:<\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th style=\"text-align: center\">Team<\/th>\n      <th style=\"text-align: center\">Number of D1 QBs (2008-17)<\/th>\n      <th style=\"text-align: center\">White QBs<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td style=\"text-align: center\">Colorado State<\/td>\n      <td style=\"text-align: center\">13<\/td>\n      <td style=\"text-align: center\">13<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Old Diminion<\/td>\n      <td style=\"text-align: center\">5<\/td>\n      <td style=\"text-align: center\">5<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">UC Berkely<\/td>\n      <td style=\"text-align: center\">12<\/td>\n      <td style=\"text-align: center\">12<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Northwestern<\/td>\n      <td style=\"text-align: center\">13<\/td>\n      <td style=\"text-align: center\">13<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Central Michigan<\/td>\n      <td style=\"text-align: center\">11<\/td>\n      <td style=\"text-align: center\">11<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Washington State<\/td>\n      <td style=\"text-align: center\">10<\/td>\n      <td style=\"text-align: center\">10<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Western Michigan<\/td>\n      <td style=\"text-align: center\">11<\/td>\n      <td style=\"text-align: center\">11<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">UMAss Amherst<\/td>\n      <td style=\"text-align: center\">6<\/td>\n      <td style=\"text-align: center\">6<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Stanford<\/td>\n      <td style=\"text-align: center\">13<\/td>\n      <td style=\"text-align: center\">13<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">BYU<\/td>\n      <td style=\"text-align: center\">14<\/td>\n      <td style=\"text-align: center\">14<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>Given the Big Ten was the whitest conference, it\u2019s probably not surprising to see that 3\/10 of the states with the higest rates of white quartbacking were in the Midwest:<\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th style=\"text-align: center\">Team<\/th>\n      <th style=\"text-align: center\">Number of D1 QBs (2008-17)<\/th>\n      <th style=\"text-align: center\">White QBs<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td style=\"text-align: center\">Wisconsin<\/td>\n      <td style=\"text-align: center\">14<\/td>\n      <td style=\"text-align: center\">13<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Wyoming<\/td>\n      <td style=\"text-align: center\">11<\/td>\n      <td style=\"text-align: center\">10<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Oklahoma<\/td>\n      <td style=\"text-align: center\">28<\/td>\n      <td style=\"text-align: center\">25<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Michigan<\/td>\n      <td style=\"text-align: center\">55<\/td>\n      <td style=\"text-align: center\">49<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Arkansas<\/td>\n      <td style=\"text-align: center\">25<\/td>\n      <td style=\"text-align: center\">22<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Missouri<\/td>\n      <td style=\"text-align: center\">15<\/td>\n      <td style=\"text-align: center\">13<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Colorado<\/td>\n      <td style=\"text-align: center\">42<\/td>\n      <td style=\"text-align: center\">35<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Idaho<\/td>\n      <td style=\"text-align: center\">28<\/td>\n      <td style=\"text-align: center\">23<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Washington<\/td>\n      <td style=\"text-align: center\">22<\/td>\n      <td style=\"text-align: center\">18<\/td>\n    <\/tr>\n    <tr>\n      <td style=\"text-align: center\">Illinois<\/td>\n      <td style=\"text-align: center\">38<\/td>\n      <td style=\"text-align: center\">31<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>There\u2019s no correlation between the number of quarterbacks a school had (which is a heuristic measure of the size of the program), and the level of whiteness of their quarterbacks. Really, the only D1 team with racially equitable quarterbacking is the University of Arizona with only 5 white quarterbacks out of their aggregate 15.<\/p>\n\n<p><br \/>\n<img align=\"center\" src=\"\/images\/qb_whiteness_distro.png\" width=\"670px\" height=\"400px\" \/>\n<em>Distribution of QB whiteness across schools<\/em>\n<br \/><\/p>\n\n<p>In terms of sheer numbers, nobody messes with Texas. They had 168 D1 QBs, 121 of whom were labeled caucasian (72%, so, about average). Ohio was a distant second with 92 quarterbacks, 58 of whom were caucasian (63%).<\/p>\n\n<p><br \/>\n<img align=\"center\" src=\"\/images\/qb_whiteness_michigan.png\" width=\"600px\" height=\"500px\" \/>\n<em>Per-state QB whiteness<\/em>\n<br \/><\/p>\n\n<p>The fact that Michigan had 49 white quarterbacks out of a state aggregated 55 is strange given the number of (pretty high profile) D1 programs: U Mich, Michigan State, Western Michigan, Eastern and Central Michigan. Each one of these programs staffed at least 80% white quarterbacks, despite being some of the most high-profile, <a href=\"https:\/\/ftw.usatoday.com\/2016\/01\/the-6-craziest-jim-harbaugh-recruiting-stories-that-we-know-of\">heavily recruiting<\/a> football programs in the nation.<\/p>\n\n<h4 id=\"unsolicited-opinions-beyond-code-etl\">Unsolicited opinions beyond code, ETL<\/h4>\n<p>This analysis is really just an executive summary, and someone could make the argument that the rate of white quarterbacking needs to be put in context with the rest of the team - would it really be that unfair for a team that\u2019s 80% white guys to have a white quarterback? Would it be unfair for a team without much of a recruiting budget, located in a predominately white area (e.g. Idaho) to have exclusively white quarterbacks? I\u2019d love to have program revenue or budget data to study the impact of football program funding (which would serve as a proxy for recruitment ability) on average QB whiteness.<\/p>\n\n<p>But at the end of the day, the vast majority or QBs are (very disproportionately) white, and I think that most reasonable people would agree that this isn\u2019t a good thing. Does this problem start at the college level? Definitely not. This is completely anecdotal, but for anyone interested, I highly recommend watching Netflix\u2019s original series \u201c<a href=\"https:\/\/www.imdb.com\/title\/tt5771332\/\">QB1<\/a>\u201d. To me, it highlights how much it takes beyond just pure athleticism to become a star college quarterback. Tate Martell\u2019s entire family (one of three featured QBs in season 1) moved to Las Vegas just so he could play at in an elite high school football program. White quarterbacking at the college level is probably just as much a reflection of the racial wealth gap and other forms of systemic and historic racism as it is anything else. A symptom of a larger problem.<\/p>\n\n<p>But at the very least, I\u2019d like to posit that it\u2019s on the wealthy, enormous football programs (if not the NCAA itself) to fund youth quarterback mentoring programs with diverse young quarterbacks. If we\u2019re not going to pay elite football players, the least we can do is demand that publicly-funded programs dedicate resources that will make their teams 10, 20, and 30 years out more equitable.<\/p>\n\n","pubDate":"Sat, 24 Feb 2018 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2018\/02\/24\/college_football.html","guid":"https:\/\/ffineis.github.io\/blog\/2018\/02\/24\/college_football.html","category":"blog"},{"title":"The Case for Big Brother in Big Data","description":"<h3 id=\"garbage-in-garbage-out\">Garbage in, garbage out<\/h3>\n\n<p>Data Scientists usually wear the messiness of the data they work with as a badge of honor. And they should! It\u2019s not easy to take just any dataset and shape it into something that you can build a predictive model out of, or even just craft some sort of executive-level quantitative report. But when the task is training a model to deploy on real-time data, Data Scientists need to make sure their data was intended for more than a one-off type of analysis. We should demand structure.<\/p>\n\n<p>Here is an impression of a dataset a Data Scientist might see in the wild -<\/p>\n\n<table>\n  <caption>Made up lawnmower data. Can anyone else relate to this?<\/caption>\n  <thead>\n    <tr>\n      <th>ser_no<\/th>\n      <th>last_updated<\/th>\n      <th>trbd<\/th>\n      <th>price<\/th>\n      <th>id<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>U542<\/td>\n      <td>1900\/01\/01 00:00:99<\/td>\n      <td>K1242<\/td>\n      <td>245.88<\/td>\n      <td>342198<\/td>\n    <\/tr>\n    <tr>\n      <td>KT294<\/td>\n      <td>2017-09-10<\/td>\n      <td>K1242<\/td>\n      <td>232.98<\/td>\n      <td>342198<\/td>\n    <\/tr>\n    <tr>\n      <td>hello<\/td>\n      <td>NULL<\/td>\n      <td>test -- hold for Jim<\/td>\n      <td>112.23<\/td>\n      <td>342198<\/td>\n    <\/tr>\n    <tr>\n      <td><\/td>\n      <td>NULL<\/td>\n      <td>yes<\/td>\n      <td><\/td>\n      <td>342198<\/td>\n    <\/tr>\n    <tr>\n      <td>serial_no_234<\/td>\n      <td>Tuesday<\/td>\n      <td>KT234<\/td>\n      <td>112.23<\/td>\n      <td>342198<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>Maybe the people who supplied you this lawnmower data don\u2019t know what the <em>trbd<\/em> field means, because their DBA who quit in 2011 designed their Salesforce database. Maybe your manager wants you to use this to build a model to predict lawnmower prices based on weather patterns, but nobody can tell you if <code class=\"language-plaintext highlighter-rouge\">last_updated<\/code> can safely be interpreted as when each lawnmower was sold, which is pretty crucial if you\u2019re going to try to join historical weather conditions to this price data.<\/p>\n\n<p>My point is that unstructured, free-text data can quickly lead to the \u201cgarbage in, garbage out\u201d phenomena.<\/p>\n\n<p><img src=\"http:\/\/alison.dbsdataprojects.com\/wp-content\/uploads\/sites\/82\/2016\/04\/cartoon-metadata.png\" alt=\"Dilbert\" \/><\/p>\n\n<p><br \/><\/p>\n\n<p>For supervised learning models, we can only expect a model to perform as well as quality of the labeled data used for training. If we don\u2019t have a clue what separates a cat from a dog sample, your model is doomed, because evaluation metrics are now meaningless. More humans can help. Humans can make heuristics to label our data. We can use Amazon Turk to get many humans to help label our data, and humans can send data to other (human) subject matter experts for label verification. But does that not defeat the entire notion of machine learning, that data needs to pass under the nose of a human before we can learn anything interesting from it?<\/p>\n\n<p><br \/><\/p>\n\n<h3 id=\"big-government-is-your-friend\">Big government is your friend<\/h3>\n\n<p>We should demand more from our data, and the government can help demand it. Take the electrical grid. The Federal Engery Regulatory Commission (FERC) has an immense set of guidelines for electricity producers and transmission owners when it comes to reporting how much energy was produced and transmitted across the grid. For example, FERC requires that all electric utility companies (e.g. ones that power entire towns, cities, or regions) have to complete the <a href=\"https:\/\/www.eia.gov\/electricity\/2008forms\/906-923crosswalk.xls\">Energy Information Administration\u2019s Form 906<\/a> whereby the utilities have to outline exactly how much of what types of fuels each electricity plant used over the last year. Even the units of fuel are prespecified to a selection of either \u201ctons,\u201d \u201cbarrels,\u201d or \u201cthousands of cubic feet.\u201d Now, Data Scientists won\u2019t need to guess the units used, or, god forbid, call the power plant and find the person who filled out the EIA 906 form to ask them about units. FERC has enforced reasonable standards in our public data, and this benefits Data Scientists by allowing us to build models that can leverage the EIA 906 form for any major electrical plant in the country, not just the handful that would have included units of input energy without the data guidelines. Do you really think electric utility companies would just uniformly supply the units of fuel used at their plants, by themselves?<\/p>\n\n<table>\n  <caption>EIA 906 data for electricity utilties. A Data Scientist's dream.<\/caption>\n  <thead>\n    <tr>\n      <th>PLANT NAME<\/th>\n      <th>PLANT ID<\/th>\n      <th>STATE<\/th>\n      <th>PRIME MOVER TYPE<\/th>\n      <th>ENERGY SOURCE<\/th>\n      <th>GROSS GENERATION (Mwh)<\/th>\n      <th>NET GENERATION (Mwh)<\/th>\n      <th>UNITS (Tons, Barrels, or 1000s tons)<\/th>\n      <th>STOCKS AT END OF PERIOD<\/th>\n      <th>HEAT CONTENT PER UNIT OF FUEL (Million Btu)<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>Sunapee<\/td>\n      <td>AP123<\/td>\n      <td>HIe<\/td>\n      <td>Diesel engine<\/td>\n      <td>Diesel fuel<\/td>\n      <td>100.1<\/td>\n      <td>12.5<\/td>\n      <td>Barrels<\/td>\n      <td>34.1<\/td>\n      <td>6832.22<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p><br \/><\/p>\n\n<p>The government has solved so many other huge data headaches simply by enforcing similar data schemas. What if any publicly-traded company was able to report their annual earnings using a report template they created themselves? Apple would use one set of profit reporting guidelines while Ford used another and IBM used another one, and none of the reports would look the same. Instead, the Securities and Exchange Commission makes everyone use a 10-k form. What if there were no standards for reporting daily trading volume, high, low, and closing stock prices? We all benefit immensely from having agreed-upon and enforced data schemas.<\/p>\n\n<p>Take just the example of a Vehicle Identificaion Number (VIN). All cars have one, and it\u2019s a standard enforced by the International Organization for Standardization - a body run by the UN, the definition of \u201cbig government.\u201d Any Data Scientist should immediately appreciate the VIN - it\u2019s an immutable, easily-interpreted primary key. If you have access to a car\u2019s VIN, you have a unique identifier for any car in addition to information about the car\u2019s characteristics that is vendor-agnostic. Without some sort of ISO convention for unique automobiles, any type of cross-vehicle make comparison would be a nightmare of ad hoc rules about what constitues an SUV, or fixing discrepancies between auto manufacturers that track the age of each car based on the year it came off of the assembly line versus manufacturers that track age based on a car\u2019s model year.<\/p>\n\n<p><br \/><\/p>\n\n<h3 id=\"the-point\">\u2026the point?<\/h3>\n\n<p>I only say all of this for two reasons - (1) to defend the notion that the government does do useful things and (2) because I believe that the industries most ripe for distruption by the Internet of Things (IoT) analytics are those that are in some way overseen by some type of governmental or regulatory body. Left to their own devices, groups of competing entities building things like sensors, valves, power plants, or automobiles would most likely just create their own data and reporting conventions. This creates obstacles in letting fully human-independent machine learning take root in a way that easily scales across an industry. When \u201cbig brother\u201d is around to nudge everyone to create, at the very least, data that vaguely resembles everyone else\u2019s data, this unlocks doors in terms of the scope of problems upon which Data Scientists can hope to deploy machine learning solutions.<\/p>\n\n","pubDate":"Wed, 13 Sep 2017 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2017\/09\/13\/case_for_big_govt.html","guid":"https:\/\/ffineis.github.io\/blog\/2017\/09\/13\/case_for_big_govt.html","category":"blog"},{"title":"Meet the Greebles. (In pursuit of alternative deep learning tutorial set)","description":"<h3 id=\"tired-of-mnist\">Tired of MNIST?<\/h3>\n\n<p>Most aspiring data scientists have at least heard of neural networks and \u201cdeep learning\u201d by now, and you\u2019ve probably noticed that deep learning has been getting really high-profile coverage, especially with the advent of self-driving cars and Google DeepMind\u2019s AlphaGo program that <a href=\"https:\/\/deepmind.com\/alpha-go.html\">beat a professional Go player<\/a> in March, 2016.<\/p>\n\n<p>Not wanting to miss out on the trend, I began reading blog posts, tutorials, and doc pages on the mathematical foundations of different types of neural networks, and of course, how the hell to implement one. I definitely suggest Andrew Ng\u2019s Coursera course, <a href=\"https:\/\/www.coursera.org\/learn\/machine-learning\">\u201cMachine Learning\u201d<\/a> for an in-depth treatment of multi-layer perception neural networks. Most of the bleeding-edge neural network programming frameworks available to your typical data scientist are, not surprisingly, in Python. Here are a few of the deep learning tools I\u2019ve read about:<\/p>\n\n<ol>\n  <li><a href=\"http:\/\/keras.io\/\">Keras<\/a><\/li>\n  <li><a href=\"https:\/\/www.tensorflow.org\/\">TensorFlow<\/a><\/li>\n  <li><a href=\"http:\/\/deeplearning.net\/software\/theano\">Theano<\/a><\/li>\n  <li><a href=\"https:\/\/github.com\/Lasagne\/Lasagne\">Lasagne<\/a><\/li>\n  <li><a href=\"https:\/\/github.com\/dnouri\/nolearn\">nolearn<\/a><\/li>\n<\/ol>\n\n<p>These offerings range from full-scale Python libraries that allow you to write every aspect of a deep net from scratch (e.g. Theano) to smaller libraries (e.g. nolearn)that offer wrappers to deep learning backends like Theano and TensorFlow. R hosts many neural network packages too, but since so much of deep learning is focused on GPU computing (using graphical processing units to handle model training), most of the DIY deep learning world is centered in Python.<\/p>\n\n<p>Deep learning is a huge field, and I\u2019ve just begun to scratch the surface. Fortunately, there are dozens, probably hundreds of tutorials out there that will give you the illusion of letting you feel like you know what you\u2019re doing. Basically all of the Python offerings are open source, so you\u2019ll naturally be invited to a host of different tutorials, which is ten thousand times A GREAT THING. The only downside is, you\u2019ll be classifying the MNIST numbers over and over.<\/p>\n\n<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/MNIST_database\">MNIST<\/a> numbers is a fully labeled set of 60,000 training and 10,000 test images, the images being handwritten digits, 0 through 9. Almost every intro to deep learning tutorial out there revolves around training a neural network on the training set and then minimizing the misclassification error of the test set. Very quickly you can have a model that only misclassifies about 33\/10,000 digits, and the misclassified digits were poorly written in the first place:<\/p>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/misclassified_mnist_pics.png\" class=\"inline\" width=\"600px\" height=\"200px\" \/><\/p>\n\n<p>While the MNIST set is big enough to merit GPU computing, I\u2019m more interested in learning about neural network architectures first, not so much GPU computing. Thus, a set of 60,000 images pertaining to 10 separate classes is over-kill for me. I want to run a homemade example.<\/p>\n\n<h3 id=\"why-deep-learning\">Why deep learning?<\/h3>\n\n<p>The MNIST numbers are a great resource, no doubt, but these tutorials centered on classifying the MNIST set can easily mask the complexity and patietence required to build a high-perforant deep network. Jumping in with an MNIST tutorial might make you forget why we\u2019re even using neural networks in the beginning.<\/p>\n\n<p>The underlying reason why we use a neural net with images (either multi-layer perceptron networks, convolutional neural nets, or maybe even autoencoders) is that they let us learn really good image bases in an unsupervised way. That\u2019s the goal in most of machine learning, deriving bases (simple representations, the LEGOS, if you will) that comprise the objects in your training set. For example, here are some of the bases learned for the MNIST training set while training a multi-layer perceptron model:<\/p>\n\n<p align=\"center\">\n<img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/mnist_weights.png\" class=\"inline\" width=\"400px\" \/>\n<\/p>\n\n<p>That\u2019s it. I mean, that\u2019s the biggest reason - deep nets learn really good bases that aren\u2019t confined to being linear combinations of the original pixel features (like PCA), or convex combinations of pixel features (like archetypal analysis), but seemingly arbitrarily complex, non-linear transformations of pixel features in the training set.<\/p>\n\n<h3 id=\"outstanding-questions-that-i-have-about-deep-learning\">Outstanding questions that I have about deep learning:<\/h3>\n\n<p>Many things about deep learning go unaddressed in a typical walkthrough to a new deep learning framework like a Keras or a Theano. Here are a few questions I\u2019ll hope to explore on my own that I feel are important to understanding deep learning as a tool and not a solution.<\/p>\n\n<ol>\n  <li>\n    <p>What are the dimensionality constraints for training a multi-layer perception model? Is it even possible to train a model using less than a few thousand training examples? Is there a ratio of <strong>n<\/strong> (training examples) to <strong>p<\/strong> (feature dimension) beyond which an MLP or a convolutional neural network would be particularly easy to train?<\/p>\n  <\/li>\n  <li>\n    <p>Is there a way to assess statistical significance using a neural net - e.g., can I get something like a standard error for the coefficients in a weights matrix between two layers of an MLP?<\/p>\n  <\/li>\n  <li>\n    <p>Besides bootstrapping or cross-validation, can I get some sort of confidence interval around the predictions coming out of, say, a deep net used for multi-class classification?<\/p>\n  <\/li>\n<\/ol>\n\n<h3 id=\"meet-the-greebles\">Meet the Greebles<\/h3>\n\n<p>Greebles look exactly how they sound, as in, they\u2019re purple minions with weird phallic horns:<\/p>\n\n<p align=\"center\">\n<img src=\"https:\/\/classconnection.s3.amazonaws.com\/261\/flashcards\/472261\/png\/greebles.png\" class=\"inline\" \/>\n<\/p>\n\n<p>\u201cMale\u201d greebles have concave-up horns and \u201cfemale\u201d greebles have concave-down horns; they\u2019re commonly used in psychological studies related to facial and object recognition, and according to Wikipedia they\u2019re commonly found in psychology textbooks. In my <a href=\"https:\/\/github.com\/fineiskid\/Greeble_image_learning\">greebles repo<\/a>, you\u2019ll find 160 color greeble images with 84 males and 76 females that I got from Carnegie Mellon\u2019s <a href=\"http:\/\/wiki.cnbc.cmu.edu\/Novel_Objects\">TarrLab<\/a>.<\/p>\n\n<p>In the coming tutorials, I\u2019m going to see how well I can train a host of models, including a couple of deep-nets, to classify greebles by \u201cgender\u201d. There is a \u201cgreeble generator\u201d available through the TarrLab too, should we need a bigger set for training. But overall, I\u2019m lucky to just have such a solid set of labeled, uniformly positioned, shaped, and colored images, all of which make the MNIST set such a good resource.<\/p>\n\n<h3 id=\"what-ill-explore-with-greebles\">What I\u2019ll explore with greebles<\/h3>\n\n<ul>\n  <li><strong>Greeble decompositions:<\/strong> PCA \u201ceigengreeble\u201d decomposition, non-negative matrix factorization, archetypal\/prototypical analyses<\/li>\n  <li><strong>Logistic and kernel-based<\/strong> classification methods<\/li>\n  <li><strong>Multi-layer perceptron<\/strong> neural nets<\/li>\n  <li><strong>Convolutional<\/strong> neural nets<\/li>\n  <li><strong>Autoencoders:<\/strong> similar to PCA, the autoencoder finds a low-rank approximation to an input<\/li>\n<\/ul>\n\n<h3 id=\"greeble-decomposition-tutorial\">Greeble decomposition <a href=\"https:\/\/github.com\/fineiskid\/Greeble_image_learning\/blob\/master\/greeble_decompositions.ipynb\">tutorial<\/a><\/h3>\n\n<p>To get started, check out the <a href=\"https:\/\/github.com\/fineiskid\/Greeble_image_learning\/blob\/master\/greeble_decompositions.ipynb\">tutorial<\/a> I\u2019ve posted in my greebles repository for how to get started loading the greeble images, and how to start reducing the dimension of the initial feature space. Each greeble .tif file is 360 pixels by 320 pixels, so we have 160 greebles with each 115200 interesting features. No learning algorithm is going to be able to swim in such a high-dimensional situation, so I\u2019ve used principal component analysis and non-negative matrix factorization as ways to reduce the dimension of our greeble set prior to fitting a classification model.<\/p>\n\n","pubDate":"Wed, 01 Jun 2016 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2016\/06\/01\/Greeble_decomposition.html","guid":"https:\/\/ffineis.github.io\/blog\/2016\/06\/01\/Greeble_decomposition.html","category":"blog"},{"title":"tl;dr Intro to Bayesian Statistics","description":"<h3 id=\"youve-heard-of-the-debate\">You\u2019ve heard of the debate<\/h3>\n<p>All data scientists have heard of the famous <em>frequentist-Bayesian controversy<\/em>.\nIf you\u2019re like me, when you\u2019re asked the question, \u201cBayesian or a frequentist?\u201d\nyou just say \u201cfrequentist\u201d because you\u2019re just guessing that Bayesian statistics\nhas something to do with Bayes\u2019 Theorem, and you haven\u2019t used Bayes\u2019 Theorem\nsince college when you had the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Monty_Hall_problem\">Monty-Hall\nproblem<\/a> on your homework. Am\nI alone? Quite possibly.<\/p>\n\n<p>Anyways, the other day I finally came across an excellent, (potentially) real-\nworld situation that clearly illustrates the difference between a Bayesian\noutlook and the frequentist outlook.<\/p>\n\n<h3 id=\"the-set-up\">The set-up<\/h3>\n<p>Just in case you\u2019re a lawyer, this example is entirely fictional and is taken\ndirectly from <em>Bayesian Methods for Data Analysis<\/em> by Carlin and Louis, and all\ncharacters and companies are fictious, any seeming correspondence to actual\npeople and companies is purely a coincidence. Here\u2019s the set-up: it\u2019s November\n2015, just a few weeks before Shmerger King starts wants to start selling\nhotdogs. You\u2019re a hotshot consultant hired to test whether or not people prefer\nhotdogs made out of mice (<strong>case A<\/strong>) or hotdogs made out of cats (<strong>case B<\/strong>).<\/p>\n\n<p>Because of your time constraint, you were only able to (randomly) gather 25\npeople to sign up for your study. Here\u2019s your study: each person gets two\nhotdogs, one made out of mice and one made out of cats (the subjects don\u2019t know\nwhich hotdog is which), and you need to assess the probability that people\ngenuinely prefer mice hotdogs (case A), and we\u2019re going to call this \\(\\theta\\).\nYou ran the experiment and 20 people said they prefer mice hotdogs. So\u2026 what\ndo you tell Shmerger King? What if this 80% mice hotdog preference was a fluke?<\/p>\n\n<h3 id=\"bayes-frequentist-debate-summed-up\">Bayes-frequentist debate summed up<\/h3>\n<p><strong>Frequentists<\/strong> will say this: \\(\\theta\\) is the average fraction of people that\nprefer mice hotdogs to cat hotdogs if you ran the experiment infinity times. If\nnot infinity times, then at least like, a bunch of times. There\u2019s not enough\ntime to repeat this experiment over and over hotshot!<\/p>\n\n<p><strong>Bayesians<\/strong> will say this:\n\\(\\text{Pr}(\\theta|data) \\propto \\text{likelihood}(data|\\theta)\\times\\text{Pr}(\\theta)\\)<\/p>\n\n<p>Bayesians call \\(\\text{Pr}(\\theta | data)\\) the <strong>posterior probability<\/strong> of\n\\(\\theta\\) . Now, it\u2019s up to you, the hotshot consultant, to postulate both a\n<em>likelihood<\/em> function that specifies the probability of the data given some\nvalue of \\(\\theta\\) and a <em>prior<\/em> distribution for \\(\\theta\\) itself.<\/p>\n\n<h3 id=\"not-that-bad\">Not that bad<\/h3>\n<p>Yeah, ok, Bayesians have to specify the likelihood function of the data and the\nprior for the missing parameter. Frequentists don\u2019t do this. But for this\nexperiment, specifying a likelihood is pretty easy: Clearly, each subject\u2019s\nresponse should be independent from each of the other 24 subjects\u2019 response, and\nsince there are just two outcomes, \u201cmice hotdog preference\u201d or \u201ccat hotdog\npreference,\u201d the likelihood really lends itself to a binomial distribution. This\nis to say, if \\(\\theta\\) takes on some value, say 0.75, then the probability that\n20\/25 people will prefer the mice hotdogs is a lot higher than if \\(\\theta =\n0.3\\).<\/p>\n\n<p>Priors are a little bit more complicated, because as a hotshot consultant you\nhave to think about <em>what you genuinely believe<\/em> about the distribution of\n\\(\\theta\\). Maybe you think that people will really like the mice hotdogs because\nthere\u2019s some literature out there about people eating mice. Maybe you have zero\ninformation about people\u2019s preferences. Maybe you\u2019re skeptical and you think\nthat people won\u2019t be able to tell the difference between the hotdogs, suggesting\nthat \\(\\theta\\) is probably centered around 0.5. A good pick for a prior\ndistribution would be the beta distribution because it\u2019s really malleable, and\nit\u2019s actually a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Conjugate_prior\">conjugate prior<\/a>\nto the binomial distribution. More on conjugate priors below.<\/p>\n\n<h3 id=\"envisioning-likelihood\">Envisioning likelihood<\/h3>\n\n<p>The likelihood function defines the probability of observing the data (20 mice\nhotdog preferences in 25 trials) under a particular value of \\(\\theta\\). Below, we\ncan see that if \\(\\theta = 0.8\\) (the frequentist estimate), there\u2019s a much higher\nprobability that we see 20\/25 mice hotdog preferences as opposed to when \\(\\theta\n= 0.3\\). If we kept going down this path, we\u2019d probably just pick \\(\\theta = 0.8\\)\nbecause this is the parameter estimate that <em>maximizes likelihood<\/em>.<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-python\" data-lang=\"python\"><span class=\"kn\">from<\/span> <span class=\"nn\">scipy.stats<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">binom<\/span><span class=\"p\">,<\/span> <span class=\"n\">beta<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">numpy<\/span> <span class=\"k\">as<\/span> <span class=\"n\">np<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">matplotlib.pyplot<\/span> <span class=\"k\">as<\/span> <span class=\"n\">plt<\/span>\n<span class=\"o\">%<\/span> <span class=\"n\">matplotlib<\/span> <span class=\"n\">inline<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">seaborn<\/span> <span class=\"k\">as<\/span> <span class=\"n\">sns<\/span><span class=\"p\">;<\/span> <span class=\"n\">sns<\/span><span class=\"p\">.<\/span><span class=\"nb\">set<\/span><span class=\"p\">()<\/span>\n\n<span class=\"n\">fig<\/span><span class=\"p\">,<\/span> <span class=\"n\">ax<\/span> <span class=\"o\">=<\/span> <span class=\"n\">plt<\/span><span class=\"p\">.<\/span><span class=\"n\">subplots<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"n\">figsize<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"mi\">11<\/span><span class=\"p\">,<\/span><span class=\"mi\">8<\/span><span class=\"p\">])<\/span>\n\n<span class=\"n\">n<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">25<\/span>\n<span class=\"n\">p1<\/span> <span class=\"o\">=<\/span> <span class=\"mf\">0.8<\/span><span class=\"p\">;<\/span> <span class=\"n\">p2<\/span> <span class=\"o\">=<\/span> <span class=\"mf\">0.3<\/span>\n<span class=\"n\">x<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">arange<\/span><span class=\"p\">(<\/span><span class=\"mi\">30<\/span><span class=\"p\">)<\/span> <span class=\"c1\">#Note that binomial distribution is discrete.\n<\/span><span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">,<\/span> <span class=\"n\">binom<\/span><span class=\"p\">.<\/span><span class=\"n\">pmf<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"p\">,<\/span> <span class=\"n\">p1<\/span><span class=\"p\">),<\/span> <span class=\"s\">\"b\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"theta = 0.8\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">,<\/span> <span class=\"n\">binom<\/span><span class=\"p\">.<\/span><span class=\"n\">pmf<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"p\">,<\/span> <span class=\"n\">p2<\/span><span class=\"p\">),<\/span> <span class=\"s\">\"r\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"theta = 0.3\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">legend<\/span><span class=\"p\">(<\/span><span class=\"n\">loc<\/span><span class=\"o\">=<\/span><span class=\"s\">'best'<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_title<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Likelihood under different thetas\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_xlabel<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Population ratio of (Mice preferences)\/(Cat preferences)\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_ylabel<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Density\"<\/span><span class=\"p\">)<\/span><\/code><\/pre><\/figure>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/burgers_likelihood_curves.png\" class=\"inline\" \/><\/p>\n\n<h3 id=\"envisioning-the-prior\">Envisioning the prior<\/h3>\n\n<p>The prior distribution for \\(\\theta\\) allows you, the hotshot consultant, to\ninject your underlying believe about \\(\\theta\\), which is the proportion of all of\nShmurger King\u2019s clientelle that really prefers mice hotdogs to cat hotdogs, the\nthing you\u2019re trying to pin down.<\/p>\n\n<p>The beta distribution is a natural fit for the prior here:<\/p>\n<ul>\n  <li>its support (the domain of values you can plug into the beta probability\ndistribution function) is [0,1]<\/li>\n  <li>Through its two parameters, \\(\\alpha\\) and \\(\\beta\\) (in Bayesian statistics, the\nparameters of your prior are called <em>hyperparameters<\/em>, the shape of the beta\ndistribution is highly configurable<\/li>\n  <li>It\u2019s the conjugate prior distribution to the binomial distribution (so, our\nlikelihood function), which means that the posterior distribution (i.e.\n\\(Pr(\\theta | data)\\)) is also a beta distribution, just with different parameters\nthan the prior. That\u2019s what <em>conjugacy to the likelihood<\/em> means, that your\nposterior distribution is of the same type as your prior.<\/li>\n<\/ul>\n\n<h4 id=\"what-do-you-think\">What do you think?<\/h4>\n<p>Bayesian statistics lets us inject our subjective beliefs into our models.\nPerhaps, you think one of the following statements is true:<\/p>\n\n<ul>\n  <li>(1) You have absolutely no idea whether or not people prefer mice hotdogs over\ncat hotdogs<\/li>\n  <li>(2) You think it\u2019s likely that people won\u2019t be able to tell the difference, so\n\\(\\theta\\) tends to be around 0.5<\/li>\n  <li>(3) You think that people will either really love or really hate mice hotdogs,\nso \\(\\theta\\) will likely take on extreme values.<\/li>\n<\/ul>\n\n<p>With the beta(1,1), beta(0.5, 0.5), and beta(2,2) distributions, respectively,\nwe can emulate those scenarios:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-python\" data-lang=\"python\"><span class=\"n\">fig<\/span><span class=\"p\">,<\/span> <span class=\"n\">ax<\/span> <span class=\"o\">=<\/span> <span class=\"n\">plt<\/span><span class=\"p\">.<\/span><span class=\"n\">subplots<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"n\">figsize<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"mi\">11<\/span><span class=\"p\">,<\/span><span class=\"mi\">8<\/span><span class=\"p\">])<\/span>\n\n<span class=\"c1\">## Define vector of potential theta values\n<\/span><span class=\"n\">theta<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">linspace<\/span><span class=\"p\">(<\/span><span class=\"mi\">0<\/span><span class=\"p\">,<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"mi\">100<\/span><span class=\"p\">)<\/span>\n\n<span class=\"c1\">## Plot prior distributions\n<\/span><span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">pdf<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">),<\/span> <span class=\"s\">\"b\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"beta(1,1)\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">pdf<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"mf\">0.5<\/span><span class=\"p\">,<\/span> <span class=\"mf\">0.5<\/span><span class=\"p\">),<\/span> <span class=\"s\">\"r\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"beta(0.5,0.5)\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">pdf<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"mi\">2<\/span><span class=\"p\">,<\/span> <span class=\"mi\">2<\/span><span class=\"p\">),<\/span> <span class=\"s\">\"DarkOrange\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"beta(2,2)\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">legend<\/span><span class=\"p\">(<\/span><span class=\"n\">loc<\/span><span class=\"o\">=<\/span><span class=\"s\">'best'<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_title<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Different prior parameterizations\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_xlabel<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Theta\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_ylabel<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Density\"<\/span><span class=\"p\">)<\/span><\/code><\/pre><\/figure>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/burgers_priors.png\" class=\"inline\" \/><\/p>\n\n<h3 id=\"putting-it-together-the-posterior\">Putting it together: the posterior<\/h3>\n\n<p>Since the beta distribution is the conjugate prior to the binomial likelihood\nfunction (no derivation here), the posterior is also a beta distribution, only\nnow \\[\\alpha = \\alpha_{prior} + \\text{successes}\\] and \\[\\beta =\\beta_{prior} + n -\n\\text{successes}\\]\nThe derivation of the posterior\u2019s parameters involves multiplying the beta prior and binomial likelihood functions together,\nit\u2019s a big drawn out process. As a hotshot consultant, you\u2019d probably just want\nto consult mathematica, Google, or the <em>Bayesian Methods for Data Analysis<\/em>\nbook. The main point is that the posterior distribution is just a reparameterization of the prior! That\u2019s why people like conjugate priors.<\/p>\n\n<p>Anyway, the main point is that our choice of hyperparameters (i.e. how we\nparameterized the prior), will affect the posterior distribution. In plotting\nthe resultant posterior distributions of \\(\\theta\\), notice that your choice for\nhyperparameters really doesn\u2019t change the shape or location of the posterior!<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-python\" data-lang=\"python\"><span class=\"n\">fig<\/span><span class=\"p\">,<\/span> <span class=\"n\">ax<\/span> <span class=\"o\">=<\/span> <span class=\"n\">plt<\/span><span class=\"p\">.<\/span><span class=\"n\">subplots<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"n\">figsize<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"mi\">11<\/span><span class=\"p\">,<\/span><span class=\"mi\">8<\/span><span class=\"p\">])<\/span>\n\n<span class=\"c1\">## Observed data: number of successes\n<\/span><span class=\"n\">success<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">20<\/span>\n\n<span class=\"c1\">## Plot posteriors\n<\/span><span class=\"n\">one_postr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">pdf<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"o\">+<\/span><span class=\"n\">success<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"o\">-<\/span><span class=\"n\">success<\/span><span class=\"o\">+<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">five_postr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">pdf<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"mf\">0.5<\/span><span class=\"o\">+<\/span><span class=\"n\">success<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"o\">-<\/span><span class=\"n\">success<\/span><span class=\"o\">+<\/span><span class=\"mf\">0.5<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">two_postr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">pdf<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"mi\">2<\/span><span class=\"o\">+<\/span><span class=\"n\">success<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"o\">-<\/span><span class=\"n\">success<\/span><span class=\"o\">+<\/span><span class=\"mi\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"n\">one_postr<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"b\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"Posterior w\/ beta(1,1) prior\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"n\">five_postr<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"r\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"Posterior w\/ beta(0.5,0.5) prior\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">plot<\/span><span class=\"p\">(<\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span> <span class=\"n\">two_postr<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"DarkOrange\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">label<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"Posterior w\/ beta(2,2) prior\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">legend<\/span><span class=\"p\">(<\/span><span class=\"n\">loc<\/span><span class=\"o\">=<\/span><span class=\"s\">'best'<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_title<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Posterior distributions under different prior parameterizations\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_xlabel<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Theta\"<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">ax<\/span><span class=\"p\">.<\/span><span class=\"n\">set_ylabel<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Density\"<\/span><span class=\"p\">)<\/span><\/code><\/pre><\/figure>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/burgers_posteriors.png\" class=\"inline\" \/><\/p>\n\n<h3 id=\"drawing-conclusions\">Drawing conclusions<\/h3>\n<p>As you can see from the plots directly above, the posterior distribution\u2019s mode\nsettles right around \\(\\theta = 0.8\\) across our three prior parameterizations.\nOne of the benefits of a Bayesian analysis is that there\u2019s no ambiguity in what\nwe mean by \u201cconfidence interval.\u201d<\/p>\n\n<p>Remember the hoopla in your intro to stats class about confidence intervals? To\nfrequentists, the term \u201cconfidence interval\u201d means that \u201cIf I ran the experiment\n100 times, about 95 of the confidence intervals that I estimate (I\u2019m estimating\nthe 95% confidence interval of \\(\\theta\\) in each experiment) will cover the true\nvalue of \\(\\theta\\).\u201d It\u2019s way easier in Bayesian statistics.<\/p>\n\n<p>Now, you can finally say, \u201cThe probability that \\(\\theta\\) lies between a and b is\n95%,\u201d and Bayesian statisticians call \u201cconfidence intervals\u201d <strong>\u201ccredible sets.\u201d<\/strong><\/p>\n\n<p>All you do to get a \u201ccredible set\u201d is find differences in cumulative densities\nof the posterior! Moreover, we can use the beta cumulative density function to\nassess the probability that \\(\\theta\\) is greater than some value that the\nSchmerger King execs will be happy with, such as \\(\\theta = 0.6\\), under each\nprior distribution:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-python\" data-lang=\"python\"><span class=\"c1\">## Find posterior modes\n<\/span><span class=\"n\">posteriors<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">array<\/span><span class=\"p\">([<\/span><span class=\"n\">one_postr<\/span><span class=\"p\">,<\/span> <span class=\"n\">five_postr<\/span><span class=\"p\">,<\/span> <span class=\"n\">two_postr<\/span><span class=\"p\">])<\/span>\n<span class=\"n\">modes<\/span> <span class=\"o\">=<\/span> <span class=\"n\">theta<\/span><span class=\"p\">[<\/span><span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">apply_along_axis<\/span><span class=\"p\">(<\/span><span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">argmax<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"n\">posteriors<\/span><span class=\"p\">)]<\/span>\n\n<span class=\"c1\">## Calculate credible intervals\n<\/span><span class=\"n\">posterior_params<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">array<\/span><span class=\"p\">([[<\/span><span class=\"mi\">1<\/span><span class=\"o\">+<\/span><span class=\"n\">success<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"o\">-<\/span><span class=\"n\">success<\/span><span class=\"o\">+<\/span><span class=\"mi\">1<\/span><span class=\"p\">],<\/span> <span class=\"p\">[<\/span><span class=\"mf\">0.5<\/span><span class=\"o\">+<\/span><span class=\"n\">success<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"o\">-<\/span><span class=\"n\">success<\/span><span class=\"o\">+<\/span><span class=\"mf\">0.5<\/span><span class=\"p\">],<\/span> <span class=\"p\">[<\/span><span class=\"mi\">2<\/span><span class=\"o\">+<\/span><span class=\"n\">success<\/span><span class=\"p\">,<\/span> <span class=\"n\">n<\/span><span class=\"o\">-<\/span><span class=\"n\">success<\/span><span class=\"o\">+<\/span><span class=\"mi\">2<\/span><span class=\"p\">]])<\/span>\n<span class=\"n\">CI<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">zeros<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">i<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"n\">posterior_params<\/span><span class=\"p\">.<\/span><span class=\"n\">shape<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">]):<\/span>\n    <span class=\"n\">CI<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">]<\/span> <span class=\"o\">=<\/span> <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">cdf<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"n\">posterior_params<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">],<\/span> <span class=\"n\">posterior_params<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">])<\/span> <span class=\"o\">-<\/span> \\\n            <span class=\"n\">beta<\/span><span class=\"p\">.<\/span><span class=\"n\">cdf<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.6<\/span><span class=\"p\">,<\/span> <span class=\"n\">posterior_params<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">],<\/span> <span class=\"n\">posterior_params<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">])<\/span>\n    <span class=\"k\">print<\/span> <span class=\"s\">\"Under prior distribution {} we are {:.2f}% sure that theta &gt; 0.6.\"<\/span><span class=\"p\">.<\/span><span class=\"nb\">format<\/span><span class=\"p\">(<\/span><span class=\"n\">i<\/span><span class=\"o\">+<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">100<\/span><span class=\"o\">*<\/span><span class=\"n\">CI<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">])<\/span><\/code><\/pre><\/figure>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/tldrbayes_CDF_results.png\" class=\"inline\" \/><\/p>\n\n<p>Given that we\u2019ve made some pretty reasonable assumptions for the likelihood and\nprior distributions, you can safely report that people firmly prefer mice\nhotdogs to cat hotdogs.<\/p>\n","pubDate":"Thu, 05 May 2016 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2016\/05\/05\/tldrBayes.html","guid":"https:\/\/ffineis.github.io\/blog\/2016\/05\/05\/tldrBayes.html","category":"blog"},{"title":"Installing OpenCV on Mac OS X in an Anaconda Virtual Environment","description":"<h3 id=\"whats-opencv\">What\u2019s OpenCV?<\/h3>\n<p>Ahhh, computer vision, such a cool field! Lately, I\u2019ve been trying to become more knowledgeable about CV and image processing in python. <a href=\"http:\/\/opencv.org\/downloads.html\">OpenCV<\/a> (CV = \u2018computer vision\u2019) is an excellent open source computer vision software library written in C++ that supports C++, C, Python, Java, and Matlab API\u2019s. OpenCV will supply you with functions that will let you detect faces in images, track objects in a video, and perform any number of image processing tasks.<\/p>\n\n<p>The only problem is: how the <em>hell<\/em> do I install OpenCV so that I can use it in conjunction with a Jupyter notebook? Let\u2019s be honest, most likely you\u2019re either you\u2019re using a Jupyter notebook, Spyder, or the ipython terminal (if you\u2019re a real sadist) to test your python code. And especially if you\u2019re coding for image processing, you\u2019re going to want to view your progress without having (a) a million separate images open and (b) having to wait for Spyder to inevitably crash. That\u2019s the beauty of a Jupyter notebook - when you\u2019re using it with <a href=\"http:\/\/matplotlib.org\/\">Matplotlib<\/a>, you can just display your images and videos in a living document!<\/p>\n\n<p>For me, my ideal OpenCV situation would be for me to be able to simply type and evaluate the following <code class=\"language-plaintext highlighter-rouge\">import<\/code> statements with zero errors or package conficts:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-python\" data-lang=\"python\"><span class=\"kn\">import<\/span> <span class=\"nn\">opencv<\/span>\n<span class=\"n\">img<\/span> <span class=\"o\">=<\/span> <span class=\"n\">cv2<\/span><span class=\"p\">.<\/span><span class=\"n\">imread<\/span><span class=\"p\">(<\/span><span class=\"s\">\"The_Cure_Rules.png\"<\/span><span class=\"p\">)<\/span><\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<h3 id=\"problems-with-traditional-installation-methods\">Problems with traditional installation methods<\/h3>\n\n<p>There are <strong>many<\/strong> ways to install OpenCV. The standard approach is to download it from the OpenCV website and then compile and install OpenCV using the software building utility \u201cCMake\u201d all within a virutal Python environment. I\u2019ve gone down this route according to <a href=\"http:\/\/www.pyimagesearch.com\/2015\/06\/15\/install-opencv-3-0-and-python-2-7-on-osx\/\">Adrian Rosebrock<\/a>\u2019s fabulous installation walkthrough, and if you just want to have access to OpenCV 3.0, I suggest you consider it. But, at the end of the day, there are even more steps required after Adrian\u2019s 9 steps to get OpenCV compatible with a Jupyter notebook. Other installation walkthroughs I\u2019ve found tend to be generally convoluted and assume that you have Homebrew, XCode, maybe MacPorts, or just experience in general with installing and building software packages. <strong>Wouldn\u2019t it be great if we could just run something analogous to <code class=\"language-plaintext highlighter-rouge\">pip install opencv<\/code>?<\/strong><\/p>\n\n<p>If you\u2019re like me (maybe you\u2019re not) I often think that <code class=\"language-plaintext highlighter-rouge\">pip install<\/code>\u2018ing a Python package is the same thing as R\u2019s <code class=\"language-plaintext highlighter-rouge\">install.packages<\/code> function - while we get similar functionality, R packages come with the luxury of basically never interfering with other R package dependencies! If one package needs a newer or older version of some other package you\u2019ve already installed, <code class=\"language-plaintext highlighter-rouge\">install.packages<\/code> will most likely just take care of everything for you. Python packages, on the other hand, will often have dependencies on specific versions of other packages, so if you <code class=\"language-plaintext highlighter-rouge\">pip install<\/code> one package, other package may fail to import because their dependent packages have been updated. That\u2019s why we use virtual environments; my favorite method for creating and running virtual environments is with <a href=\"https:\/\/www.continuum.io\/downloads\">Anaconda<\/a>, a Python distribution that comes with Sklearn, Scipy, NumPy, Jupyter notebook, and most of the other essential tools a data scientist needs when using Python.<\/p>\n\n<p>Overall, I installed OpenCV cleanly in just a few steps:<\/p>\n\n<ul>\n  <li>Install Anaconda, make Anaconda\u2019s Python your system\u2019s default Python (skip if you already have this).<\/li>\n  <li>Create a virtual environment.<\/li>\n  <li>Make sure all Conda packages are up-to-date.<\/li>\n  <li>Run <code class=\"language-plaintext highlighter-rouge\">conda install -c https:\/\/conda.binstar.org\/menpo opencv<\/code><\/li>\n  <li>Test.<\/li>\n<\/ul>\n\n<p><br \/><\/p>\n\n<h3 id=\"1-install-anaconda-skip-if-you-already-have-anaconda\">(1) Install Anaconda. (Skip if you already have Anaconda).<\/h3>\n\n<p>First off, I\u2019m still a python 2 guy. Yeah, there\u2019s python 3, but I grew up on Py 2.7 and it\u2019ll take a lot to pry it from my cold, dead hands. So I have a python 2.7 Anaconda environment running on my computer. Your choice.<\/p>\n\n<p>I went to the Anaconda <a href=\"https:\/\/www.continuum.io\/downloads\">downloads<\/a> page and got the Python 2.7 Mac OS X 64-Bit <em>command-line installer<\/em>, so that we can install everything from Terminal.<\/p>\n\n<p>After downloading that, navigate to your Downloads directory (if you\u2019re new to the Terminal, just open the Terminal application and type <code class=\"language-plaintext highlighter-rouge\">cd $HOME\/Downloads<\/code>).<\/p>\n\n<p>While still in Terminal, enter<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span>bash Anaconda2-2.5.0-MacOSX-x86_64.sh<\/code><\/pre><\/figure>\n\n<p>Awesome, now you\u2019ve downloaded and installed Anaconda.<\/p>\n\n<p><br \/><\/p>\n\n<h3 id=\"1b-make-anaconda-your-default-python-installation\">(1.b) Make Anaconda your default python installation.<\/h3>\n<p>For data science, Anaconda rules. Ideally, when you\u2019re in Terminal and you type <code class=\"language-plaintext highlighter-rouge\">python<\/code>, you\u2019d like for the Anaconda python installation to be the default python that starts running instead of what comes installed by default on a typical Macbook. Why? Well, using Anaconda we can just import NumPy, import any Scikit Learn funciton, import Matplotlib, etc.<\/p>\n\n<p>To see what I\u2019m talking about, type this in Terminal:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span>which python<\/code><\/pre><\/figure>\n\n<p>If you get <code class=\"language-plaintext highlighter-rouge\">\/usr\/bin\/python2.7<\/code>, you\u2019re not using the Anaconda installation. To change this, you\u2019ll need to change your <strong>bash_profile<\/strong> so that the default path to the python installation in the Anaconda directory. If you don\u2019t have a .bash_profile file in your home directory, do this:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span><span class=\"nb\">touch<\/span> <span class=\"nv\">$HOME<\/span>\/.bash_profile<\/code><\/pre><\/figure>\n\n<p>This just created that file. Next, open the .bash_profile page and add this line:<\/p>\n\n<p><strong>export PATH=\u201d~\/anaconda\/bin:$PATH\u201d<\/strong><\/p>\n\n<p>Finally, you have to make your system update python path the with your new settings, so in Terminal type<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span><span class=\"nb\">source<\/span> <span class=\"nv\">$HOME<\/span>\/.bash_profile<\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<h3 id=\"2-make-an-anaconda-virtual-environment\">(2) Make an Anaconda virtual environment<\/h3>\n\n<p>Anaconda has great <a href=\"http:\/\/conda.pydata.org\/docs\/py2or3.html#create-a-python-2-7-environment\">documentation<\/a> if you ever get lost using their tools, but otherwise they\u2019re pretty easy to use. To create a virtual python 2.7 environment called \u201cpy27,\u201d run this:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span>conda create <span class=\"nt\">-n<\/span> py27 <span class=\"nv\">python<\/span><span class=\"o\">=<\/span>2.7 anaconda<\/code><\/pre><\/figure>\n\n<p>To enter this virtual environment, we use Conda\u2019s <code class=\"language-plaintext highlighter-rouge\">source activate<\/code> function:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span><span class=\"nb\">source <\/span>activate py27<\/code><\/pre><\/figure>\n\n<p>If the environment is running properly, you should see <code class=\"language-plaintext highlighter-rouge\">(py27)<\/code> preceding the <code class=\"language-plaintext highlighter-rouge\">$<\/code> sign at the command prompt in Terminal. In this environment we have access to Anaconda\u2019s python package installer, <code class=\"language-plaintext highlighter-rouge\">conda install<\/code>, so that we can install packages at will in this \u201cbubble\u201d without messing up dependencies (basically breaking python) in any other environment. Side note: if you want to exit this py27 environment, just enter <code class=\"language-plaintext highlighter-rouge\">source deactivate<\/code> in Terminal.<\/p>\n\n<p><br \/><\/p>\n\n<h3 id=\"3-update-packages\">(3) Update packages<\/h3>\n<p>Just to be safe, I updated all of my python packages while inside of my py27 environment. It\u2019s ridiculously easy with Anaconda:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span>conda update <span class=\"nt\">--all<\/span><\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<h3 id=\"4-install-opencv\">(4) Install OpenCV<\/h3>\n<p>With Anconda we can install python packages within a specific Conda environment using <code class=\"language-plaintext highlighter-rouge\">conda install<\/code> instead of <code class=\"language-plaintext highlighter-rouge\">pip<\/code>, the typical python package management system.<\/p>\n\n<p>Next, I would normally suggest just typing <code class=\"language-plaintext highlighter-rouge\">conda install opencv<\/code> at the command prompt, but this (unsurprisingly) lead me to a package conflict with NumPy! Yep, the version of OpenCV that Conda installed relied on a specific release of the NumPy package that was actually in conflict with the one that was just updated in step (3). OK, to be honest, maybe I brought that upon myself with updating the packages the way I did. But, there\u2019s a work around that functions with this latest update of NumPy: install OpenCV directly from the <a href=\"http:\/\/www.menpo.org\/\">Menpo project<\/a>:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span>conda <span class=\"nb\">install<\/span> <span class=\"nt\">-c<\/span> https:\/\/conda.binstar.org\/menpo opencv<\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<h3 id=\"5-fire-up-a-jupyter-notebook-and-test\">(5) Fire up a Jupyter notebook and test!<\/h3>\n<p>The Anaconda environment should now have everything we need to start analyzing images in a self-contained little Jupyter notebook. Test it out. First, launch a Jupyter notebook from the terminal:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-bash\" data-lang=\"bash\"><span class=\"nv\">$ <\/span>jupyter notebook<\/code><\/pre><\/figure>\n\n<p>Next, see if everything is installed correctly; hopefully you\u2019ll be able to run this sans errors:<\/p>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/FrankFineis\/FrankFineis.github.io\/master\/images\/opencv_import_ss.png\" alt=\"jupyter notebook\" \/><\/p>\n\n<p>If successful, you\u2019ll be able to readily access OpenCV functions with the package prefix <code class=\"language-plaintext highlighter-rouge\">cv2<\/code>!<\/p>\n","pubDate":"Sun, 13 Mar 2016 00:00:00 +0000","link":"https:\/\/ffineis.github.io\/blog\/2016\/03\/13\/install_opencv.html","guid":"https:\/\/ffineis.github.io\/blog\/2016\/03\/13\/install_opencv.html","category":"blog"},{"title":"Example Case Interview: the Kaggle Competition. (Part 2)","description":"<p>After finishing <a href=\"http:\/\/frankfineis.github.io\/tutorials\/2016\/02\/17\/kaggle-pt1.html\">Part 1<\/a> of this tutorial we have our data features - recall that we saved the TF-IDF transformed text data from the <em>names<\/em> and <em>description\/caption<\/em> fields and country names we got from the Geonames API in the <code class=\"language-plaintext highlighter-rouge\">.\/data<\/code> directory - we\u2019ll assemble our training and test data matrices. After that, we\u2019ll train an <code class=\"language-plaintext highlighter-rouge\">xgboost<\/code> model comprised of trees and (briefly) tune a few hyperparameters.<\/p>\n\n<p>It\u2019s important to note that there are two different ways to train and validate a model: we can use the functions supplied to us in the <code class=\"language-plaintext highlighter-rouge\">xgboost<\/code> package directly (e.g. <code class=\"language-plaintext highlighter-rouge\">xgb.train<\/code> or <code class=\"language-plaintext highlighter-rouge\">xgb.cv<\/code>), OR, we can use the <code class=\"language-plaintext highlighter-rouge\">caret<\/code> package. I\u2019ll illustrate both, but I\u2019ll use <code class=\"language-plaintext highlighter-rouge\">caret<\/code> to tune the model that will be used for making predictions on <code class=\"language-plaintext highlighter-rouge\">test.csv<\/code>.<\/p>\n\n<p>Go ahead and navigate to the <a href=\"https:\/\/github.com\/fineiskid\/photo_kaggle\/blob\/master\/scripts\/run_classifier.R\">run_classifier.R<\/a> script to follow along!<\/p>\n\n<p><br \/><\/p>\n\n<h3 id=\"1-the-assemble_data-function\">(1) The <code class=\"language-plaintext highlighter-rouge\">assemble_data<\/code> function<\/h3>\n\n<p>This function will load and format either your training or test data (from <code class=\"language-plaintext highlighter-rouge\">train.csv<\/code> or <code class=\"language-plaintext highlighter-rouge\">test.csv<\/code> accordingly). Namely, this data pre-processing function will do the following:<\/p>\n\n<ul>\n  <li><em>Assembling training set<\/em>: we change the <em>good<\/em> vector in <code class=\"language-plaintext highlighter-rouge\">train.csv<\/code> to zeros and ones for use with Xgboost\u2019s function model training function, <code class=\"language-plaintext highlighter-rouge\">xgboost.train<\/code>, append each of the the TF-IDF features from the <em>name<\/em> and <em>description\/caption<\/em> text columns, append a <a href=\"https:\/\/www.quora.com\/What-is-one-hot-encoding-and-when-is-it-used-in-data-science\">one-hot encoding<\/a> of the country names data, remove rows whose countries are missing (there are only about 150 of these cases), and return the training data and target vector with R\u2019s <code class=\"language-plaintext highlighter-rouge\">as.matrix<\/code> function. One-hot encoding of the country names will make one binary vector for each country name, and that vector will have a 1 if that row\u2019s photo album came from the corresponding country. This is accomplished with the line<\/li>\n<\/ul>\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"w\"> <\/span><span class=\"n\">country_one_hot<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">model.matrix<\/span><span class=\"p\">(<\/span><span class=\"o\">~<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">+<\/span><span class=\"n\">country<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">country<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><\/code><\/pre><\/figure>\n\n<ul>\n  <li><em>Assembling the test set<\/em>: Again, we append text and one-hot encoded country features, only now we can ignore the target vector because we\u2019re obviously missing <em>good<\/em>\/<em>bad<\/em> photo albumn classifications. Also, instead of removing rows with missing country names, we\u2019ll impute the most common country name (the USA) because we don\u2019t have the luxury of just excluding albums from the test set. This imputation happens on the line<\/li>\n<\/ul>\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"w\"> <\/span><span class=\"n\">country<\/span><span class=\"o\">$<\/span><span class=\"n\">country<\/span><span class=\"p\">[<\/span><span class=\"n\">which<\/span><span class=\"p\">(<\/span><span class=\"nf\">is.na<\/span><span class=\"p\">(<\/span><span class=\"n\">country<\/span><span class=\"p\">))]<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"nf\">names<\/span><span class=\"p\">(<\/span><span class=\"n\">which.max<\/span><span class=\"p\">(<\/span><span class=\"n\">table<\/span><span class=\"p\">(<\/span><span class=\"n\">country<\/span><span class=\"p\">)))<\/span><span class=\"w\"> <\/span><\/code><\/pre><\/figure>\n\n<p><br \/>\nOnce you\u2019re familiar with the <code class=\"language-plaintext highlighter-rouge\">assemble_data<\/code> function, notice that the lines immediately after defining <code class=\"language-plaintext highlighter-rouge\">assemble_data<\/code> are calling that function to gather our training set and training target vector:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"n\">train_data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">assemble_data<\/span><span class=\"p\">()<\/span><span class=\"w\">\n<\/span><span class=\"n\">train<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">train_data<\/span><span class=\"o\">$<\/span><span class=\"n\">data<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"n\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">train_data<\/span><span class=\"o\">$<\/span><span class=\"n\">y<\/span><\/code><\/pre><\/figure>\n\n<p><br \/><\/p>\n\n<h3 id=\"2a-train-a-model-with-randomly-chosen-parameters-optional\">(2.a) Train a model with randomly chosen parameters (optional)<\/h3>\n\n<p>If you want to use the model training, validation, and prediction functions supplied in the Xgboost package, that\u2019s great, just be aware that you should supply each of <code class=\"language-plaintext highlighter-rouge\">xgb.train<\/code>, <code class=\"language-plaintext highlighter-rouge\">xgb.cv<\/code>, and <code class=\"language-plaintext highlighter-rouge\">xgb::predict<\/code> with special data structures created with <code class=\"language-plaintext highlighter-rouge\">xgb.DMatrix<\/code> instead of regular old matrices or R data.frames. First, we split up the <code class=\"language-plaintext highlighter-rouge\">train<\/code> data into a training set and a validation set. I know, it\u2019s confusing terminology - we\u2019re taking 80% of the training data and calling <em>this<\/em> the training set and the remaining 20% the <em>validation<\/em> set. Anyway, the next chunk of code will fit a xgboosted tree model with a set of hyperparameters I pulled out of nowhere. Note that by using the <code class=\"language-plaintext highlighter-rouge\">watchlist<\/code> setting, the training and validation set performance will print to the screen each time a new one of the <code class=\"language-plaintext highlighter-rouge\">nround<\/code> small trees is appended to the aggregate model, but I\u2019m saving this output to a text file via R\u2019s <code class=\"language-plaintext highlighter-rouge\">sink<\/code> function. Finally, we can estimate our accuracy on <code class=\"language-plaintext highlighter-rouge\">test.csv<\/code> by using our prediction error on the validation set as a proxy:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"n\">trainIndex<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">as.vector<\/span><span class=\"p\">(<\/span><span class=\"n\">caret<\/span><span class=\"o\">::<\/span><span class=\"n\">createDataPartition<\/span><span class=\"p\">(<\/span><span class=\"n\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">y<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                                         <\/span><span class=\"n\">p<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0.8<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"c1\">#fraction of training data kept as 'training' data<\/span><span class=\"w\">\n                                         <\/span><span class=\"n\">list<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">FALSE<\/span><span class=\"p\">))<\/span><span class=\"w\">\n\n<\/span><span class=\"c1\">#hyperparameters<\/span><span class=\"w\">\n<\/span><span class=\"n\">max.depth<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"m\">8<\/span><span class=\"w\"> <\/span><span class=\"c1\">#How deep each weak learner (small tree) can get. Will control overfitting.<\/span><span class=\"w\">\n<\/span><span class=\"n\">eta<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"m\">0.5<\/span><span class=\"w\"> <\/span><span class=\"c1\">#eta is the learning rate, which also has to do with regularization. 1 -&gt;&gt; no regularization. 0 &lt; eta &lt;= 1.<\/span><span class=\"w\">\n<\/span><span class=\"n\">nround<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"m\">150<\/span><span class=\"w\"> <\/span><span class=\"c1\">#The number of passes over training data. This is the number of trees we're ensembling.<\/span><span class=\"w\">\n\n<\/span><span class=\"n\">train.DMat<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">xgb.DMatrix<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">train<\/span><span class=\"p\">[<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"p\">],<\/span><span class=\"w\"> <\/span><span class=\"n\">label<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">y<\/span><span class=\"p\">[<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">])<\/span><span class=\"w\">\n\n<\/span><span class=\"n\">valid.DMat<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">xgb.DMatrix<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">train<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"p\">],<\/span><span class=\"w\"> <\/span><span class=\"n\">label<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">y<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">])<\/span><span class=\"w\">\n\n<\/span><span class=\"c1\">#Fit boosted model with our random parameters. Save output that would otherwise print to console.<\/span><span class=\"w\">\n<\/span><span class=\"n\">sink<\/span><span class=\"p\">(<\/span><span class=\"s2\">\".\/data\/watchlist_output.txt\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">append<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">FALSE<\/span><span class=\"p\">)<\/span><span class=\"w\">\n<\/span><span class=\"n\">bst<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">xgb.train<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">train.DMat<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                <\/span><span class=\"n\">watchlist<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">list<\/span><span class=\"p\">(<\/span><span class=\"n\">train<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">train.DMat<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">validation<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">valid.DMat<\/span><span class=\"p\">),<\/span><span class=\"w\">\n                <\/span><span class=\"n\">max.depth<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">max.depth<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                <\/span><span class=\"n\">eta<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">eta<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">nthread<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">4<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                <\/span><span class=\"n\">nround<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">nround<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                <\/span><span class=\"n\">objective<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"binary:logistic\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                <\/span><span class=\"n\">eval_metric<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"logloss\"<\/span><span class=\"p\">)<\/span><span class=\"w\">\n<\/span><span class=\"n\">sink<\/span><span class=\"p\">()<\/span><span class=\"w\">\n\n<\/span><span class=\"n\">valid.preds<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">predict<\/span><span class=\"p\">(<\/span><span class=\"n\">bst<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">valid.DMat<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"c1\">#Xgboost::predict returns class probabilities, not class labels!<\/span><span class=\"w\">\n<\/span><span class=\"n\">theta<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"m\">0.5<\/span><span class=\"w\">\n<\/span><span class=\"n\">valid.class_preds<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">ifelse<\/span><span class=\"p\">(<\/span><span class=\"n\">valid.preds<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;=<\/span><span class=\"w\"> <\/span><span class=\"n\">theta<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"p\">)<\/span><span class=\"w\">\n<\/span><span class=\"n\">valid.accuracy<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"nf\">sum<\/span><span class=\"p\">(<\/span><span class=\"nf\">as.numeric<\/span><span class=\"p\">(<\/span><span class=\"n\">valid.class_preds<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">y<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">]))<\/span><span class=\"o\">\/<\/span><span class=\"nf\">length<\/span><span class=\"p\">(<\/span><span class=\"n\">y<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">])<\/span><span class=\"w\"> <\/span><span class=\"c1\">#~78% valid accuracy<\/span><span class=\"w\">\n<\/span><span class=\"n\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">sprintf<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"Accuracy on validation set: %f\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">valid.accuracy<\/span><span class=\"p\">))<\/span><\/code><\/pre><\/figure>\n\n<p>Before moving on, one cool feature of boosted tree models is that we can get <strong>variable importances<\/strong> - a variable\u2019s importance to the overall model is an average of the improvement in accuracy gained from all of the small trees every time that feature was used to split up a node in a tree. Viewing the variable importances might help to verify that your model makes sense, and it wouldn\u2019t hurt to include it in a code\/case interview to demonstrate that you can put words behind the model you\u2019ve built.<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"n\">importance_matrix<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">xgb.importance<\/span><span class=\"p\">(<\/span><span class=\"n\">model<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">bst<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">feature_names<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">colnames<\/span><span class=\"p\">(<\/span><span class=\"n\">train<\/span><span class=\"p\">))<\/span><span class=\"w\">\n<\/span><span class=\"n\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">importance_matrix<\/span><span class=\"p\">)<\/span><span class=\"w\">\n<\/span><span class=\"n\">barplot<\/span><span class=\"p\">(<\/span><span class=\"n\">importance_matrix<\/span><span class=\"o\">$<\/span><span class=\"n\">Gain<\/span><span class=\"p\">[<\/span><span class=\"m\">6<\/span><span class=\"o\">:<\/span><span class=\"m\">1<\/span><span class=\"p\">],<\/span><span class=\"w\">\n        <\/span><span class=\"n\">horiz<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">T<\/span><span class=\"p\">,<\/span><span class=\"w\">\n        <\/span><span class=\"n\">names.arg<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">importance_matrix<\/span><span class=\"o\">$<\/span><span class=\"n\">Feature<\/span><span class=\"p\">[<\/span><span class=\"m\">6<\/span><span class=\"o\">:<\/span><span class=\"m\">1<\/span><span class=\"p\">],<\/span><span class=\"w\">\n        <\/span><span class=\"n\">main<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"Estimated top 6 features by accuracy gain\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n        <\/span><span class=\"n\">cex.names<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">.6<\/span><span class=\"p\">)<\/span><\/code><\/pre><\/figure>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/fineiskid\/photo_kaggle\/master\/output\/feature_importance.png\" class=\"inline\" \/><\/p>\n\n<h3 id=\"2b-tune-hyperparameters-with-carettrain\">(2.b) Tune hyperparameters with <code class=\"language-plaintext highlighter-rouge\">caret::train<\/code><\/h3>\n<p>Since we really have little insight into whether we should use a small <code class=\"language-plaintext highlighter-rouge\">max_depth<\/code> or a large one, let all of our features be available when constructing a weak learner (i.e. how to set <code class=\"language-plaintext highlighter-rouge\">colsample_bytree<\/code>), etc\u2026 We should set up a grid of parameters, cross validate a model for every combination of parameters in the grid, and pick the best one! This is a very computationally expensive way to pick a model, and note that it\u2019s still not even very refined when there are big discrete gaps in the hyperparameter values present in the grid. Still, we might be able to eek out better performance with a high-level gridsearch. Use R\u2019s convenient <code class=\"language-plaintext highlighter-rouge\">expand.grid<\/code> function to make a data.frame with every combination of hyperparameters you\u2019re interested in; use <code class=\"language-plaintext highlighter-rouge\">caret::trainControl<\/code> to specify the type of validation you\u2019re interested in (we\u2019ll do 5-fold cross validation); and use <code class=\"language-plaintext highlighter-rouge\">caret::train<\/code> to search over the grid of hyperparameter combinations to find the model that minimizes log-loss. We can only use <code class=\"language-plaintext highlighter-rouge\">caret<\/code> because it recently began supporting <code class=\"language-plaintext highlighter-rouge\">model = 'xgbTree'<\/code> (caret supports hundreds of different models, actually), and it conveniently supports log-loss as an optimization metric too!<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"n\">xgb_grid<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">expand.grid<\/span><span class=\"p\">(<\/span><span class=\"n\">nrounds<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">c<\/span><span class=\"p\">(<\/span><span class=\"m\">100<\/span><span class=\"p\">),<\/span><span class=\"w\">\n                        <\/span><span class=\"n\">eta<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">c<\/span><span class=\"p\">(<\/span><span class=\"m\">0.2<\/span><span class=\"p\">),<\/span><span class=\"w\">\n                        <\/span><span class=\"n\">max_depth<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">c<\/span><span class=\"p\">(<\/span><span class=\"m\">7<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">10<\/span><span class=\"p\">),<\/span><span class=\"w\">\n                        <\/span><span class=\"n\">colsample_bytree<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">c<\/span><span class=\"p\">(<\/span><span class=\"m\">0.6<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"p\">),<\/span><span class=\"w\">\n                        <\/span><span class=\"n\">gamma<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">c<\/span><span class=\"p\">(<\/span><span class=\"m\">0.75<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"p\">),<\/span><span class=\"w\">\n                        <\/span><span class=\"n\">min_child_weight<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nf\">c<\/span><span class=\"p\">(<\/span><span class=\"m\">1<\/span><span class=\"p\">))<\/span><span class=\"w\">\n\n<\/span><span class=\"n\">tr_control<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">caret<\/span><span class=\"o\">::<\/span><span class=\"n\">trainControl<\/span><span class=\"p\">(<\/span><span class=\"n\">method<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"cv\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">number<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">5<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">classProbs<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">TRUE<\/span><span class=\"p\">,<\/span><span class=\"w\"> \n                          <\/span><span class=\"n\">allowParallel<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">TRUE<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">summaryFunction<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">mnLogLoss<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"c1\">#Using summaryFunction = summaryFunction will use ROC (i.e. AUC) to select optimal model. We want log-loss.<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">verboseIter<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">TRUE<\/span><span class=\"p\">)<\/span><span class=\"w\"> \n\n<\/span><span class=\"n\">xgb_cv1<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">caret<\/span><span class=\"o\">::<\/span><span class=\"n\">train<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">train<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                       <\/span><span class=\"n\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">as.factor<\/span><span class=\"p\">(<\/span><span class=\"n\">ifelse<\/span><span class=\"p\">(<\/span><span class=\"n\">y<\/span><span class=\"o\">==<\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"good\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"bad\"<\/span><span class=\"p\">)),<\/span><span class=\"w\"> <\/span><span class=\"c1\"># Target vector should be non-numeric factors to identify our task as classification, not regression.<\/span><span class=\"w\">\n                       <\/span><span class=\"n\">tuneGrid<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">xgb_grid<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"c1\">#Which hyperparameters we'll test.<\/span><span class=\"w\">\n                       <\/span><span class=\"n\">trControl<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">tr_control<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"c1\"># Specify how cross validation should go down.<\/span><span class=\"w\">\n                       <\/span><span class=\"n\">method<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"xgbTree\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                       <\/span><span class=\"n\">metric<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"logLoss\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"c1\"># Convenient.<\/span><span class=\"w\">\n                       <\/span><span class=\"n\">maximize<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">FALSE<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"c1\"># We want to minimize loss, after all.<\/span><\/code><\/pre><\/figure>\n\n<p>A couple of points regarding <code class=\"language-plaintext highlighter-rouge\">caret<\/code>\u2019s functionality versus <code class=\"language-plaintext highlighter-rouge\">xgboost<\/code>\u2019s: first, you\u2019ll need to make <code class=\"language-plaintext highlighter-rouge\">y<\/code> a factor vector instead of a numeric vector so that <code class=\"language-plaintext highlighter-rouge\">caret::train<\/code> knows that you want to perform a classification task instead of a regression task. Also, with <code class=\"language-plaintext highlighter-rouge\">caret<\/code> we can return to using matrices and data.frames instead of <code class=\"language-plaintext highlighter-rouge\">xgb.DMatrix<\/code>\u2019s. Finally - this gridsearch will take a <strong>long time<\/strong> (at least 3 hours on a Macbook with an i7 core processor).<\/p>\n\n<h3 id=\"3-visualize-performance-with-an-roc-curve-optional\">(3) Visualize performance with an ROC curve (optional):<\/h3>\n<p>Receiver operating characteristics (ROC\u2019s) are confusing, so I suggest reading the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Receiver_operating_characteristic\">Wikipedia<\/a> article about them. Maybe I\u2019ll make a post about it soon. Basically, they just let you compare the performance of different classification models. A popular one called \u201carea under curve\u201d the false positive rate (i.e. rate at which we call a bad photo album good) versus the true positive rate (i.e. rate at which we call good albums good). When the false positive rate (FPR) is zero, we\u2019ve just called every album \u2018bad\u2019 so the true positive rate (TPR) is 0%. Similarly, when we call every album good, the FPR is 100% and the TPR 100%. The best model ever would have 0% FPR and 100% TPR, so an \u201carea under the curve\u201d of 1. I suggest reading <a href=\"http:\/\/blog.yhat.com\/posts\/roc-curves.html\">this<\/a> great intro link about AUC and ROC curves. Anyway, you need to obtain class probabilities from <code class=\"language-plaintext highlighter-rouge\">caret::train<\/code> <strong>or<\/strong> <code class=\"language-plaintext highlighter-rouge\">xgb.predict<\/code> in order to build an ROC curve.<\/p>\n\n<p>My code in <a href=\"https:\/\/github.com\/fineiskid\/photo_kaggle\/blob\/master\/scripts\/run_classifier.R\">run_classifier.R<\/a> will let you build the ROC curve by hand as well as leverage the R packages <code class=\"language-plaintext highlighter-rouge\">pROC<\/code> and <code class=\"language-plaintext highlighter-rouge\">ROCR<\/code> for simplification:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"n\">auc_est<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">pROC<\/span><span class=\"o\">::<\/span><span class=\"n\">auc<\/span><span class=\"p\">(<\/span><span class=\"n\">y<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">],<\/span><span class=\"w\"> <\/span><span class=\"n\">valid.preds<\/span><span class=\"o\">$<\/span><span class=\"n\">good<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"c1\">#0.8638 on the validation set, not bad...<\/span><span class=\"w\">\n\n<\/span><span class=\"n\">rocr_pred<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">prediction<\/span><span class=\"p\">(<\/span><span class=\"n\">valid.preds<\/span><span class=\"o\">$<\/span><span class=\"n\">good<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">y<\/span><span class=\"p\">[<\/span><span class=\"o\">-<\/span><span class=\"n\">trainIndex<\/span><span class=\"p\">])<\/span><span class=\"w\">\n<\/span><span class=\"n\">rocr_perf<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">performance<\/span><span class=\"p\">(<\/span><span class=\"n\">rocr_pred<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">measure<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"tpr\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">x.measure<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"fpr\"<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"c1\">#this is of class \"performance,\" it's not a list<\/span><span class=\"w\">\n<\/span><span class=\"n\">auc_data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">data.frame<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"fpr\"<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">unlist<\/span><span class=\"p\">(<\/span><span class=\"n\">rocr_perf<\/span><span class=\"o\">@<\/span><span class=\"n\">x.values<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"tpr\"<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">unlist<\/span><span class=\"p\">(<\/span><span class=\"n\">rocr_perf<\/span><span class=\"o\">@<\/span><span class=\"n\">y.values<\/span><span class=\"p\">))<\/span><\/code><\/pre><\/figure>\n\n<p><img src=\"https:\/\/raw.githubusercontent.com\/fineiskid\/photo_kaggle\/master\/output\/roc_curve.png\" class=\"inline\" \/><\/p>\n\n<h3 id=\"4-assemble-test-data-and-gather-predictions\">(4) Assemble test data and gather predictions<\/h3>\n\n<p>Just like in step (1), use <code class=\"language-plaintext highlighter-rouge\">assemble_data<\/code> to construct the test set with all of the new features we have. If you look in the <code class=\"language-plaintext highlighter-rouge\">example_entry.csv<\/code> file that the Kaggle administrator supplied, they want for the output to have two columns, <em>id<\/em> and <em>good<\/em>, where <em>good<\/em> is binary 0\/1. Since <code class=\"language-plaintext highlighter-rouge\">caret::predict(model, newdata, type = \"raw\")<\/code> returns factor variables representing class membership, just use R\u2019s super-convenient <code class=\"language-plaintext highlighter-rouge\">ifelse<\/code> function to change the results to zeros and ones. Save the data, and submit!<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-r\" data-lang=\"r\"><span class=\"n\">test_data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">assemble_data<\/span><span class=\"p\">(<\/span><span class=\"n\">train_or_test<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"test\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">data_file<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\".\/data\/test.csv\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">name_tfidf_file<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\".\/data\/test_name_tfidf.rds\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">desc_caption_tfidf_file<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\".\/data\/test_desc_caption_tfidf.rds\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n                          <\/span><span class=\"n\">country_file<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\".\/data\/aggregate_test_countries.RDS\"<\/span><span class=\"p\">)<\/span><span class=\"w\">\n\n<\/span><span class=\"n\">test<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">test_data<\/span><span class=\"o\">$<\/span><span class=\"n\">data<\/span><span class=\"w\">\n<\/span><span class=\"n\">test_classes<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;-<\/span><span class=\"w\"> <\/span><span class=\"n\">ifelse<\/span><span class=\"p\">(<\/span><span class=\"n\">predict<\/span><span class=\"p\">(<\/span><span class=\"n\">xgb_cv1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">test<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">type<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"raw\"<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"good\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"p\">)<\/span><span class=\"w\">\n\n<\/span><span class=\"c1\">#Save and then submit predictions!<\/span><span class=\"w\">\n<\/span><span class=\"n\">write.csv<\/span><span class=\"p\">(<\/span><span class=\"n\">data.frame<\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">read.csv<\/span><span class=\"p\">(<\/span><span class=\"s2\">\".\/data\/test.csv\"<\/span><span class=\"p\">)<\/span><span class=\"o\">$<\/span><span class=\"n\">id<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">good<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">test_classes<\/span><span class=\"p\">),<\/span><span class=\"w\">\n          <\/span><span class=\"s2\">\".\/output\/test_predictions.csv\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">row.names<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">FALSE<\/span><span class=\"p\">)<\/span><\/code><\/pre><\/figure>\n\n<h3 id=\"optional-run-this-bad-boy-yourself\">(Optional) run this bad boy yourself<\/h3>\n\n<p>From your command line, navigate to the <code class=\"language-plaintext highlighter-rouge\">photo_kaggle<\/code> directory and run <code class=\"language-plaintext highlighter-rouge\">&gt; Rscript .\/scripts\/run_classifier.R<\/code>. This will build an xgboost model and save predictions from the <code class=\"language-plaintext highlighter-rouge\">test.csv<\/code> file provided to us on Kaggle. From here it\u2019s easy to add and tune more hyperparameters, add some creative features, delete useless ones, etc. Xgboost is really powerful, have fun!<\/p>\n","pubDate":"Tue, 08 Mar 2016 15:28:13 +0000","link":"https:\/\/ffineis.github.io\/blog\/data\/2016\/03\/08\/kaggle-pt2.html","guid":"https:\/\/ffineis.github.io\/blog\/data\/2016\/03\/08\/kaggle-pt2.html","category":["blog","data"]},{"title":"Example Case Interview: the Kaggle Competition. (Part 1)","description":"<p>Alright, so you\u2019re an aspiring data scientist, say a graduate student in a STEM field trying to get into private industry, and congratulations, you\u2019ve made it to the case study round! What do I mean by <em>case study<\/em>? Ah, I mean a timed test with a <em>training set<\/em> and a <em>test set<\/em>. You\u2019ve been instructed to build a model that will give predicted values for the observations contained in the test set, and then your (hopefully) future employer will compare your values with the test set\u2019s true values. Few things get more meritocratic than that!<\/p>\n\n<h4 id=\"general-steps-involved-in-a-data-science-coding-interview\">General steps involved in a data science coding interview:<\/h4>\n<ol>\n  <li>Load your data. Poke around.<\/li>\n  <li>Decide on an appropriate mathematical\/machine learning model you\u2019d like to use.<\/li>\n  <li>Create a data processing pipeline for both your training and test data sets.\n    <ul>\n      <li>Pick features you\u2019d like to try in your model. A <strong>feature<\/strong> is generally a column within your dataset fed into your machine learning model.<\/li>\n      <li>If applicable, standardize or normalize various features.<\/li>\n    <\/ul>\n  <\/li>\n  <li>Tune the model\u2019s hyperparameters through validation.<\/li>\n  <li>Fit model with decided upon hyperparameters with all of your training data.<\/li>\n  <li>Get predictions for the processed test data set.<\/li>\n<\/ol>\n\n<p><br \/><\/p>\n\n<h2 id=\"example-case-interview-the-kaggle-photo-album-classification-project\">Example case interview: the Kaggle photo album classification project<\/h2>\n<p><a href=\"https:\/\/www.kaggle.com\/\">Kaggle<\/a> is a data science competition website where individuals (and teams) compete, sometimes for big bucks, on data science projects hosted by big name companies (Deloitte and NASA, just to name a few) who want\/need models and solutions to said data science projects. The projects run the gamut in difficulty, and I\u2019ve picked an easier one that serves as a good example for what you might expect for a data science case interview: the <a href=\"https:\/\/www.kaggle.com\/c\/PhotoQualityPrediction\">photo album quality prediction<\/a> project. You can track all of my relevant code and data <a href=\"https:\/\/github.com\/fineiskid\/photo_kaggle\">here<\/a> in this Github repo. The main idea is that we have data corresponding to photo albums that have been uploaded by users, and somehow they were labeled \u201cgood\u201d or \u201cbad.\u201d In the training set we have information about each photo album like number of photos, size of each photo, etc., and we seek to make a good\/bad classification for a set of albums that have not been labeled, this latter set being the test set.<\/p>\n\n<p><br \/><\/p>\n\n<h2 id=\"the-gist\">THE GIST:<\/h2>\n<p>Like I said, we\u2019ll need to process the training data, seek out new features, pick a model, train and tune it, process the test data, and get our predictions on the test data. I\u2019m going to do this using <code class=\"language-plaintext highlighter-rouge\">R<\/code>, and since there\u2019s been a lot of buzz about <strong>extreme gradient boosting<\/strong> over the last year or two, and the <a href=\"https:\/\/www.youtube.com\/watch?v=Og7CGAfSr_Y\">xgboost library<\/a> that implements the technique has won at least one Kaggle competition (probably more, I didn\u2019t feel like researching it further), we\u2019ll use xgboost to build a model\/get predictions.<\/p>\n\n<p>I\u2019m not going to get into the nitty gritty of boosted trees and gradient boosting, but from a high level, you can think of it as a weighted sum of small decision trees. The size of the weighted sum (i.e. the number of decision trees) is a hyper-parameter that we\u2019ll tune. Each additional decision tree itself comes from fitting the residuals between the outcome and the existing weighted sum of small residual trees. Xgboost by default builds this type of boosted tree model for classification purposes, but it can also be used for continuous, regression learning purposes by setting <code class=\"language-plaintext highlighter-rouge\">objective = \"reg:linear\"<\/code> within the parameter list submitted to <code class=\"language-plaintext highlighter-rouge\">xbg.train<\/code> (more on this to come). I\u2019d Google it, but let\u2019s move on to data preprocessing first.<\/p>\n\n<p>When we make a model using the training data, we\u2019ll need to make sure that we treat the test data in exactly the same way we did the training data to get the same results. For example, if we scale one feature in the training set, we have to scale the corresponding feature in the test set. Staying organized is the number one priority!<\/p>\n\n<p>We will be evaluated according to the <strong>log-loss<\/strong> the host will calculate from our vector of predictions on the albums put forth in <code class=\"language-plaintext highlighter-rouge\">test.csv<\/code>. We could theoretically evaluate log-loss by hand, it\u2019s given by<\/p>\n\n<p><img src=\"http:\/\/www.sciweavers.org\/tex2img.php?eq=%24%24-%5Csum%20%28y_%7Bi%7Dlog%28y_%7Bpred%7D%29%20%2B%20%281-y_%7Bi%7D%29log%281-y_%7Bpred%7D%29%29%24%24&amp;bc=White&amp;fc=Black&amp;im=jpg&amp;fs=12&amp;ff=arev&amp;edit=0 align=&quot;center&quot; border=&quot;0&quot; alt=&quot;$$-\\sum (y_{i}log(y_{pred}) + (1-y_{i})log(1-y_{pred}))$$&quot; width=&quot;339&quot; height=&quot;22&quot; \/&gt;\" alt=\"equation\" \/><\/p>\n\n<p>Fortunately, the <code class=\"language-plaintext highlighter-rouge\">xgboost<\/code> library will allow us to specify log-loss as the loss metric we want to minimize.<\/p>\n\n<p><br \/><\/p>\n\n<h2 id=\"what-our-data-looks-like\">What our data looks like:<\/h2>\n<ol>\n  <li><code class=\"language-plaintext highlighter-rouge\">id<\/code>: index of the photo album. This is pretty useless towards training a predictive model, so this will be removed from training and test sets.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">latitude<\/code>: integer-rounded latitude coordinates of geo-tag of the photo album.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">longitude<\/code>: integer-rounded longitude coordinates of geo-tag of the photo album.<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">width<\/code>: The width of the images in the album, in pixels<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">height<\/code>: The height of the images in the album, in pixels<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">size<\/code>: The number of photos in the album<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">name<\/code>: Common words in the name of the album<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">description<\/code>: The common words in the description of the album<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">caption<\/code>: The common words in all the captions of the photos within the album<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">good<\/code>: 1 means the human reviewer liked the album, 0 means they didn\u2019t (we\u2019re trying to predict this value). Note that this column is only present in <code class=\"language-plaintext highlighter-rouge\">training.csv<\/code> and not in <code class=\"language-plaintext highlighter-rouge\">test.csv<\/code>.<\/li>\n<\/ol>\n\n<p>Note that the \u201cwords\u201d have ben anonymized into integers. A word is present in the dataset if it has occured \u201cmore than 20 times in different albums,\u201d according to the Kaggle competition\u2019s host - this does not mean that the words in our dataset each occur at least 20 times (few of them do, actually).<\/p>\n\n<p><br \/><\/p>\n\n<h2 id=\"extra-features\">Extra features:<\/h2>\n<p>The main features that come with the training\/test data are integer-rounded latitude\/longitude coordinates, height\/width of the photos used in albums being studied, the number of photos being studied (<code class=\"language-plaintext highlighter-rouge\">size<\/code>), and anonymized text from the album name, album description, and album caption.<\/p>\n\n<ol>\n  <li>\n    <p><em>Area<\/em>: area is a nonlinear feature (it\u2019s multiplicative, duh) that might help us eek-out some extra performance.<\/p>\n  <\/li>\n  <li>\n    <p><em>Country<\/em>: country name may help; perhaps well-liked albums are more likely in exotic locales. While latitude\/longitude might get us most of the way there especially with a tree-based algorithm like xgboost, this might help when coordinates are clustered together at the integer-level, but actual nation varies. I used <a href=\"http:\/\/www.geonames.org\/\">Geonames<\/a> to gather country names based on the longitude\/latitude integers supplied (see <a href=\"https:\/\/github.com\/fineiskid\/photo_kaggle\/blob\/master\/src\/geographic_features.R\">geographic_features.R<\/a> script) and saved a vector of names for each of the training and test sets. There\u2019s a great R package aptly titled <code class=\"language-plaintext highlighter-rouge\">geonames<\/code> that handles all of the URL requests for you, and my script should walk you through the country name acquisition process pretty smoothly. When it\u2019s time to build the boosted model, we simply load <code class=\"language-plaintext highlighter-rouge\">aggregate_train_countries.RDS<\/code> and <code class=\"language-plaintext highlighter-rouge\">aggregate_test_countries.RDS<\/code> with R\u2019s <code class=\"language-plaintext highlighter-rouge\">readRDS<\/code> function and attach them to our feature matrices.<\/p>\n  <\/li>\n  <li>\n    <p><em>Text frequency inverse document frequency data<\/em>: if we treat each album\u2019s name, caption, or description as a \u201cdocument,\u201d then we can get text features by measuring each word\u2019s importance to the \u201cdocument.\u201d Check out the <a href=\"https:\/\/github.com\/fineiskid\/photo_kaggle\/blob\/master\/src\/text_features.R\">text_features.R<\/a> script to see exactly how I\u2019ve computed the TF-IDF features for the training and test sets. For a given word in a \u201cdocument,\u201d that word\u2019s TF-IDF value will increase if the word occurs frequently in the document and decrease if the word is common across many different documents. I\u2019ve built separate TF-IDF matrices for the <code class=\"language-plaintext highlighter-rouge\">names<\/code> feature and a separate, combined matrix for both the <code class=\"language-plaintext highlighter-rouge\">description<\/code> and <code class=\"language-plaintext highlighter-rouge\">caption<\/code> features (I just mashed those features together as I don\u2019t know the difference between a photo album caption and a description). See <code class=\"language-plaintext highlighter-rouge\">text_features.R<\/code> for the calculations. Again, we generate the TF-IDF features for each of the training and test sets and load them when necessary. An important note about TF-IDF features: because we can\u2019t assume that words present in the test set will necessarily be contained within the vocabulary of the training set, we have to designate the words in the test set not seen in the training set as having a TF-IDF value of zero.<\/p>\n  <\/li>\n<\/ol>\n\n<p><br \/><\/p>\n\n<h2 id=\"whats-left-to-do\">What\u2019s left to do?<\/h2>\n<p>As of now have chosen a statistical model, checked out our data, and extracted some more features. Next, we\u2019ll have to train and tune an xgboost model. There are a <strong>bunch<\/strong> of parameters we can tune to try to minimize the log-loss, and we might look at some of these:<\/p>\n\n<ul>\n  <li><code class=\"language-plaintext highlighter-rouge\">max.depth<\/code> : how many levels each small trees in our model, which is a sum of small trees, will be allowed to have<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">gamma<\/code> : when picking a new small tree to add to our model, this is the minimum reduction in loss required to allow a node on a tree to be split further into two child nodes<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">colsample_bytree<\/code>: in an attempt to de-correlate the small trees we\u2019re adding to our model, for each tree we\u2019ll choose a fraction of columns to pick from the training data to build said tree (I think this is similar to <code class=\"language-plaintext highlighter-rouge\">max_features<\/code> in Python\u2019s Random Forest classifier in Sklearn)<\/li>\n  <li><code class=\"language-plaintext highlighter-rouge\">num_round<\/code>: How many small trees comprise the model? This also represents the number of times we sweep over the training data, as we get one small tree per sweep.<\/li>\n<\/ul>\n\n<p>While in a Kaggle competition or a data science code interview you won\u2019t be able to know exactly how erroneous your predictions are on the test set, we can use cross-validation to get an estimate of test error for each set of parameters we\u2019ll test. Picking the set of parameters resulting in the least amount of cross-validated test error, we use those parameters to run <code class=\"language-plaintext highlighter-rouge\">xgboost::predict()<\/code> and submit our predictions!<\/p>\n\n","pubDate":"Wed, 17 Feb 2016 05:28:13 +0000","link":"https:\/\/ffineis.github.io\/blog\/2016\/02\/17\/kaggle-pt1.html","guid":"https:\/\/ffineis.github.io\/blog\/2016\/02\/17\/kaggle-pt1.html","category":"blog"}]}}