<?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 Leo Lezcano on Medium]]></title>
        <description><![CDATA[Stories by Leo Lezcano on Medium]]></description>
        <link>https://medium.com/@LeoLezcano?source=rss-2c55727373d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*xEpNqruNWfFpcu-UT3KCUw.jpeg</url>
            <title>Stories by Leo Lezcano on Medium</title>
            <link>https://medium.com/@LeoLezcano?source=rss-2c55727373d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:16:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@LeoLezcano/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[The Walmart.com Journey Towards Spanish Query Understanding (Part 1)]]></title>
            <link>https://medium.com/walmartglobaltech/the-walmart-com-journey-towards-spanish-query-understanding-part-1-e08e3b348dcc?source=rss-2c55727373d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e08e3b348dcc</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-translation]]></category>
            <category><![CDATA[cross-lingual]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[domain-adaptation]]></category>
            <dc:creator><![CDATA[Leo Lezcano]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 23:59:21 GMT</pubDate>
            <atom:updated>2023-06-13T18:44:36.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-768Wgi5FB9zydIiH0y3EA.png" /></figure><h3>The Walmart.com Journey Towards Spanish Query Understanding</h3><h4>Opportunity statement and challenges</h4><p>Online stores in the United States offer a unique scenario for <a href="https://en.wikipedia.org/wiki/Cross-language_information_retrieval">Cross-Lingual Information Retrieval (CLIR)</a> due to the mix of Spanish and English inside and across queries. While State-of-the-art Machine Translation (MT) provides an opportunity to lift relevance by translating the Spanish queries to English before delivering them to the search engine, there are domain specific challenges in product search that render the raw application of generic MT an impractical solution.</p><h3>Table of Contents</h3><h4><a href="#39b7">Part 1: Opportunity statement and challenges</a></h4><p>—<a href="#3f7c">USA is home to the 2nd largest Spanish speaking population</a> <br> — <a href="#326e">The impact of COVID-19 in purchasing habits</a><br> — <a href="#3020">Walmart reaction to the influx of Spanish in the search bar</a><br> — <a href="#d35a">Challenges of Spanish query translation</a></p><h4><strong>Part 2: Translatability and Translation of Spanish queries</strong></h4><p>This article covers the first part, opportunity statement and challenges. For the second part, we have published an open access paper titled <a href="https://dl.acm.org/doi/abs/10.1145/3543873.3587660">Cross-lingual Search for e-Commerce based on Query Translatability and Mixed-Domain Fine-Tuning</a>.</p><h3>USA is home to the 2nd largest Spanish speaking population</h3><p>According to the<a href="https://www.census.gov/library/stories/2021/08/improved-race-ethnicity-measures-reveal-united-states-population-much-more-multiracial.html"> 2020 US Census</a>, the United States is now home to 62 million Spanish speakers, representing 18.7% of its population. More people speak Spanish in US than in any other country in the world, except for Mexico. Moreover, this dominance of US amongst Spanish speaking nations is consolidating. According to the <a href="https://www.pewresearch.org/fact-tank/2021/09/09/key-facts-about-u-s-latinos-for-national-hispanic-heritage-month/">Pew Research Center</a>, hispanics accounted for half of the US population increase from 2010 to 2020, a greater share than any other racial or ethnic group. It was also an increase of 23% over the previous decade, outpacing the nation’s 7% overall population growth.</p><h4>The impact of COVID-19 in purchasing habits</h4><p>While physical stores have traditionally allowed the non-English speaking customers to visually find a product, the e-commerce search experience requires familiarity with specific English terms. With about 70% of Hispanics <a href="https://www.pewresearch.org/fact-tank/2021/09/09/key-facts-about-u-s-latinos-for-national-hispanic-heritage-month/ft_2021-09-09_keyfactslatinos_08/">speaking Spanish at home</a>, such English terminology is frequently lacking.</p><p>When the pandemic hit US soil, Spanish speakers had no choice but to textually submit their every day grocery needs, cuisine needs and merchandizing needs into online stores and remote delivery systems. As professor Scott Galloway put it, the pandemic was an accelerant that <a href="https://www.inc.com/magazine/202102/scott-galloway/post-corona-crisis-opportunity-book.html">fast-forwarded 10 years</a> of adoption in online shopping and remote delivery services, amongst other trends.</p><p>A survey by <a href="https://www.shopify.com/enterprise/how-to-sell-internationally-online">Shopify</a> on multilingual support in eCommerce showed a <strong>13%</strong> relative increase in conversion when buyers were shown a store translated into their language. And CSA results from the series<strong> </strong><a href="https://csa-research.com/Blogs-Events/Blog/do-b2b-buyers-value-localization"><strong>“Can’t Read, Won’t Buy”</strong></a><strong> </strong>arrived to the following stats<strong>:</strong></p><ul><li><strong>“65%</strong> of consumers prefer content in their native language”</li><li><strong>“40%</strong> will not buy from websites in other languages”</li><li><strong>“66% </strong>of business users told us they’d pay up to 30% more for a localized product”</li><li><strong>“34%</strong> of consumers said they would also be willing to dig deeper into their wallets for products adapted to their language and market”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRvcASqnokCwB4LG44nKJg.png" /></figure><h4>Walmart reaction to the influx of Spanish in the search bar</h4><p>At Walmart.com, we started noticing an influx of Spanish searches as COVID-19 pandemic restrictions increased, and in-store customers began shifting to online shopping. At the height of the pandemic, Spanish queries across the Walmart app and website increased more than <strong>five times</strong> their pre-pandemic levels.</p><p>This rapid shift in behavior highlighted the need to bring Spanish Query Understanding, as it can drastically improve relevance and reduce null and low results for queries written in a language other than English. Given that our US Store and Online were indexed in English, a new layer of language detection, translation and understanding was needed to retrieve relevant items for non-English queries.</p><p>We quickly mobilized and rolled out a minimum viable product (MVP) a few months later. Our initial release has been followed by a sequence of back-end and front-end improvements that have led to where we are today, a domain-adapted query translation system that will be covered in Part 2 of this series.</p><h3>Challenges of Spanish query translation</h3><p>With some of them being associated to polysemy, and others to the anglo-hispanic blend colloquially known as Spanglish, this section introduces the challenges that we have faced in the pursue of an accurate and efficient Spanish Query Understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*itPk7O1S3gUlB897ckk6ZA.png" /></figure><p><strong>Challenge #1 — Non-Translatable entities:</strong> Contrary to generic text, product oriented queries carry a high density of named entities, such as brands, movie titles, product lines, or names of sport teams. An example is the entity <em>“corona”</em> (<em>“crown”</em> in English) which should not be translated when referring to the beer brand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mNXEhA_upqxyUDIqgcez6Q.png" /></figure><p><strong>Challenge #2 — Spanish Ambiguity:</strong> The polysemic <em>“muñeca”</em> can be translated to <em>“wrist”</em> or <em>“doll”</em> depending on the context. When such context is lacking, ambiguity can be controlled by biasing the translation towards product interpretations, i.e., intent is assumed to be <em>“doll”</em>. On the other hand, the Spanish search “<em>calabaza</em>” can be translated to either <em>“butternut squash”</em> or <em>“pumpkin”</em> products, making the disambiguation less straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*ISVJAg4ViWCZvEtItY2Qlw.png" /></figure><p><strong>Challenge #3 — Cross-Language Ambiguity:</strong> The lack of context may also harm language detection; e.g., while in English <em>“pie”</em> and <em>“pan”</em> relate to <em>“pastry”</em> and <em>“cookware”</em>, respectively, the same morphemes mean <em>“foot”</em> and <em>“bread”</em> in Spanish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*f_niX8mM0MCnEvy_JkTiNg.png" /></figure><p><strong>Challenge #4 — Query Translatability: </strong>Beyond accuracy, the translation of queries is not the final goal but the means to relevant results. Offering the best results requires not only detecting Spanish but also deciding whether to automatically translate or not. For example, if translated, the Spanish query <em>“cuentos de hadas”</em> (<em>“fairy tales”</em>) would lose its implicit Spanish intention, and <em>“queso blanco”</em> (<em>“white cheese”</em>) would not imply the Latin American style of cheese.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Efuj0p5IDOO9-BDFVyZVkw.png" /></figure><p><strong>Challenge #5 — Mixed language queries:</strong> Also known as Spanglish, Hispanic customers in the US frequently mix Spanish and English in the same query, e.g., <em>“cake de fresa”</em>, <em>“colchón queen”</em> or <em>“display grande”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*16hWxIkGe_jft4ZIIw2udA.png" /></figure><p><strong>Challenge #6— Spanish dialects:</strong> The US Hispanic immigration is rooted in more than 10 Spanish-speaking countries. The table below shows the distribution of origin, as well as the US state with the largest population of hispanics with such origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*dBqBi497_6rKtd-faovYmQ.png" /><figcaption><a href="https://es.wikipedia.org/wiki/Latino_(Estados_Unidos)">https://es.wikipedia.org/wiki/Latino_(Estados_Unidos)</a></figcaption></figure><p>Different regions enrich the Spanish language with different dialects, leading to a variety of terms that sometimes converge to the same English intention. For example, there are <a href="https://www.speakinglatino.com/spanish-words-for-popcorn/">15+ Spanish words for <em>“popcorn”</em><strong><em> </em></strong>across Latin America</a>, 5+ for <em>“appetizer”</em>, 3+ for “avocado”, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*uGqIx0h5r2LmI8LkUO5VDA.png" /></figure><p>The distribution of origin listed above leads to an unbalanced distribution in the usage of Spanish dialects and variations across the states. For example, our online customers from CA and TX most frequently refer to <em>“pools”</em> as <em>“albercas”</em>, while FL customers usually prefer <em>“piscinas”</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHvJOKivPE4w9WqrLcg0jg.png" /><figcaption>Dominant query variations by state as submitted to Walmart.com</figcaption></figure><p><strong>Challenge #7 — Evaluation from a Search perspective: </strong><a href="https://en.wikipedia.org/wiki/Discounted_cumulative_gain">nDCG</a> and <a href="https://en.wikipedia.org/wiki/A/B_testing">A/B tests</a> are traditional instruments to assess the statistical significance of multiple metrics for a new Search feature, including <a href="https://en.wikipedia.org/wiki/Relevance_(information_retrieval)">relevance</a>, <a href="https://en.wikipedia.org/wiki/Click-through_rate">CTR</a> and <a href="https://en.wikipedia.org/wiki/Gross_merchandise_volume">GMV</a>. These instruments can be used to evaluate the impact of translation in search, however we should keep in mind the following:</p><ul><li>These are end to end instruments that evaluate not just the quality of translation but how well it plays with the rest of the search stack to offer an effective product search experience.</li><li>The success of nDCG, when query translation is involved, requires the participation of bilingual judges so that the ratings of the Query-Item pairs that feed the test can be accurate.</li><li>For A/B testing, we ideally sample users that could be impacted by the query translation. However this is challenging in a diverse and multilingual society like US, where users frequently mix traffic in the language under study (eg. Spanish) with the dominant English. This may lead to noisy signals and neutral results.</li></ul><p><strong>Challenge #8 — Evaluation from a Translation perspective:</strong></p><ul><li>The <strong>B</strong>i<strong>L</strong>ingual<strong> E</strong>valuation<strong> U</strong>nderstudy​ (<a href="https://en.wikipedia.org/wiki/BLEU">BLEU</a>) metric is vastly adopted by the machine translation community. It belongs to the family of n-gram matching algorithms that offer simple and inexpensive implementations with high explainability. However, it has historically suffered from intolerance to paraphrasing and token order change in semantically correct translations.</li><li>To compensate for BLEU’s limitations, there has been a growing interest on metrics based on semantic similarity. <strong>BERTScore</strong> leverages contextualized token embeddings​ to tolerate synonyms, paraphrasing and distant dependencies in semantically correct translations. However, these approaches offer less explainability and are susceptible to the compatibility between the selected encoder and the domain under study. For example, a BERTscore could find “corona beer” and “crown beer” to be semantically close given that both “corona” and “crown” are beer brands, however, “crown beer” is an incorrect translation for “cerveza corona”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuixAXhZFvTTBmpTWWElyg.png" /></figure><p><strong>Challenge #9 — Latency:</strong> For online stores serving millions of customers, the real-time speed of the translation is as important as its accuracy.</p><p><strong>Challenge #10 — Cold start:</strong> When supporting a secondary language in an IR system, its query activity is scarce until awareness grows amongst customers. This impacts the click-through data that could be leveraged for domain adaptation purposes.</p><p>This article has covered the first part, opportunity statement and challenges. The domain-adapted query translation system that has iteratively evolved inside Walmart Search to address the 10 challenges we covered above is documented in our open access paper <a href="https://dl.acm.org/doi/abs/10.1145/3543873.3587660">Cross-lingual Search for e-Commerce based on Query Translatability and Mixed-Domain Fine-Tuning</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e08e3b348dcc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/the-walmart-com-journey-towards-spanish-query-understanding-part-1-e08e3b348dcc">The Walmart.com Journey Towards Spanish Query Understanding (Part 1)</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Java ready for functional programming?]]></title>
            <link>https://medium.com/@LeoLezcano/java-streams-opportunities-for-improvement-95324bed7bbf?source=rss-2c55727373d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/95324bed7bbf</guid>
            <category><![CDATA[javastreams]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Leo Lezcano]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 06:07:35 GMT</pubDate>
            <atom:updated>2020-06-18T19:01:28.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBxG2N1iXoXed6HD9KT2RQ.jpeg" /><figcaption>Photo by author. Temple of Poseidon, 2010.</figcaption></figure><h4>Limitations to consider when adopting Java Streams</h4><p>When it comes to data processing tasks, I’ve enjoyed in recent years the migration of imperative code to its functional equivalent in Scala. However, dealing with Java Streams has not being equally pleasant due to the issues below. I’m sure they will improve over time, making more and more scenarios suitable for the adoption of functional programming<strong>.</strong></p><ul><li><strong>Lack of native support for tuples</strong>: The functional style, particularly when using <em>maps</em> and <em>flatmaps</em>, frequently leads to the need of Tuples to preserve code simplicity. Unlike Scala, Java doesn’t natively support tuples, forcing a variety of workarounds like: a) importing third party libraries; or b) using the <em>Entry class</em>. These may affect the consistency of the streams adoption and have an impact on performance.</li><li><strong>Handling Exceptions</strong>: When migrating imperative Java code to streams, exception handling frequently leads to headaches, especially because of checked exceptions and because the functional style sees a block of stream operations (<em>maps</em>, <em>filters</em>, etc.) as an step will succeed or not. Trying to handle exceptions inside a stream block feels similar to handling exceptions inside a SQL query. The practice is often that of avoiding the exception at all, rather than handling it.</li><li><strong>Stream block debugging</strong>: For reasons similar to the bullet above, debugging a chunk of functional code is awkward if traditional debugging approaches are used. Sometimes the convenient one-line anonymous lambdas have to be expanded to multiple lines to better support debugging, or something like <em>IntelliJ Java Stream Debugger plugin</em> is required to facilitate debugging.</li><li><strong>Logging, Testing, and the IllegalStateException</strong>: The fact that Java streams, define a DAG that has to be operated/executed every time you want to read the result can have an impact both in performance and code simplicity when logs are added to the code. A typical scenario is that a <em>stream.count()</em> is added after a un-collected functional block to log the size of the intermediate results. At that point the stream has been operated and trying to collect again will lead to and exception.</li><li><strong>Ambiguity in Static vs Instance method referencing</strong>: Given the code below, a <strong>Stream&lt;C&gt;.map(C::m)</strong> is ambiguous as can refer to both the <strong>static m()</strong> as well as the <strong>instance m()</strong>. Such problem doesn’t happen in Scala where <strong>C.m</strong> is different from<strong> _.m</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f917816497256e9b8f55c534e3514752/href">https://medium.com/media/f917816497256e9b8f55c534e3514752/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95324bed7bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A modern guide to Spark RDDs]]></title>
            <link>https://medium.com/data-science/a-modern-guide-to-spark-rdds-725cd7c14059?source=rss-2c55727373d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/725cd7c14059</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[spark-rdd]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Leo Lezcano]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 17:06:33 GMT</pubDate>
            <atom:updated>2020-06-17T09:24:56.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBBDvMrwUuLBHBZGmZke5w.jpeg" /><figcaption>Photo by author. Altea, Spain, Spring 2011.</figcaption></figure><h4>Everyday opportunities to reach the full potential of PySpark</h4><p>The web is full of Apache Spark tutorials, cheatsheets, tips and tricks. Lately, most of them have been focusing on <a href="https://spark.apache.org/docs/latest/sql-programming-guide.html">Spark SQL and Dataframes</a>, because they offer a gentle learning curve, with a familiar SQL syntax, as opposed to the steeper curve required for the older <a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html">RDD API</a>. However, it’s the versatility and stability of RDDs what ignited the Spark adoption in 2015, and turned it into a dominant framework for distributed data processing.</p><p>As you become a regular Spark user, mainly three circumstances will lead you to consider the RDD API:</p><ul><li>Accessing raw unstructured data sources</li><li>Performing data operations which are more suited for a general programming language than for SQL. Avoiding UDFs</li><li>Parallelizing the execution of a third party library</li></ul><p>This opinionated material covers such circumstances and the questions that frequently arise from them, so that you can enjoy the full potential of PySpark.</p><h3>Table of Contents</h3><p><a href="#c5f3">A note on style</a><br>— <a href="#78aa">Grow your functional python vertically</a><br>— <a href="#645c">Append the Spark type to variable names</a></p><p><a href="#c7c6">Turning Dataframes into RDDs &amp; vice versa</a><br>— <a href="#e69f">Dataframe to RDD</a><br> — <a href="#c178">RDD to Dataframe</a></p><p><a href="#c047">The expressive Python dictionaries</a><br>— <a href="#25aa">One-line dictionary transformations</a><br>— <a href="#c1df">Python sets &amp; dictionaries are unhashable</a></p><p><a href="#9638">Caching &amp; Broadcasting</a><br>— <a href="#2a90">Caching RDDs</a><br>— <a href="#7b71">Unpersisting RDDs</a><br>— <a href="#bf34">Cleaning the whole RDD cache</a></p><p><a href="#4aec">Distributed execution of Python libraries</a><br>— <a href="#f7cd">Numpy — A generic approach</a><br>— <a href="#b154">NLTK — Partition setup</a></p><h3>A note on style</h3><p>Code readability is particularly important when functional programming meets big data, on the one hand because traditional IDE debugging tools have been designed around imperative programming, and on the other, because multiple code runs for debugging purposes is expensive and time consuming.</p><h4>Grow your Functional Python vertically</h4><p>Spark logics are defined as <a href="https://data-flair.training/blogs/dag-in-apache-spark/">DAGs</a>. Keep the code narrow to improve readability by breaking the lines with a <strong>BACKSLASH “\”</strong> after every <a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html#transformations">transformation</a> or <a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html#actions">action</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/599086b30997535fa28ebe5233952709/href">https://medium.com/media/599086b30997535fa28ebe5233952709/href</a></iframe><h4>Append the Spark type to variable names</h4><p>Distributed data will largely fall into one of the three types:</p><ul><li><a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html">RDD</a></li><li><a href="https://spark.apache.org/docs/latest/sql-programming-guide.html">Dataframe</a></li><li><a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html#broadcast-variables">Broadcast Variable</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaf28532331755cdfe6daa16c9c88303/href">https://medium.com/media/eaf28532331755cdfe6daa16c9c88303/href</a></iframe><h3>Turning Dataframes into RDDs and vice versa</h3><p>The backbone of a Dataframe is an RDD[<a href="https://spark.apache.org/docs/2.3.4/api/python/pyspark.sql.html?highlight=row#pyspark.sql.Row">Row</a>], a Spark type that behaves very similar to a Python dictionary. As you can see below this <a href="https://spark.apache.org/docs/2.3.4/api/python/pyspark.sql.html?highlight=row#pyspark.sql.Row">Row</a> type serves as a bridge between the two APIs.</p><h4>Dataframe to RDD</h4><ul><li><strong>Approach:</strong> Dataframe -&gt; RDD[Row] -&gt; RDD[dict]</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9e2d382ab24cbe75124a82d8632cd5e/href">https://medium.com/media/b9e2d382ab24cbe75124a82d8632cd5e/href</a></iframe><h4>RDD to Dataframe</h4><ul><li><strong>Approach A:</strong> RDD[dict] -&gt; RDD[Row] -&gt; Dataframe</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c12c8ad60fb3c6d87bc2707fbf96a2c/href">https://medium.com/media/9c12c8ad60fb3c6d87bc2707fbf96a2c/href</a></iframe><ul><li><strong>Approach B:</strong> RDD[tuples] -&gt; Dataframe</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/830278a5ffe10323bb00a96476b77f5f/href">https://medium.com/media/830278a5ffe10323bb00a96476b77f5f/href</a></iframe><h3>The expressive Python dictionaries</h3><p>As the chain of operations on an RDD grows long, it’s challenging to keep the code readable and the logic understandable. Python dictionaries play a key role in this regard. As opposed to Scala tuples, they allow accessing fields by name rather than position, and as opposed to Scala Case Classes, they can be created in-line without previous external definition.</p><h4>One-line dictionary transformations</h4><p>Lambda functions are syntactically restricted to a single expression. In the common scenario where an RDD[dict] transformation is needed, consider these one-line lambdas. Note that <strong>**old_dict</strong> leads to a shallow copy, but no <a href="https://docs.python.org/3/library/copy.html">deepcopy operations</a> are required inside RDD operations, as PySpark guarantees the new dictionary to be totally independent, ie. <strong>RDDs are immutable</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/743893fccc4f30caf6057a89a07c0a2e/href">https://medium.com/media/743893fccc4f30caf6057a89a07c0a2e/href</a></iframe><h4>Python sets and dictionaries are unhashable types</h4><p>RDD aggregations such as <a href="https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.groupByKey">groupByKey</a> and <a href="https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.reduceByKey">reduceByKey</a> require the Key to be a hashable type for shuffling purposes. Therefore, avoid using Python dictionaries and sets as shuffling keys. If you must, consider using <strong>frozensets.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f7fad0c712d0f187de3f357e365465d/href">https://medium.com/media/6f7fad0c712d0f187de3f357e365465d/href</a></iframe><h3>Caching and Broadcasting</h3><p>Learning how to customize Spark’s distributed memory processing leads to optimal resource usage for ETLs and ML training jobs. Also, it’s the key ingredient of a fast and smooth <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL</a> experience for <a href="https://jupyter.org/">Jupyter</a> and <a href="https://zeppelin.apache.org/">Zeppelin</a> notebooks.</p><h4>Caching RDDs</h4><p>See <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html?highlight=cache#pyspark.RDD.cache">RDD.cache</a> for the common use case of persisting to MEMORY, or <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html?highlight=cache#pyspark.RDD.persist">RDD.persist</a> for other storage levels. Note that <strong>line 4</strong> below sets the caching instruction but only an action like <strong>line 6</strong> will trigger the DAG execution and subsequent storage in memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4a5db35cb6582979508d1a73d39dd1/href">https://medium.com/media/cf4a5db35cb6582979508d1a73d39dd1/href</a></iframe><h4>Unpersisting RDDs</h4><p>There are mainly two reasons to invoke <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html?highlight=cache#pyspark.RDD.unpersist">RDD.unpersist</a> and remove all its blocks from memory and disk:</p><ol><li>You’re done using the RDD, ie. all the <a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html#actions">actions</a> depending on the RDD have been executed, and you want to free up storage for further steps in your pipeline or ETL job.</li><li>You want to <em>modify</em> the persisted RDD, a frequent use case when working on Jupyter/Zeppelin notebooks. Given that RDDs are immutable, what you can do is reuse the RDD name to point to a new RDD. Therefore, if the code above is ran twice, you’ll end up with two allocations in memory of the same <strong>cached_rdd</strong>. After the first run, <strong>cached_rdd</strong> will point to the first allocation below, and then to the second, leaving the first allocation orphaned.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*GsgdVkO5btLcEXSZQ4_JNQ.png" /></figure><p>To avoid duplicate memory allocation, prepend a <strong>try-unpersist</strong> (line 1–4 below) to the Jupyter paragraph that initializes the RDD:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f859f7550542586d9b64a94c5db00d26/href">https://medium.com/media/f859f7550542586d9b64a94c5db00d26/href</a></iframe><h4>Cleaning the RDD cache</h4><p>Unpersisting all RDDs can be achieved as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5981f05c46d0250aac80c71dd0fc2a3b/href">https://medium.com/media/5981f05c46d0250aac80c71dd0fc2a3b/href</a></iframe><h3>Distributed execution of Python libraries</h3><p>The flexibility of RDDs allows to distribute the payload when running practically any Python code. For computationally inexpensive tasks such as <strong>O(n)</strong> and below, truly big data is required for the benefits of parallelization to be obvious. However, for above linear complexity, parallelization can easily turn hours of medium-sized data jobs into minutes, or minutes of small data jobs into seconds.</p><h4>Numpy — A generic approach</h4><p>In order to parallelize the execution of libraries such as <a href="https://www.statsmodels.org/">statsmodels</a>, <a href="https://scikit-learn.org/">scikit-learn</a>, <a href="https://numpy.org/">numpy</a>, simply invoke them from inside a <strong>map</strong>, <strong>flatMap</strong>, <strong>filter</strong> or any other <a href="https://spark.apache.org/docs/latest/rdd-programming-guide.html#transformations">transformation</a>. In the example below, the <strong>np.median</strong> call is inside an RDD map, therefore, it will run locally in each Spark executor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d78980ff30a4ab67339e46ca2c250bf1/href">https://medium.com/media/d78980ff30a4ab67339e46ca2c250bf1/href</a></iframe><h4>NLTK — Partition setup</h4><p>The Natural Language Toolkit (<a href="https://www.nltk.org/">NLTK</a>) library requires further setup in addition to importing it. The <a href="https://www.nltk.org/api/nltk.html#nltk.downloader.download">nltk.download</a> call in the example below must run in <strong>each executor</strong> to guarantee local nltk data availability. In such cases, consider using <a href="https://spark.apache.org/docs/latest/api/python/pyspark.html?highlight=mappartitions#pyspark.RDD.mapPartitions">RDD.mapPartitions</a> to avoid redundant calls to nltk.download inside the same executor. The RDD mapPartitions call allows to operate on the whole list of RDD entries for each partition, while the RDD map/flatMap/filter work on each RDD entry and offer no visibility to which partition the entry belongs to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c19fd97905c6bdf5439ece8a095147f/href">https://medium.com/media/3c19fd97905c6bdf5439ece8a095147f/href</a></iframe><p><strong>… more sections coming soon.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=725cd7c14059" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-modern-guide-to-spark-rdds-725cd7c14059">A modern guide to Spark RDDs</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>