<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Moura on Medium]]></title>
        <description><![CDATA[Stories by Daniel Moura on Medium]]></description>
        <link>https://medium.com/@daniel.c.moura?source=rss-7cd388a0c4da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*RghmFR44k2M9vCl0Zb2F6g.jpeg</url>
            <title>Stories by Daniel Moura on Medium</title>
            <link>https://medium.com/@daniel.c.moura?source=rss-7cd388a0c4da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:56:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel.c.moura/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Command-Line Data Analytics Made Easy]]></title>
            <link>https://medium.com/data-science/command-line-data-analytics-b2ac88f912d1?source=rss-7cd388a0c4da------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ac88f912d1</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Daniel Moura]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 04:10:29 GMT</pubDate>
            <atom:updated>2022-11-09T19:46:34.545Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>With SQL powered by Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVsgLM-TtOABYMgYd1Lozw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The command-line is incredibly powerful when it comes to data processing. Still, many of us working with data do not take advantage of it. I can think of some reasons:</p><ul><li>Poor readability: the focus is on minimising how much you need to type and not so much on how readable a sequence of commands is;</li><li>Steep learning curve: many commands, with many options;</li><li>Looks outdated: some of these tools are around since the 70s and target delimited text files (and not modern formats like JSON and YAML).</li></ul><p>These motivated me to write a command-line tool that focuses on readability, easiness to learn, and modern data formats, while leveraging the command-line ecosystem. On top of that, it also leverages the Python ecosystem! Meet <a href="https://github.com/dcmoura/spyql">SPyQL — SQL with Python in the middle</a>:</p><pre><strong>SELECT <br>  </strong>date.fromtimestamp(purchase_ts) <strong>AS</strong> purchase_date,<br>  sum_agg(price * quantity) <strong>AS</strong> total<br><strong>FROM</strong> csv(&#39;<em>my_purchases.csv</em>&#39;)<br><strong>WHERE</strong> department.upper() == &#39;IT&#39; and purchase_ts is not Null<br><strong>GROUP</strong> BY 1<br><strong>ORDER</strong> BY 1<br><strong>TO</strong> json</pre><h3>SPyQL in Action</h3><p>I think the best way for getting to know SPyQL and getting comfortable with the command-line is to open a terminal and solve a problem. In this case, we will try to understand the geographical distribution of cell towers. Let’s start!</p><h4>Setup</h4><p>Let’s start by installing SPyQL:</p><pre>$ pip3 install -U spyql</pre><p>and check its version:</p><pre>$ spyql --version<br>spyql, version 0.8.0</pre><p>Let’s also install <a href="https://github.com/dcmoura/matplotcli">MatplotCLI</a>, a utility for creating plots from the command-line that leverages <a href="https://github.com/matplotlib/matplotlib">Matplotlib</a>:</p><pre>$ pip3 install -U matplotcli</pre><p>Finally, we will download some sample data (you can alternatively copy-paste the URL to your browser and download the file from there):</p><pre>$ wget <a href="https://raw.githubusercontent.com/dcmoura/blogposts/master/spyql_cell_towers/sample.csv">https://raw.githubusercontent.com/dcmoura/blogposts/master/spyql_cell_towers/sample.csv</a></pre><p>This CSV file contains data about cell towers that were added to the <a href="https://www.opencellid.org/">OpenCellid database </a>on 2022 September 10. ( OCID-diff-cell-export-2022–09–10-T000000.csv file from the <a href="https://www.opencellid.org/">OpenCellid</a> project redistributed without modificatio ns under the <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>).</p><h4>Inspecting the data</h4><p>Let’s look to the data by getting the first 3 lines of the file:</p><pre>$ head -3 <em>sample.csv</em></pre><pre>radio,mcc,net,area,cell,unit,lon,lat,range,samples,changeable,created,updated,averageSignal<br>GSM,262,2,852,2521,0,10.948628,50.170324,15762,200,1,1294561074,1662692508,0<br>GSM,262,2,852,2501,0,10.940241,50.174076,10591,200,1,1294561074,1662692508,0</pre><p>You could do this same operation with SPyQL:</p><pre>$ spyql &quot;<strong>SELECT</strong> * <strong>FROM</strong> csv <strong>LIMIT</strong> 2&quot; &lt; <em>sample.csv</em></pre><p>or</p><pre>$ spyql &quot;<strong>SELECT</strong> * <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>LIMIT</strong> 2&quot;</pre><p>Notice that we are telling to get 2 rows of data and not 3 rows of the file (where the first is the header). One advantage of SPyQL is that we can change the output format easily. Let’s change the output to JSON and look to the first record:</p><pre>$ spyql &quot;<strong>SELECT</strong> * <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>LIMIT</strong> 1 <strong>TO</strong> json(indent=2)&quot;</pre><pre>{<br>  &quot;radio&quot;: &quot;GSM&quot;,<br>  &quot;mcc&quot;: 262,<br>  &quot;net&quot;: 2,<br>  &quot;area&quot;: 852,<br>  &quot;cell&quot;: 2521,<br>  &quot;unit&quot;: 0,<br>  &quot;lon&quot;: 10.948628,<br>  &quot;lat&quot;: 50.170324,<br>  &quot;range&quot;: 15762,<br>  &quot;samples&quot;: 200,<br>  &quot;changeable&quot;: 1,<br>  &quot;created&quot;: 1294561074,<br>  &quot;updated&quot;: 1662692508,<br>  &quot;averageSignal&quot;: 0<br>}</pre><h4>Querying the data</h4><p>Let’s first count how many records we have:</p><pre>$ spyql &quot;<strong>SELECT</strong> count_agg(*) <strong>AS</strong> n <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;)&quot;</pre><pre>n<br>45745</pre><p>Notice that aggregation functions have the suffix _agg to avoid conflicts with Python’s functions like min, max and sum.</p><p>Now, let’s count how many cell towers we have by type:</p><pre>$ spyql &quot;<strong>SELECT</strong> radio, count_agg(*) <strong>AS</strong> n <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>GROUP BY</strong> 1 <strong>ORDER BY</strong> 2 DESC <strong>TO</strong> pretty&quot;</pre><pre>radio        n<br>-------  -----<br>GSM      31549<br>LTE      12996<br>UMTS      1182<br>CDMA        16<br>NR           2</pre><p>Notice the pretty printing output. We can plot the above results by setting the output format to JSON and piping results into <a href="https://github.com/dcmoura/matplotcli">MatplotCLI</a>:</p><pre>$ spyql &quot;<strong>SELECT</strong> radio, count_agg(*) <strong>AS</strong> n <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>GROUP BY</strong> 1 <strong>ORDER BY</strong> 2 DESC <strong>TO</strong> json&quot; | plt &quot;<strong>bar</strong>(radio, n)&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bVbOK7aqhyWPsV11vnb8A.png" /><figcaption>Matplolib plot created by MatplotCLI using the output of a SPyQL query</figcaption></figure><p>How easy was that? :-)</p><h4>Querying the data: a more complex example</h4><p>Now, let’s get the top 5 countries with more cell towers added on that day:</p><pre>$ spyql &quot;<strong>SELECT</strong> mcc, count_agg(*) <strong>AS</strong> n <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>GROUP</strong> <strong>BY</strong> 1 <strong>ORDER</strong> <strong>BY</strong> 2 DESC <strong>LIMIT</strong> 5 <strong>TO</strong> pretty&quot;</pre><pre>  mcc      n<br>-----  -----<br>  262  24979<br>  440   5085<br>  208   4573<br>  310   2084<br>  311    799</pre><p>MCC stands for Mobile Country Code (262 is the code for Germany). The first digit of the MCC identifies the region. Here’s an exert from <a href="https://en.wikipedia.org/wiki/Mobile_country_code">Wikipedia</a>:</p><pre>0: Test networks<br>2: Europe<br>3: North America and the Caribbean<br>4: Asia and the Middle East<br>5: Australia and Oceania<br>6: Africa<br>7: South and Central America<br>9: Worldwide</pre><p>Let’s copy paste the above list of regions and create a new file name mcc_geo.txt. On the mac this is as easy as $ pbpaste &gt; mcc_geo.txt, but you can also paste this into a text editor and save it. Now, let’s ask SPyQL to open this file as a CSV and print its contents:</p><pre>$ spyql &quot;<strong>SELECT</strong> * <strong>FROM</strong> csv(&#39;<em>mcc_geo.txt</em>&#39;) <strong>TO</strong> pretty&quot;</pre><pre>  col1  col2<br>------  -------------------------------<br>     0  Test networks<br>     2  Europe<br>     3  North America and the Caribbean<br>     4  Asia and the Middle East<br>     5  Australia and Oceania<br>     6  Africa<br>     7  South and Central America<br>     9  Worldwide</pre><p>SPyQL detected that the separator is a colon and that the file has no header. We can use the <em>colN</em> syntax to address the <em>Nth</em> column. Now, let’s create a single JSON object with as many key-value pairs as input rows. Let the 1st column of the input be the <em>key</em> and the 2nd column be the <em>value</em>, and save the result to a new file:</p><pre>$ spyql &quot;<strong>SELECT</strong> dict_agg(col1,col2) <strong>AS</strong> json <strong>FROM</strong> csv(&#39;<em>mcc_geo.txt</em>&#39;) <strong>TO</strong> json(&#39;<em>mcc_geo.json</em>&#39;, indent=2)&quot;</pre><p>We can use cat to inspect the output file:</p><pre>$ cat <em>mcc_geo.json</em>                                               </pre><pre>{<br>  &quot;0&quot;: &quot;Test networks&quot;,<br>  &quot;2&quot;: &quot;Europe&quot;,<br>  &quot;3&quot;: &quot;North America and the Caribbean&quot;,<br>  &quot;4&quot;: &quot;Asia and the Middle East&quot;,<br>  &quot;5&quot;: &quot;Australia and Oceania&quot;,<br>  &quot;6&quot;: &quot;Africa&quot;,<br>  &quot;7&quot;: &quot;South and Central America&quot;,<br>  &quot;9&quot;: &quot;Worldwide &quot;<br>}</pre><p>Basically, we have aggregated all input lines into a Python dictionary, and then saved it as a JSON file. Try removing the AS json alias from the SELECT to understand why we need it :-)</p><p>Now, let’s get the statistics by region instead of by MCC. For this, we will load the JSON file that we just created (with the -J option) and do a dictionary lookup:</p><pre>$ spyql -Jgeo=<em>mcc_geo.json</em> &quot;<strong>SELECT</strong> geo[mcc//100] <strong>AS</strong> region, count_agg(*) <strong>AS</strong> n <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>GROUP</strong> <strong>BY</strong> 1 <strong>ORDER</strong> <strong>BY</strong> 2 DESC <strong>TO</strong> pretty&quot;</pre><pre>region                               n<br>-------------------------------  -----<br>Europe                           35601<br>Asia and the Middle East          5621<br>North America and the Caribbean   3247<br>Australia and Oceania              894<br>Africa                             381<br>South and Central America            1</pre><p>We do an integer division by 100 to get the 1st digit of the MCC and then we lookup this digit on the JSON we just created (which is loaded as a Python dictionary). This how we do a JOIN in SPyQL, via a dictionary lookup :-)</p><h4>Leveraging Python libs on your queries</h4><p>Another advantage of SPyQL is that we can leverage the Python ecosystem. Let’s try to do some more geographical statistics. Let’s count towers by H3 cell (resolution 5) for Europe. First, we need to install the <a href="https://github.com/uber/h3-py">H3 lib</a>:</p><pre>$ pip3 install -U h3</pre><p>Then, we can convert latitude-longitude pairs into H3 cells, count how many towers we have by H3 cell, and save results into a CSV:</p><pre>$ spyql &quot;<strong>IMPORT</strong> h3 <strong>SELECT</strong> h3.geo_to_h3(lat, lon, 5) <strong>AS</strong> cell, count_agg(*) <strong>AS</strong> n <strong>FROM</strong> csv(&#39;<em>sample.csv</em>&#39;) <strong>WHERE</strong> mcc//100==2 <strong>GROUP</strong> <strong>BY</strong> 1 <strong>TO</strong> csv(&#39;<em>towers_by_h3_res5.csv</em>&#39;)&quot;</pre><p>Visualising these results is fairly simple with Kepler. Just go to <a href="https://kepler.gl/demo">kepler.gl/demo</a> and open the above file. You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OILE5o2twQbYJNl43DYokw.png" /><figcaption>Kepler visualization of aggregations by H3 cell (resolution 5) from SPyQL</figcaption></figure><h3>Final words</h3><p>I hope you enjoyed SPyQL and that I could show you how simple it makes to query data from the command-line. In this first post about SPyQL, we are just scratching the surface. There is a lot more we can do. We have barely leveraged the Shell and Python ecosystems in this article. And we worked with a small file (SPyQL can handle GB-size files without compromising system resources). So, stay tuned!</p><p>Try out SPyQL and reach back to me with your thoughts. Thank you!</p><h3>Resources</h3><p>SPyQL repo: <a href="https://github.com/dcmoura/spyql">github.com/dcmoura/spyql</a></p><p>SPyQL documentation: <a href="https://spyql.readthedocs.io/">spyql.readthedocs.io</a></p><p>MatplotCLI repo: <a href="https://github.com/dcmoura/matplotcli">github.com/dcmoura/matplotcli</a></p><p>You can find me on <a href="https://twitter.com/daniel_c_moura">Tweeter</a>, <a href="https://www.linkedin.com/in/dmoura/">LinkedIn</a> and <a href="https://vimeo.com/danielcmoura">Vimeo</a>!</p><p>Article originally published at <a href="https://danielcmoura.com/blog/2022/spyql-cell-towers/">danielcmoura.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ac88f912d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/command-line-data-analytics-b2ac88f912d1">Command-Line Data Analytics Made Easy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[R vs. Python vs. Julia]]></title>
            <link>https://medium.com/data-science/r-vs-python-vs-julia-90456a2bcbab?source=rss-7cd388a0c4da------2</link>
            <guid isPermaLink="false">https://medium.com/p/90456a2bcbab</guid>
            <category><![CDATA[julia]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel Moura]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 12:30:36 GMT</pubDate>
            <atom:updated>2021-07-08T07:20:30.481Z</atom:updated>
            <content:encoded><![CDATA[<h4>How easy it is to write efficient code?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iu6-cGb4KpEzyd7djVI3lw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@biosss91?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austris Augusts</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>TL;DR: just jump to the Overall Comparison section</em></p><p>If you are a Data Scientist, chances are that you program in either Python or R. But there is a new kid on the block named Julia that promises C-like performance without compromising the way Data Scientists write code and interact with data.</p><p>In <a href="https://towardsdatascience.com/freeing-the-data-scientist-mind-from-the-curse-of-vectorization-11634c370107?source=friends_link&amp;sk=e7b0086f3678261cb64b6dbb43744613"><strong>my last post</strong></a>, I have compared R to Julia, showing how Julia brings a refreshening programming mindset to the Data Science community. The main takeaway is that with Julia, you no longer need to vectorize to improve performance. In fact, good use of loops might deliver the best performance.</p><p>In this post, I am adding Python to the mix. The language of choice of Data Scientists has a word to say. We will solve a very simple problem where built-in implementations are available and where programming the algorithm from scratch is straightforward. The goal is to understand our options when we need to write efficient code.</p><h3>Membership testing via linear search</h3><p>Let us consider the problem of membership testing on an unsorted vector of integers.</p><pre><strong>julia</strong>&gt; 10 ∈ [71,38,10,65,38]<br>true</pre><pre><strong>julia</strong>&gt; 20 ∈ [71,38,10,65,38]<br>false</pre><p>In principle, this problem is solved via linear search. The algorithm runs through the elements of the input vector until finding the value being searched (successful search) or reaching the end of the vector (unsuccessful search). The goal is to tell if a given integer is <strong>in</strong> the vector.</p><p>For evaluating different implementations in R, Python, and Julia, I generated a <a href="https://github.com/dcmoura/blogposts/raw/master/r_python_julia/vec.txt">dataset</a> with 1.000.000 unique integers ranging from 1 to 2.000.000 and performed 1.000 searches with all integers from 1 to 1.000. The probability of a search being successful is ~50%, so half the times the algorithm will scan the complete vector to conclude that the search was unsuccessful. In the remaining cases, the algorithm should require (<em>n+1)/2</em> evaluations (on average) to find the element, with <em>n</em> being the length of the vector.</p><p>I measured the performance of each implementation by taking the median CPU time of 3 runs. Additional information about the hardware and software for running experiments can be found <a href="https://github.com/dcmoura/blogposts/blob/master/r_python_julia/README">here</a>.</p><p><em>Please note that the goal of these experiments is not to make an accurate benchmark of the different languages and implementations. The goal is to highlight the hurdles that languages pose to data scientists when performance is important.</em></p><h3>C implementation</h3><p>I implemented the linear search in C to get a grasp on what would be the performance on a statically typed compiled language and to set the baseline. The binary executable took 0.26 seconds of CPU time to execute the 1.000 searches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ecd484d768169c2f03905acb96bbcf/href">https://medium.com/media/66ecd484d768169c2f03905acb96bbcf/href</a></iframe><h3>R implementation</h3><p>I tried different flavors of the membership test in R, from a specialized operator (in) to a C-like implementation using loops, passing by a vectorized approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0510f2fc665c69d5ec8136bdaaffa4b6/href">https://medium.com/media/0510f2fc665c69d5ec8136bdaaffa4b6/href</a></iframe><p>As we move from in_search to for_search we get higher control of the algorithm. However, as control increases, performance degrades in R. It is an order of magnitude faster to use a vectorized operation, as in vec_search, that does a full array scan than looping through the elements until finding a match. Like in <a href="https://towardsdatascience.com/freeing-the-data-scientist-mind-from-the-curse-of-vectorization-11634c370107?source=friends_link&amp;sk=e7b0086f3678261cb64b6dbb43744613">my previous post</a>, vectorization paid off despite requiring more memory and (redundant) operations. As expected, the specialized operator in has the highest performance and the cleaner code.</p><p>I also tried Map-Reduce operations, but did not have the patience to wait until they finished… not an option if you seek performance.</p><h3>Python implementation</h3><p>To be honest, the initial goal was to use only native functions and native data structures, but the in operator was ~10x slower than R when using Python’s native lists. So, I also included results with NumPy arrays (which bring vectorized operations to Python). CPU time went from 9.13 to 0.57 seconds, about 2 times the baseline. When moving to a loop approach, however, native lists took the edge by one order of magnitude… I gave NumPy a second chance by adding JIT compilation with the Numba package. There are limitations in Numba but it is simple to use: you just need to include the Numba package and tag the functions you want to see compiled JIT (and carefully read the manual). Loops with NumPy plus Numba deliver comparable (or better) performance than vectorized/specialized operations, but getting here was not easy as there are several traps in the way. Speaking about traps, performing loops on native lists with Numba was disappointing… again, I stopped execution because it was taking over 5 minutes to finish.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4ad321d87570f013259423e52ff7c6/href">https://medium.com/media/ed4ad321d87570f013259423e52ff7c6/href</a></iframe><h3>Julia implementation</h3><p>In Julia, I included a couple more flavors to show the diversity and performance of natively available functionalities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f949113b59afff0fb844b9af6bb5ddc2/href">https://medium.com/media/f949113b59afff0fb844b9af6bb5ddc2/href</a></iframe><p>Except for vectorized operations, the performance was pretty close to the implementation in C, with a degradation between 20%-50%. The vectorized performance was decent, about 4x C’s CPU time, but also about 2x NumPy’s CPU time on vectorized operations. The freedom you get is incredible, as you can code virtually any algorithm in Julia! For achieving top performance on for loops, I used hints to tell the compiler not to check if indexes are within bounds of the array (inbounds macro) and to tell the compiler it has extra liberties in the order it executes iterations (simd macro). In case you are wondering, not providing these hints would bring the loops’ performance close to the in_search.</p><h3>Overall comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OH_n58xfBC7HSP2U8ZC1GQ.png" /><figcaption>(plot made in R using ggplot2 and ggrepel)</figcaption></figure><p>Looking to results side by side for this simple problem, we observe that:</p><ul><li>Julia’s performance is close to C almost independently on the implementation;</li><li>The exception in Julia is when writing R-like vectorized code, with performance degrading about 3x;</li><li>When adding JIT compilation (Numba) to Python, loop-based implementations got close to Julia’s performance; still Numba imposes constraints on your Python code, making this option a compromise;</li><li>In Python, pick well between native lists and NumPy arrays and when to use Numba: for the less experienced it is not obvious which is the best data structure (performance-wise), and there is no clear winner (especially if you include the use case of adding elements dynamically, not covered here);</li><li>R is not the fastest, but you get a consistent behavior compared to Python: the slowest implementation in R is ~24x slower than the fastest, while in Python is ~343x (in Julia is ~3x);</li><li>Native R always performed better than native Python;</li><li>Whenever you cannot avoid looping in Python or R, element-based looping is more efficient than index-based looping.</li></ul><h3>Details matter…</h3><p>I could stop the article right here and write how seamless it is to write efficient code in Julia. Still, details matter, and the programmer needs to be mindful of Julia’s internals. Can you guess what is the line of <a href="https://github.com/dcmoura/blogposts/blob/master/r_python_julia/linear_search.jl">code</a> that most affects performance? Here is a hint: you will not find it in any of the snippets presented before…</p><p>Here it is:</p><pre>map(line -&gt; parse(Int, line), eachline(f))</pre><p>This line of code parses the input text file <em>f</em>, which contains one number per line (note that reading the file is not part of the benchmark). So, what is it so special about this line of code? In a nutshell, Julia infers that:</p><ul><li>the type of the elements returned by the anonymous function (first argument of map) is (always) integer;</li><li>the output of the mapping is, therefore, an array of integers.</li></ul><p>Since Julia knows that is storing an array of integers, it allocates a contiguous block of memory where each item contains an integer. This allows for efficient read operations.</p><p>How can we mess up? Here is one way:</p><pre>a = []<br>for line in eachline(f)<br>    push!(a, parse(Int, line))<br>end</pre><p>Seems similar, right? However:</p><pre>&gt; typeof(a)<br>Array{Any,1}</pre><p>The sentence a = []<em>, </em>as convenient as it might look, creates an array of Any, meaning that you can store any type of data on each element of the array. Internally, Julia stores an array of pointers in memory for cooping with the flexibility that Any provides. As a result, Julia can no longer process a sequential contiguous block of memory when processing the array. What is the impact on performance? A<strong>bout 50 to 100 times slower</strong>!</p><p>Fixing this code would be fairly simple: a = Int[] (instead of a = []) would do the job as it specifies the type of the elements.</p><h3>Bottom line</h3><p>From all the languages covered in this article, Julia clearly is the easiest to write efficient code. Still, you need to know what you are doing. Fortunately, <a href="https://docs.julialang.org/en/v1/manual/performance-tips/">performance tips</a> are available that can put you on the right track.</p><p>Happy coding!</p><p><em>p.s. I use all three languages regularly and I love them all. Each one has its place.</em></p><p><strong>Code available at</strong> <a href="https://github.com/dcmoura/blogposts">github.com/dcmoura/blogposts</a></p><p>You can find me on <a href="https://twitter.com/daniel_c_moura">Tweeter</a>, <a href="https://www.linkedin.com/in/dmoura/">LinkedIn</a> and <a href="https://vimeo.com/danielcmoura">Vimeo</a> (<strong>check out my datavizs!</strong>)</p><p>If you liked this article, you might also enjoy <a href="https://towardsdatascience.com/freeing-the-data-scientist-mind-from-the-curse-of-vectorization-11634c370107"><strong>Freeing the data scientist mind from the curse of vectoRization</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90456a2bcbab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/r-vs-python-vs-julia-90456a2bcbab">R vs. Python vs. Julia</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Freeing the data scientist mind from the curse of vectoRization]]></title>
            <link>https://medium.com/data-science/freeing-the-data-scientist-mind-from-the-curse-of-vectorization-11634c370107?source=rss-7cd388a0c4da------2</link>
            <guid isPermaLink="false">https://medium.com/p/11634c370107</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[julia]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Daniel Moura]]></dc:creator>
            <pubDate>Wed, 07 Aug 2019 22:30:15 GMT</pubDate>
            <atom:updated>2019-08-20T22:32:56.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>Julia to the rescue!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRppeOgJz5ofmntBwmix0g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dhudson_creative?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Debby Hudson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Nowadays, most data scientists use either Python or R as their main programming language. That was also my case until I met Julia earlier this year. Julia promises performance comparable to statically typed compiled languages (like C) while keeping the rapid development features of interpreted languages (like Python, R or Matlab). This performance is achieved by just-in-time (JIT) compilation. Instead of interpreting code, Julia compiles code in runtime. While JIT compilation has been around for sometime now (e.g. <a href="https://blogs.mathworks.com/loren/2016/02/12/run-code-faster-with-the-new-matlab-execution-engine/">Matlab introduced it in 2002</a>), Julia was designed for performance with JIT compilation in mind. Type stability and multiple-dispatch are key design concepts in Julia that put it apart from the competition. There is a <a href="https://ucidatascienceinitiative.github.io/IntroToJulia/Html/WhyJulia">very nice notebook</a> by the Data Science Initiative at the University of California that explains these concepts if you want to learn more.</p><p>Somewhere in time, we started using interpreted languages for handling large datasets (I guess datasets grew bigger and bigger and we kept using the same tools). We learned that, for the sake of performance, we want to avoid loops and recursion. Instead, we want to use vectorized operations or specialized implementations that take data structures (e.g. arrays, dataframes) as input and handle them in a single call. We do this because in interpreted languages we pay an overhead for each time we execute an instruction. While I was happy coding in R, it involved having a set of strategies for avoiding loops and recursion and many times the effort was being directed to “how do I avoid the pitfalls of an interpreted language?”. I got to a point where I was coding C functions to tackle bottlenecks on my R scripts and, while performance clearly improved, the advantages of using R were getting lost in the way. That was when I started looking for alternatives and I found Julia.</p><p>In this post, we will start by solving a simple problem in R where I will try to illustrate the mindset and limitations when programming in interpreted languages. Then, we will solve the same problem with Julia, showing how the mindset differs completely and how C-like performance can be achieved out of the box.</p><h3>The vectorization pathway</h3><p>Sometimes it is not clear how to get the best performance using vectorization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-dVCgnlVSTUIPKRbqUhSA.png" /></figure><p>Let us consider the problem of finding the distances between all combinations of pairs of points, given a vector of points. For the sake of simplicity, points have one dimension and we will use the L1-distance. Given the input [5, 3, 9, 1] the expected output is [2, 4, 4, 6, 2, 8] (resulting from |5–3|, |5–9|, |5–1|, |3–9|, |3–1| and|9–1|).</p><p>This problem is solved in R using the dist function of the stats package:</p><pre>&gt; as.vector(<strong>dist(</strong>c(5, 3, 9, 1), method=”manhattan”<strong>)</strong>)<br>[1] 2 4 4 6 2 8</pre><p>R’s implementation returns a distance matrix that we convert into a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*QoOv_EZNnCvozOi_OBC1tQ.png" /><figcaption>Distance matrix: gray cells are redundant</figcaption></figure><p>Let us pretend that dist is not available. How would you code it in R?</p><p>Solving this problem with a loop-based approach is straightforward: we need an outer loop for iterating over the first element of the pair and an inner loop for the second element. Since the L1-distance is symmetric (|<em>a-b| = |b-a|</em>), we just need to do this for half the combinations, while avoiding calculating the distances of points to themselves (the diagonal of the matrix). A loop-based implementation in R would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a56f4d15f2f29b4c0d57bb8a49b93f22/href">https://medium.com/media/a56f4d15f2f29b4c0d57bb8a49b93f22/href</a></iframe><p>If you program in R, you would say that this is not proper R code… loops are slow and produce very verbose code… there should be a way of vectorizing.</p><p>One way to drop loops is by generating vectors with all combinations of pairs. Basically, we are finding the (row, column) coordinates of the lower triangle of the distance matrix. Then, we can calculate the distances with a single vectorized operation. We know that we are paying a memory penalty, but we hope that the vectorization pays off.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e51bdf9b6b2124fa3113776134287b58/href">https://medium.com/media/e51bdf9b6b2124fa3113776134287b58/href</a></iframe><p>Another alternative is to use R’s outer function for generating a matrix with the differences between all combinations of two points (including redundant combinations). Then, we only need to retrieve the absolute value of the lower triangular part of the matrix. We might feel reluctant because we are making ~2 times more operations (and storing them in memory), but this does result in cleaner and more readable code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a557bc3ae9cf5673605f4bfd7e3427/href">https://medium.com/media/62a557bc3ae9cf5673605f4bfd7e3427/href</a></iframe><p>As we travel along the vectorization pathway, the code is becoming more compact, but is it becoming faster? We are exchanging compactness by more memory and more operations… it is not trivial to predict which of these implementations is the most efficient.</p><p>We could go on an on trying to figure out what is the best way to avoid the pitfalls of R when we already have a simple loop-based solution (which would be difficult to beat in a compiled language). So, if this function is performance-critical, it might make sense to implement it in C, CPP or Fortran. A CPP translation of the original implementation, integrated with R via the Rcpp library, would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84260a35f2d7bc8f18aa74617e6bc180/href">https://medium.com/media/84260a35f2d7bc8f18aa74617e6bc180/href</a></iframe><h4>Experiments</h4><p>I ran the different implementations 3 times each with vectors of 10.000 random numbers (requiring 49.995. 000 distance calculations when avoiding redundancy, 100.000.000 otherwise) and took the median CPU time and memory consumption. I used a 2017 MacBook Pro, 2.3 GHz Intel Core i5, 16 GB RAM running Mac OS 10.14 with R 3.6.0, Julia 1.0.3 and XCode 10.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7CjtOKJ_X0uWVjGXeHyyg.png" /></figure><p>The loop-based implementation in R was the slowest, as expected (and would be much slower before version 3.4 where JIT became available). By vectorizing, we decrease computation time but increase memory consumption, which can become a problem as the size of the input increases. Even after our vectorization efforts, we are still far from the performance of R’s dist function.</p><p>Rcpp allowed decreasing both computation time and memory requirements, outperforming R’s core implementation. This is not surprising as R’s dist function is much more flexible, adding several options and input validation. While it is great that we can inject C/CPP code into R scripts, now we are dealing with two programming languages and we have lost the goodies of interactive programming for the CPP code.</p><h3>Julia’s way</h3><p>Julia’s programming mindset differs completely from R’s. The most efficient solution is attained by a loop-based approach that preallocates memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a509951a3218cce469c6d4b38acbb2c6/href">https://medium.com/media/a509951a3218cce469c6d4b38acbb2c6/href</a></iframe><p>If you want to write less code, you can do so at the expense of computational efficiency. One way of compressing code is through comprehensions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81550f2f6b031d55ed9823d7d0017115/href">https://medium.com/media/81550f2f6b031d55ed9823d7d0017115/href</a></iframe><p>The above comprehension is much more compact than the loop-based implementation while embodying the same logic. The main disadvantage of this approach is that the output vector is not preallocated. Since the compiler cannot predict the size of the output, the output grows dynamically as needed.</p><p>Finally, if you prefer a vectorized approach, you also have that choice in Julia. Translating R’s implementation based on the outer function would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f743c1c1303e3c39d1bdc17bcd3eab1a/href">https://medium.com/media/f743c1c1303e3c39d1bdc17bcd3eab1a/href</a></iframe><p>Unlike in R, we expect this to be the least efficient approach since it requires more memory and unnecessary (redundant) operations.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puHzUypaaA1X-H1qT1tQfA.png" /></figure><p>Julia stands out by delivering C-like performance out of the box. The tradeoff between code compactness and efficiency is very clear, with C-like code delivering C-like performance. Comprehensions are a good compromise as they are simpler to code, less prone to bugs, and equally memory-efficient for this problem.</p><p>When using R for tackling computational intensive tasks, we hope to find a specialized function to solve our problem. If a specialized function is not available, we either need to program it in C/CPP or go through the vectorization pathway. If we choose the second, we will probably end up far from the performance we would get from the first.</p><h3>Closing thoughts</h3><p>Vectorization, comprehension, map-filter-reduce are all great tools that can save you time and deliver a more compact and readable code. However, programmers should not be forced to use them because of performance limitations of the programming language. You do not want to spend your time experimenting several ways to implement a solution when there is a straightforward and otherwise efficient implementation.</p><p>Julia allows you to choose between code compactness and computational efficiency, making this tradeoff very clear. You can implement C-like loops, R-like vectorizations, or Python-like comprehensions. It’s up to you. You can optimize the ratio between the time you need to code the solution and the time the solution takes to run. You can implement your own algorithms without relying on a second language.</p><p>Being much younger than Python and R, Julia is fighting its way through the data science community. I loved when I started using Matlab 13 years ago because of the way I could interact with data. I am now loving how I can write faster code faster and how I am free to implement virtually any algorithm in Julia. Give it a go, I am sure you will love it too!</p><p><strong>Code available at:</strong> <a href="https://github.com/dcmoura/blogposts">github.com/dcmoura/blogposts</a></p><p>You can find me on <a href="https://twitter.com/daniel_c_moura">Tweeter</a>, <a href="https://www.linkedin.com/in/dmoura/">LinkedIn</a> and <a href="https://vimeo.com/danielcmoura">Vimeo</a> (check out my datavizs!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11634c370107" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/freeing-the-data-scientist-mind-from-the-curse-of-vectorization-11634c370107">Freeing the data scientist mind from the curse of vectoRization</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>