<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/data-driven-unit-testing-for-data-scientists-and-quant-developers-alike/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://cartesianfaith.com/2018/03/12/data-driven-unit-testing-for-data-scientists-and-quant-developers-alike/"> R – Cartesian Faith</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Often overlooked, testing is a critical process that saves time over the long term and enables building complex systems. Unit tests for model (descriptive, predictive, or prescriptive analytics) systems differ from standard software. Effective unit testing of computational systems requires a particular emphasis on the data used in the tests. Below are some guidelines to follow to streamline your unit testing and avoid ambiguous results.</p>
<h3>Every test must add information</h3>
<p>First, what are we trying to accomplish with testing? At a very high level, we want certainty from our code. Unfortunately, we don’t always implement things correctly. Sometimes, when we add new functionality, we break old. Worse, we can’t always control the inputs to our system, and the system fails when we least expect it. Testing helps us understand how our system will behave under different conditions. Doing so increases our confidence in the reliability of our system. With greater reliability, we can build atop the software in other systems.</p>
<p>If a test doesn’t provide any useful information, the test should be eliminated. These tests are a waste of time and act like noise in the code. Suppose I write a trivial function to convert a timestamp to GMT. I often load data saved in GMT, but sometimes it gets converted to local timezone when reading in. So we need to convert it back. It looks like</p>
<pre>
to_gmt &lt;- function(x) as.POSIXct(as.character(x), tz='GMT')
</pre>
<p>Do I need to test this? I could, but how much information would a test provide? Not much. If I chose to test this function, I would probably focus on an edge case, such as what happens if I don't get a POSIXct as input.</p>
<p>Let's look at a slightly more complicated example. Suppose I want to compute the precision of my model. I often implement this from scratch to reduce the dependencies in my code. One implementation is</p>
<pre>
precision &lt;- function(predicted, actual) {
  cm &lt;- table(actual, predicted)
  cm['TRUE','TRUE'] / sum(cm[,'TRUE'])
}
</pre>
<p>Do I need to test this? As a sanity check, we probably want to test one expected scenario, since it's easy to confuse the implementation of precision and recall. We might also want to verify that the result is unaffected by the ordering of the labels.</p>
<h3>Test one situation per unit test</h3>
<p>If you’ve ever answered a question with “it depends”, you know that different situations result in different answers. The same is true of testing, and that is what we want to test. From the perspective of the scientific method, we know that to determine if a particular variable has an effect on an experiment, all other variables must be held constant. The same is true of testing. When a test containing multiple scenarios fails, how do you know what caused the test failure? It requires more work to determine the cause of a failure versus separating the tests.</p>
<p>For example, using <a rel="nofollow" href="https://yihui.name/en/2013/09/testing-r-packages/" target="_blank">testit</a> in R, suppose I chose to test two scenarios in my <code>to_gmt</code> function. The first scenario is a sanity test to make sure it does what I expect, while the second is an edge case (and not really valid — why?).</p>
<pre>
assert('to_gmt works', {
  x1 &lt;- as.POSIXct(&quot;2018-03-01 16:00:00&quot;)
  x2 &lt;- as.POSIXct(&quot;2018-03-01 16:00:00+0200&quot;)
  (as.character(to_gmt(x1)) == &quot;2018-03-01 16:00:00 GMT&quot;)
  (as.character(to_gmt(x2)) == &quot;2018-03-01 14:00:00 GMT&quot;)
})
</pre>
<p>If this test fails, what caused the problem? It's easier to know by creating two distinct tests.</p>
<pre>
assert('to_gmt sanity test', {
  x &lt;- as.POSIXct(&quot;2018-03-01 16:00:00&quot;)
  (as.character(to_gmt(x)) == &quot;2018-03-01 16:00:00 GMT&quot;)
})

assert('to_gmt when input has embedded timezone', {
  x &lt;- as.POSIXct(&quot;2018-03-01 16:00:00+0200&quot;)
  (as.character(to_gmt(x)) == &quot;2018-03-01 14:00:00 GMT&quot;)
})
</pre>
<h3>Focus on edge cases</h3>
<p>Mathematical functions have a standard suite of tests that need to be performed. These include normal operation (the sanity or smoke test), followed by boundary conditions, followed by bad data scenarios. Boundary conditions map to the domain of a function. In these cases, data typically has the correct type, but the value is not appropriate for the function. For example, division by 0 is undefined, so it’s important to know what happens when a 0 is given to the division operator. Similarly, the logarithm isn’t defined for negative numbers, so a negative number is out of bounds and should be tested. Adhering to the rule that each test must add information, there isn’t any reason to add more than one test, since all negative numbers are a member of the same boundary condition.</p>
<p>Bad data scenarios are different from boundary scenarios. Here, the type of data is simply wrong. For log, this might be a character. There are innumerable bad data scenarios, and they don’t all need to be tested (see below for more discussion).</p>
<p>Boundary conditions almost always need to be tested. Some bad data scenarios need to be tested. How do you distinguish between the two? Consider matrix inversion. A boundary condition is a singular matrix. A bad data scenario is a non-square matrix.</p>
<h3>Make test coverage proportional to usage and impact</h3>
<p>Not all scenarios need to be tested. Indeed, any student of logic knows that it’s impossible to prove statements as absolutely true (where deduction can’t be applied). In testing, the concept of coverage describes how much of a system is tested. Simplistic test coverage tools check to see if each function (or method) has a test. Sometimes they’ll perform code analysis to look for different conditions that may require testing. Unfortunately, coverage doesn’t understand boundary conditions and edge cases. Thus, attempting to achieve 100% test coverage is not only a fool’s errand but is also a red herring.</p>
<p>As an alternative, an efficient heuristic is to evaluate how important a function is and write sufficient tests commensurate with its importance. Two ways to measure importance include 1) how often a function is used, and 2) how bad is it if the function fails. If the answer is either “a lot” or “pretty bad”, then you likely need a lot of tests pretty badly.</p>
<h3>Use realistic test cases</h3>
<p>It’s tempting to construct explicit data structures to test with, even if that’s not the intended use case. It’s better to write tests that are consistent with a function’s raison d’être. One reason is that test cases can act like documentation when the test scenarios are realistic. If they aren’t realistic, the test cases only demonstrate the mechanics of an operation without communicating the semantics of the operation.</p>
<p>Consider the <code>which</code> function, which takes a logical vector and returns a set of ordinals. A mechanical test constructs inputs explicitly and exclusively tests the mechanical operation of the function.</p>
<pre>
assert('which returns correct ordinals', {
  all.equal(which(c(TRUE,FALSE,TRUE,FALSE)), c(1,3))
})
</pre>
<p>This test does indeed verify the function’s behavior, but it doesn’t communicate how this function is used in the real world. A better test provides some context to provide insight into the semantics of the function. For example, <code>which</code> extracts ordinals based on some condition. A better test illustrates this use case by generating the logical vector via a conditional expression.</p>
<pre>
assert('which returns correct ordinals', {
  x &lt;- 11:14
  all.equal(which(x %% 2 == 1), c(1,3))
})
</pre>
<p>The test now indicates that <code>which</code> typically takes a conditional expression that evaluates to a logical vector.</p>
<h3>Favor programmatic assertions over manual assertions</h3>
<p>How often do you write code from scratch versus copying and pasting a snippet from elsewhere? Reusing bits of code is common in testing. Many unit testing frameworks have a lot of boilerplate code, not to mention tests can have repetitive setup tasks. When creating data for tests and evaluating data afterward, it’s important to do this in a programmatic manner.</p>
<p>Consider a function <code>reverse</code> that reverses a vector. This is what manual assertions look like.</p>
<pre>
assert('reverse a vector', {
  x &lt;- c(2,3,4)
  act &lt;- reverse(x)
  (act[1] == 4)
  (act[2] == 3)
  (act[3] == 2)
})
</pre>
<p>These assertions only work for vectors of length 3. Sometimes it's not worth programmatically generating data for a test. But using manual assertions is particularly bad. After duplicating a code snippet, you may change some input data but not change the assertion. In some cases, the new behavior will pass despite the test not being robust.</p>
<p>A better test tests equality programmatically. Now the assertion works generically for any two vectors of equal length. Notice that I also explicitly defined the expected vector, further templatizing the code.</p>
<pre>
assert('reverse a vector', {
  x &lt;- c(2,3,4)
  exp &lt;- c(4,3,2)
  act &lt;- reverse(x)
  all.equal(act, exp)
})
</pre>
<h3>Use data that unequivocally verifies function behavior</h3>
<p>Let’s return to the scientific method. Earlier I mentioned that to control variables, each test should be in a separate function. Adhering to this rule, there’s still a chance that a test is ambiguous. Here’s how it works. Consider the <code>reverse</code> function once more. I test it like this:</p>
<pre>
assert('reverse a list 1', {
  x &lt;- c(2,2,2,2)
  exp &lt;- c(2,2,2,2)
  act &lt;- reverse(x)
  all.equal(act, exp)
})
</pre>
<p>Is this a good choice of data for the test? No, because we can't tell whether or not the function did the right thing. There are all sorts of function implementations that can yield the same result, such as <code>function(x) x</code>, or <code>function(x) sample(x)</code>. So this data does not produce an unequivocal interpretation of the result.</p>
<p>How about <code>x &lt;- c(2,2,3,3)</code>? This is also not optimal, because the duplicate values can hide extraneous functionality. Better to use unique values. What about <code>x &lt;- c(4,3,2,1)</code>? These are unique, but can I get the correct answer using a different algorithm? Sure, with <code>function(x) x[order(x)]</code>, so this isn’t an unequivocal result.</p>
<p>In short, if there exists more than one plausible explanation for how a result is produced, the test is not unequivocal. Spend more time choosing better test data.</p>
<h3>Explicitly distinguish between values and ordinals</h3>
<p>In R ordinals (aka array indices) are first-class. Ordinals conveniently represent a set and can be used across columns or rows in a data frame. Ordinals are clearly different from values, but we often use values that look like ordinals in tests. This choice of test data makes interpretation ambiguous.</p>
<p>For example, in my earlier test of <code>which</code>, I chose the input as <code>x &lt;- 11:14</code>. What if I chose <code>x &lt;- 1:4</code> instead?</p>
<pre>
assert('which returns correct ordinals', {
  x &lt;- 1:4
  all.equal(which(x %% 2 == 1), c(1,3))
})
</pre>
<p>Mechanically, I'm still testing the same thing, but I've introduced ambiguity into the test. If I'm unfamiliar with <code>which</code>, can I determine definitively what the function is returning: ordinals or values? It’s unclear because my values <em>look like</em> ordinals. Using a different range of values helps to distinguish between the two.</p>
<h3>Conclusion</h3>
<p>Testing is an important part of model development. To get the most out of testing, it’s important to follow some simple guidelines. The key is to pay attention to the data you are using in your tests and focus on testing the most important parts of your model and/or system. While the examples are in R, the same guidelines apply to any language your models are written in, including Python and Javascript.</p>
<p>If you found this article helpful, please share it on social media. Better yet, write better tests!</p>
<p><em>Brian Lee Yung Rowe is founder and CEO of Pez.AI, a data science company that happens to make chatbots. Learn more about how Pez.AI is creating the first data-driven chatbot platform at <a rel="nofollow" href="http://pez.ai/" target="_blank">pez.ai</a>.</em></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://cartesianfaith.com/2018/03/12/data-driven-unit-testing-for-data-scientists-and-quant-developers-alike/"> R – Cartesian Faith</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/u0oxadclf0w" height="1"></a></div>