<?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 Shachaf Poran on Medium]]></title>
        <description><![CDATA[Stories by Shachaf Poran on Medium]]></description>
        <link>https://medium.com/@scf1984?source=rss-33e74b6a3393------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3PGTZONfzzHKuPjT0JaJ9g.jpeg</url>
            <title>Stories by Shachaf Poran on Medium</title>
            <link>https://medium.com/@scf1984?source=rss-33e74b6a3393------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:35:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scf1984/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[Data Science Better Practices, Part 2 — Work Together]]></title>
            <link>https://medium.com/data-science/data-science-better-practices-part-2-work-together-9ec019f8b79e?source=rss-33e74b6a3393------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec019f8b79e</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shachaf Poran]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 18:57:40 GMT</pubDate>
            <atom:updated>2024-01-05T18:57:40.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science Better Practices, Part 2 — Work Together</h3><h4>You can’t just throw more data scientists at this model and expect the accuracy to magically increase.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alTdK5apwYp0oX2Ngcmqmw.jpeg" /><figcaption>Photo by Joseph Ruwa: <a href="https://www.pexels.com/photo/set-of-chess-pieces-in-daylight-4038397/">https://www.pexels.com/photo/set-of-chess-pieces-in-daylight-4038397/</a></figcaption></figure><p><a href="https://towardsdatascience.com/data-science-better-practices-part-1-test-your-queries-629ad5209f28">(Part 1 is here)</a></p><p>Not all data science projects were created equal.</p><p>The vast majority of data science projects I’ve seen and built were born as a throw-away proof-of-concept. Temporary one-off hacks to make something tangentially important work.</p><p>Some of these projects might end up becoming something else, perhaps a bit bigger or more central in helping the organization’s goal.</p><p>Only a select few get to grow and mature over long periods of time.</p><p>These special projects are usually those that solve a problem of special interest to the organization. For example, a CTR predictor for an online advertising network, or an image segmentation model for a visual effects generator, or a profanity detector for a content filtering service<em>.</em></p><p>These are also the ones that will see considerable company resources used to optimize them, and rightly so. When even a minor improvement of some accuracy metric can be directly responsible for higher revenue or be the make-or-breaker of product launches and funding rounds — the organization should spare no expense.</p><p>The resource we’re talking about in this post is <strong>Data Scientists</strong>.</p><p>If you’ve never managed a project, a team, a company or such — it might sound strange to treat people as a “resource”. However keep in mind that these are <em>experts with limited time to offer, and we use this time to accomplish tasks that benefit the organization</em>.</p><p>Now take note: <strong><em>resources have to be managed, and their use should be optimized</em></strong>.</p><p>Once a model becomes so big and central that more than a couple of Data Scientists work on improving it, it’s crucial to make sure that they can work on it without stepping on each other’s toes, blocking each other, or otherwise impeding each other’s work. Rather, team members should be able to help each other easily, and build on each other’s successes.</p><p>The common practice I witnessed in various places is that each member in the team tries their own “thing”. Depending on the peculiarities of the project, that may mean different models, optimization algorithms, deep learning architectures, engineered features, and so on.</p><p>This mode of work may seem to be perpendicular between members as each of them can work separately and no dependencies are created that may impede or block one’s progress.</p><p>However, that’s not entirely the case, as I’ve <a href="https://digma.ai/blog/coding-horrors-refactoring-and-feature-creep/">ranted</a> before.</p><p>For example, if a team member strikes gold with a particularly lucrative feature, other members might want to try and use the same feature in their models.</p><p>At some point in time a specific model might show a leap in performance, and quite quickly we’ll have branched versions of that best model, each slightly different from the next. This is because optimization processes tend to search for better optimums in the vicinity of the current optimum — not only with gradient descent but also with human invention.</p><p>This scenario will probably lead to much higher coupling and more dependencies than previously anticipated.</p><p>Even if we do make sure that not all Data Scientists converge this way, we should still try to standardize their work, perhaps enforcing a contract with downstream consumers to ease deployment as well as to save Machine Learning Engineers time.</p><h3>The premise</h3><p>We would like to have the Data Scientists work on the same problem in a way that allows independence on the one hand, but allows reuse of other’s work at the same time.</p><p>For the sake of examples we’ll assume we are members of a team working on the <a href="https://archive.ics.uci.edu/dataset/53/iris">Iris flower data set</a>. This means that the training data will be small enough to hold in a pandas dataframe in memory, though the tools we come up with might be applied to any type and size of data.</p><p>We would like to allow creative freedom, which means that each member is at full liberty to choose their modeling framework — be it scikit-learn, Keras, Python-only logic, etc.</p><p>Our main tool will be the abstraction of the process applied with OOP principles, and the normalization of work of individuals into a unified language.</p><h3>Disclaimer</h3><p>In this post, I am going to exemplify how one could abstract the Data Science process to facilitate teamwork. The main point is <em>not</em> the specific abstraction we’ll come up with. The main point is that <strong><em>data science managers and leaders should strive to facilitate data scientists’ work</em></strong>, be it by abstraction, protocols, version control, process streamlining, or any other method.</p><p><em>This blog post is in no way promoting </em><a href="https://en.wikipedia.org/wiki/Reinventing_the_wheel"><em>reinventing the wheel</em></a><em>. The choice whether to use an off-the-shelf product, open source tools, or developing an in-house solution should be made together with the data science and machine learning engineering teams that are relevant to the project.</em></p><p>Now that this is out of the way, let’s cut to the chase.</p><h3>Start from the end</h3><p>When we’re done, we’d like to have a unified framework to take our model through the entire pipeline from training to prediction. So, we start with defining the common pipeline:</p><ol><li>First we get <strong>training data</strong> as input.</li><li>We might want to extract additional <strong>features</strong> to enhance the dataset.</li><li>We create a model and <strong>train</strong> it repeatedly until we’re satisfied with its loss or metrics.</li><li>We then <strong>save </strong>the model to disk or any other persisting mechanism.</li><li>We need to later <strong>load </strong>the model back to memory.</li><li>Then we can apply <strong>prediction</strong> on new unseen data.</li></ol><p>Let’s declare a basic structure (aka interface) for a model according to the above pipeline:</p><pre>class Model:<br>    def add_features(self, x):<br>        ...<br>    def train(self, x, y, train_parameters=None):<br>        ...<br>    def save(self, model_dir_path):<br>        ...<br>    @classmethod<br>    def load(cls, model_dir_path):<br>        ...<br>    def predict(self, x):<br>        ...</pre><p>Note that this is not much more than the interfaces we’re used to from existing frameworks — however, each framework has its own little quirks, for example in naming: “fit” vs. “train” or the way they persist the models on disk. Encapsulating the pipeline within a uniform structure saves us from having to add implementation details elsewhere, for example when using the different models in a deployment environment.</p><p>Now, once we’ve defined our basic structure, let’s discuss how we’d expect to actually use it.</p><h3>System design</h3><h4>Features</h4><p>We’d like to have “features” as elements that can be easily passed around and added to different models. We should also acknowledge that there may be multiple features used for each model.</p><p>We’ll try to implement a sort of plugin infrastructure for our Feature class. We’ll have a base class for all features and then we can have the Model class materialize the different features sequentially in memory when it gets the input data.</p><h4>Encapsulated models</h4><p>We’d also like to have actual models that we encapsulate in our system to be transferrable between team members. However we would like to keep the option to change model parameters without writing a lot of new code.</p><p>We’ll abstract them in a different class and name it ModelInterface to aviod confusion with our Model class. The latter will in turn defer the relevant method invocations to the former.</p><h3>Features</h3><p>Our features can be regarded as functions with a pandas dataframe as an input.</p><p>If we give each feature a unique name and encapsulate it with the same interface as the others, we can allow the reuse of these features quite easily.</p><p>Let’s define a base class:</p><pre>class Feature(ABC):<br>    @abstractmethod<br>    def add_feature(self, data):<br>        ...</pre><p>And let’s create an implementation, for example sepal diagonal length:</p><pre>class SepalDiagonalFeature(Feature):<br>    def add_feature(self, data):<br>        data[&#39;SepalDiagonal&#39;] = (data.SepalLength ** 2 + \<br>                                 data.SepalWidth ** 2) ** 0.5</pre><p>We will use an instance of this class, and so I create a separate file where I store all features:</p><pre>sepal_diagonal = SepalDiagonalFeature()</pre><p>This specific implementation already presents a few decisions we made, whether conscious or not:</p><ul><li>The name of the output column is a literal within the function code, and is not saved elsewhere. This means that we can’t easily construct a list of known columns.</li><li>We chose to add the new column to the input dataframe within the add_feature function rather than return the column itself and then add it in an outer scope.</li><li>We do not know, other than by reading the function code, which columns this feature depends on. If we did, we could have constructed a DAG to decide on feature creation order.</li></ul><p>At this point these decisions are easily reversible, however later when we have dozens of features built this way we may have to refactor all of them to apply a change to the base class. This is to say that <strong>we should decide in advance what we expect from our system </strong>as well as be aware of the implications of each choice.</p><p>Let’s expand on our Model base class by implementing the add_features function:</p><pre>    def __init__(self, features: Sequence[Feature] = tuple()):<br>        self.features = features<br><br>    def add_features(self, x):<br>        for feature in self.features:<br>            feature.add_feature(x)</pre><p>Now anyone can take the sepal_diagonal feature and use it when creating a model instance.</p><p>If we didn’t facilitate reusing these features with our abstraction, Alice might choose to copy Bob’s logic and change it around a bit to fit with her preprocessing, applying different naming on the way, and generally <strong>inflating technical debt</strong>.</p><p>A question that may arise is “What about common operations, like addition. Do we need to implement an addition each time we want to use it?”.</p><p>The answer is no. For this we may use the instance fields through the self parameter:</p><pre>@dataclass<br>class AdditionFeature(Feature):<br>    col_a: str<br>    col_b: str<br>    output_col: str  <br>    <br>    def add_feature(self, data):<br>        data[self.output_col] = data[self.col_a] + data[self.col_b]</pre><p>So if, for example, we want to add petal length and petal width, we’ll create an instance with petal_sum = AdditionFeature(&#39;petalLength&#39;, &#39;petalWidth&#39;, &#39;petalSum&#39;).</p><p>For each operator/function you might have to implement a class, which may seem intimidating at first, but you will quickly find that the list is quite short.</p><h3>Model interface</h3><p>Here is the abstraction I use for model interfaces:</p><pre>class ModelInterface(ABC):<br>    @abstractmethod<br>    def initialize(self, model_parameters: dict):<br>        ...<br><br>    @abstractmethod<br>    def train(self, x, y, train_parameters: dict):<br>        ...<br><br>    @abstractmethod<br>    def predict(self, x):<br>        ...<br><br>    @abstractmethod<br>    def save(self, model_interface_dir_path: Path):<br>        ...<br><br>    @classmethod<br>    def load(cls, model_interface_dir_path: Path):<br>        ...</pre><p>And here’s an example implementation by using a scikit-learn model is given below:</p><pre>class SKLRFModelInterface(ModelInterface):<br>    def __init__(self):<br>        self.model = None<br>        self.binarizer = None<br><br>    def initialize(self, model_parameters: dict):<br>        forest = RandomForestClassifier(**model_parameters)<br>        self.model = MultiOutputClassifier(forest, n_jobs=2)<br><br>    def train(self, x, y, w=None):<br>        self.binarizer = LabelBinarizer()<br>        y = self.binarizer.fit_transform(y)<br>        return self.model.fit(x, y)<br><br>    def predict(self, x):<br>        return self.binarizer.inverse_transform(self.model.predict(x))<br><br>    def save(self, model_interface_dir_path: Path):<br>        ...<br><br>    def load(self, model_interface_dir_path: Path):<br>        ...</pre><p>As you can see, the code is mainly about delegating the different actions to the ready-made model. In train and predict we also translate the target to and fro between an enumerated value and a one-hot encoded vector, practically between our business need and scikit-learn’s interface.</p><p>We can now update our Model class to accommodate a ModelInterface instance. Here it is in full:</p><pre>class Model:<br>    def __init__(self, features: Sequence[Feature] = tuple(), model_interface: ModelInterface = None,<br>                 model_parameters: dict = None):<br>        model_parameters = model_parameters or {}<br><br>        self.features = features<br>        self.model_interface = model_interface<br>        self.model_parameters = model_parameters<br><br>        model_interface.initialize(model_parameters)<br><br>    def add_features(self, x):<br>        for feature in self.features:<br>            feature.add_feature(x)<br><br>    def train(self, x, y, train_parameters=None):<br>        train_parameters = train_parameters or {}<br>        self.add_features(x)<br>        self.model_interface.train(x, y, train_parameters)<br><br>    def predict(self, x):<br>        self.add_features(x)<br>        return self.model_interface.predict(x)<br><br>    def save(self, model_dir_path: Path):<br>        ...<br><br>    @classmethod<br>    def load(cls, model_dir_path: Path):<br>        ...</pre><p>Once again, I create a file to curate my models and have this line in it:</p><pre>best_model_so_far = Model([sepal_diagonal], SKLRFModelInterface(), {})</pre><p>This best_model_so_far is a reusable instance, however note that it is not trained. To have a reusable trained model instance we’ll need to persist the model.</p><h3>Save and load</h3><p>I choose to omit the specifics of save and load from this post as it is getting wordy, however feel free to check out my <a href="https://github.com/scf1984/clean-data-science/tree/main/team_cooperation">clean data science github repository</a> for a fully operational Hey example.</p><h3>Summary</h3><p>The framework proposed in this post is definitely not a one-size-fits-all solution to the problem of standardizing a Data Science team’s work on a single model, nor should it be treated as one. Each project has its own nuances and niches that should be addressed.</p><p>Rather, the framework proposed here should merely be used as a basis for further discussion, putting the subject of <strong><em>facilitating Data Scientist work</em></strong> in the spotlight.</p><p>Streamlining the work should be a goal set by Data Science team leaders and managers in general, and abstractions are just one item in the toolbox.</p><h3>FAQ</h3><p>Q: Shouldn’t you use a Protocol instead of ABC if all you need is a specific functionality from your subclasses?<br>A: I could, but this is not an advanced Python class. There’s a Hebrew saying “The pedant can’t teach”. So, there you go.</p><p>Q: What about dropping features? That’s important too!<br>A: Definitely. And you may choose where to drop them! You may use a parameterized Feature implementation to drop columns or have it done in the ModelInterface class, for example.</p><p>Q: What about measuring the models against each other?<br>A: It will be awesome to have some higher-level mechanism to track model metrics. That’s out of scope for this post.</p><p>Q: How do I keep track of trained models?<br>A: This could be a list of paths where you saved the trained models. Make sure to give them meaningful names.</p><p>Q: Shouldn’t we also abstract the dataset creation (before we pass it to the train function)<br>A: I was going to get around to it, but then I took an arrow in the knee. But yeah, it’s a swell idea to have different samples of the full dataset, or just multiple datasets that we can pass around like we do with features and model interfaces.</p><p>Q: Aren’t we making it hard on data scientists?<br>A: We should weigh the pros and cons on this matter. Though it takes some time to get used to the restrictive nature of this abstraction, it may save loads of time down the line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ec019f8b79e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-science-better-practices-part-2-work-together-9ec019f8b79e">Data Science Better Practices, Part 2 — Work Together</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[Data Science Better Practices, Part 1 — Test Your Queries]]></title>
            <link>https://medium.com/data-science/data-science-better-practices-part-1-test-your-queries-629ad5209f28?source=rss-33e74b6a3393------2</link>
            <guid isPermaLink="false">https://medium.com/p/629ad5209f28</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shachaf Poran]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 19:13:09 GMT</pubDate>
            <atom:updated>2023-09-09T11:32:15.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science Better Practices, Part 1 — Test Your Queries</h3><h4>How to make sure our queries do what we expect them to — and other future boons.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NcwZ12JyXQYZtDojGa8lA.png" /><figcaption>Generated with Midjourney</figcaption></figure><p>The field of Data Science has its roots in Mathematics and Statistics as well as Computer Science. While it has developed considerably in the past few decades, it is only in the past 10–15 years that it rose to prominence as a well-established role in the organization and as a stand-alone field in the tech industry.</p><p>Being a relatively young profession, best practices in Data Science haven’t had sufficient time to coalesce and are not well-documented. This is in contrast to the tangential field of Software Engineering, which is much more mature and is rich in know-how guides, structures, and methodologies that have proven beneficial over time.</p><p>It would be logical to expect that Data Scientists would benefit from the overlap and close collaboration with Software Engineers, especially as it relates to practice. Unfortunately, it is often not the case as many Data Scientists are either unaware of these methodologies or are <a href="https://digma.ai/blog/coding-horrors-refactoring-and-feature-creep/">unwilling to learn them</a>, claiming that they are either not relevant or do not lie within their field of responsibility.</p><p>In this blog series, I would like to share tips, tricks, and systematic approaches that may be used in the Data Scientist’s work, with the aim of increasing the correctness and stability of our code, better managing our models, and improving teamwork.</p><h3>The premise</h3><p>We start with a scenario anyone working with big data faces at some point, and some of us may even face it on a daily basis:</p><p>You are using PySpark and would like to extract some bits of information from a big table. You can never hold the enormous amounts of relevant data in memory so you’re forced to do all the transformations, aggregations, joins and whatnots within the query language.</p><p>You start writing the query and you’re happy about it since PySpark makes it easy to use a Pythonic and elegant api even when the query is too complicated to explain to other humans. Even if you decide to use the SQL interface — you’re still typing joyfully.</p><p>Then, you realize that you forgot a key column in a groupBy call and go back to fix it.</p><p>Then, you realize that one of the window functions is missing an orderBy clause.</p><p>Then, you decide that this magic number you used in the fourth line should be 1.25 rather than 1.2.</p><p>You end up going over these 20–50 lines of the query back and forth repeatedly for 20–30 minutes, changing it ever so slightly while building towards the final query structure.</p><p>Then… You run the query and it <strong>fails</strong>.</p><p>You once again traverse the rows and rows of code you just manifested, struggling to find what logical necessities you’ve missed and spot-fix them one-by-one.</p><p>Eventually, the query runs and returns some results.</p><p>But…</p><p>Who’s to promise you that these results indeed reflect what you’ve been trying to get all this time, and that it matches the process you’re currently holding in your head?</p><p>This is where testing comes to our aid.</p><h3>Testing?</h3><p>Yes. What we do is:</p><ol><li>Hand-craft a small dataset.</li><li>Calculate by hand the results we wish to get with the query.</li><li>Apply the query we wrote on that small dataset.</li><li>Match the query results with our own calculations.</li></ol><p>If we get a mismatch, we have to fix something — either our manual calculations were wrong or the query does not perform what we expect it to. On the other hand, if the results match — we have a go to continue to the next step.</p><p>I will now take you step-by-step into the structure I use when writing these tests.</p><h3>Setting up the environment</h3><p>Let’s start with creating the environment (a.k.a. a fixture) we need to work with PySpark. We may run numerous test cases each run, so we set the PySpark session up at the module level. Otherwise, we may resort to starting and stopping a session for each test, and this has a non-negligible overhead.</p><p>I use Python’s built-in <em>unittest</em>, however if you or other members of your team are using <em>pytest</em> or <em>nose</em> or any other testing framework I trust you will find a way to perform these actions.</p><p><em>unittest</em> has the two hooks <em>setUpModule</em> and <em>tearDownModule</em> that run before and after the tests, respectively. We’ll use those to start and to stop our PySpark session.</p><p># test_pyspark.py</p><pre>import pyspark<br>import unittest<br><br>spark: pyspark.sql.SparkSession | None = None<br><br><br>def setUpModule():<br>    global spark<br>    spark = get_spark_session(&#39;local&#39;)<br><br><br>def tearDownModule():<br>    global spark<br>    if spark is None:<br>        return<br>    try:<br>        spark.stop()<br>    finally:<br>        spark = None<br></pre><p>I like my session-creating function to be reusable, so here it is (I’ll fill the non-local option when it’s due):</p><p># query_pyspark.py</p><pre>import pyspark<br><br><br>def get_spark_session(scope=&#39;local&#39;):<br>    if scope == &#39;local&#39;:<br>        return (<br>            pyspark.sql.SparkSession.builder<br>            .appName(&#39;unit-tests&#39;)<br>            .master(&#39;local[4]&#39;)<br>        ).getOrCreate()<br>    else:<br>        ...  # TODO</pre><p>If the project becomes bigger I’d put this function in a PySpark-specific utils file, but at the moment let’s keep the project flat and small.</p><h3>Our very first test</h3><p>The very first thing I’m going to test now is that I actually get a session when running this test. Here’s the test:</p><p># test_pyspark.py</p><pre>class TestPysparkQueries(unittest.TestCase):<br>    def test_session_created(self):<br>        self.assertIsNotNone(spark)</pre><p>And what do you know, I run the test (PyCharm lets you do that directly from the code, you should see a green “play” button next to each test) and I get an OK message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/0*K4k3evJb5MDhV1mD" /></figure><h3>Creating <em>and </em>testing our data</h3><p>At this point we can start talking about data. What you should have at hand is a small dataset that covers different cases you might encounter, and you can still handle by hand. In terms of actual size I’d usually vote for 20–50 rows depending on the domain and complexity of the query. If there’s grouping involved, go for 5–10 different groups.</p><p>For instructional purposes I created a dataset of names and birth dates. I will assume for the sake of simplicity that all individuals with the same last name are siblings. I also introduced randomness to the order of the rows, to prevent order-sensitive queries from getting the right answer without addressing the order directly. The data looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*qihW1epXajrwAOUp" /></figure><p>Now it’s time to load the data into our PySpark session. But first, let’s create a sanity test for it. By the way, creating a test and only afterwards writing the code that makes the test pass is part of the Test-Driven Development (TDD) methodology, however I don’t preach it for Data Scientists, just the testing part.</p><p>For a sanity test we may test for column names, we may test for dataset size, we may go for both or we may come up with deeper tests. Heck, we may even write a test that matches the CSV file with the DataFrame row-by-row.</p><p>The stricter we are when writing the tests the more sure we’ll be later that the code is correct, but it will also make changes more difficult in the future, <em>e.g.</em> what if we want to add/change a line in the dataset to test for a specific edge case?</p><p>Balancing these speed and correctness factors is part of the art rather than the science in our line of work, and will come more naturally with time and practice.</p><p># test_pyspark.py</p><pre>    def test_load_data(self):<br>        df = get_family_data()<br>        self.assertEqual(25, df.count())</pre><p>Next, let’s write the function to load the data:</p><p># query_pyspark.py</p><pre>def get_family_data():<br>    return (<br>        get_spark_session(scope=&#39;local&#39;)<br>        .read.csv(os.path.join(os.path.dirname(__file__), <br>                  &#39;../assets/data_sample.csv&#39;))<br>    )</pre><p>And when I run the test… It fails? But how can it be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*hYK7LwXSseexz3jU" /></figure><p>After counting the number of rows again and making sure it’s 25 I end up adding <em>header=True</em> to the code, and the tests pass (don’t worry, I’ll spare you the fake drama in the next examples):</p><p># query_pyspark.py</p><pre>def get_family_data():<br>    return (<br>        get_spark_session(scope=&#39;local&#39;)<br>        .read.csv(os.path.join(os.path.dirname(__file__), <br>                  &#39;../assets/data_sample.csv&#39;), header=True)<br>    )</pre><h3>Testing our query(ies)</h3><p>Now it’s time for the query-specific test. Let’s say I’d like to get the eldest child from each family. I go over the dataset by eye (or use a sorted spreadsheet) to find the exact set of name I expect to get, and hard-code it into my test:</p><p># test_pyspark.py</p><pre>    def test_elder_child_query(self):<br>        df = get_elder_child(get_family_data())<br>        elders = {_.elder_child for _ in df.toLocalIterator()}<br>        self.assertEqual(elders, {&#39;Gus&#39;, &#39;Rita&#39;, &#39;Sam&#39;, &#39;Trent&#39;, &#39;Ursula&#39;})</pre><p>And the code that makes the test pass:</p><p># query_pyspark.py</p><pre>def get_elder_child(family_df: pyspark.sql.DataFrame):<br>    return (<br>        family_df<br>        .orderBy(f.col(&#39;date_born&#39;).desc())<br>        .groupby(&#39;last_name&#39;)<br>        .agg(f.first(&#39;first_name&#39;).alias(&#39;elder_child&#39;))<br>    )</pre><p>Despite sparing you the drama, I’ll share that I had to fix the query several times before getting the test to pass. For example, I grouped by <em>first_name</em>, I aggregated the values of <em>last_name</em>, and I forgot to make the sort descending.</p><p>In my jobs, <strong>testing saved me from losing face numerous times</strong>.</p><p>Are we done? Definitely not.</p><p>We should think of edge cases like what if we have twins? Are there families with no kids? What about null values if our data is not unreliable?</p><p>For each of these options we’ll go to our dataset, change it to produce such a case, then update our test and our code.</p><p>If we encounter these special cases through bugs that surface later (even if we did not come up with them by ourselves), we’ll do the same — change the dataset to reflect these cases and continue from there.</p><p>We should also write tests for the other queries, and we’ll meet different kinds of tests. In the test above we cared for the <strong>set of results</strong>, but what if we want to test a simple 1:1 transformation, <em>i.e.</em> f(row) = y. We need to factor in the non-determinism of Spark in terms of row order.</p><p>For example, let’s say we want to get the initials of the names in our dataset.</p><p>One option would be to sort the <em>DataFrame </em>and trust this order when we assert equalities with our hand-made list:</p><p># query_pyspark.py</p><pre>def get_initials_col():<br>    return (<br>        f.concat(<br>            f.substring(&#39;first_name&#39;, 0, 1),<br>            f.lit(&#39;. &#39;),<br>            f.substring(&#39;last_name&#39;, 0, 1),<br>            f.lit(&#39;.&#39;),<br>        )<br><br>    ).alias(&#39;initials&#39;)</pre><p># test_pyspark.py</p><pre>    def test_get_initials_col_1_by_1(self):<br>        df = (<br>            get_family_data()<br>            .withColumn(&#39;initials&#39;, get_initials_col())<br>            .orderBy(&#39;date_born&#39;)<br>        )<br>        expected_list = [&#39;V. A.&#39;, &#39;W. W.&#39;, &#39;X. M.&#39;, &#39;Y. T.&#39;, &#39;Z. C.&#39;, &#39;I. M.&#39;, &#39;J. T.&#39;, &#39;K. C.&#39;, &#39;L. A.&#39;, &#39;M. W.&#39;,<br>                         &#39;N. M.&#39;, &#39;O. T.&#39;, &#39;P. C.&#39;, &#39;Q. A.&#39;, &#39;A. A.&#39;, &#39;B. W.&#39;, &#39;C. M.&#39;, &#39;E. T.&#39;, &#39;F. C.&#39;, &#39;G. A.&#39;,<br>                         &#39;H. W.&#39;, &#39;R. W.&#39;, &#39;S. M.&#39;, &#39;T. T.&#39;, &#39;U. C.&#39;]<br>        for expected, actual in zip(expected_list, [_.initials for _ in df.toLocalIterator()]):<br>            self.assertEqual(expected, actual)</pre><p>Another option would be to write a <strong>native </strong>function that does the same work and test it well. Then we can apply it to the inputs after we load the results to memory, and write a test to assert equality on each row. Here’s an example:</p><p># query_pyspark.py</p><pre>def get_initials(first_name, last_name):<br>    return f&#39;{first_name[:1]}. {last_name[:1]}.&#39;</pre><p># test_pyspark.py</p><pre>    def test_get_initials(self):<br>        self.assertEqual(&#39;B. H.&#39;, get_initials(&#39;Bob&#39;, &#39;Hope&#39;))<br>        self.assertEqual(&#39;C. C.&#39;, get_initials(&#39;Charlie&#39;, &#39;Chaplin&#39;))<br>        self.assertEqual(&#39;J. L.&#39;, get_initials(&#39;Jonathan&#39;, &#39;Livingstone&#39;))<br><br>    def test_get_initials_col_support_function(self):<br>        df = (<br>            get_family_data()<br>            .withColumn(&#39;initials&#39;, get_initials_col())<br>        )<br>        for row in df.toLocalIterator():<br>            self.assertEqual(get_initials(row.first_name, row.last_name), row.initials)</pre><p>Of the two options I would definitely prefer the latter, as it’s more <strong>flexible </strong>since it does not rely on the data directly, but by the proxy of the support function — which is tested without any coupling to the dataset.</p><p>Of course, if the function is not too heavy for your query you may prefer to use it as a UDF, keeping the code complexity low.</p><h3>Wait, there’s more?</h3><p>Of course. There are plenty of different cases, such as results of joins and window functions, but I trust the examples above suffice in making the point that testing is an important tool and a valid choice of methodology when writing queries, even for Data Scientists like me.</p><p>Note, I chose to show how this might work while working with PySpark since it is a common big-data tool, however this pattern is not restricted to just PySpark nor to just big-data databases. In fact, it should work with any database. You can also use this methodology with in-memory database-ish tools, like <em>pandas</em>.</p><p>As long as you can:</p><ol><li>Connect to the data source.</li><li>Load/mock the data in the data source.</li><li>Execute the query.</li><li>Retrieve and process the query result.</li></ol><p>You’re good to go. If the tool you’re using does not let you perform one of these steps, you might want to reconsider using this tool.</p><p>And what do you know, there is a hidden benefit to testing your code. Let’s say you find that one of your functions is underperforming in terms of runtime or memory consumption, and decide to try and optimize or refactor it. You can now use your existing tests as assurance that your <strong>new code gives the same output </strong>as the previous one. Without these tests I would personally be afraid to change even a single line of code, terrified from breaking some dependency downstream.</p><h3>Summary</h3><p>Testing is a powerful and important way to assert the correctness of code and make any refactoring easy to manage.</p><p>In future posts, I will give other examples of what I find to be good practices when it comes to Data Science. We will touch subjects such as how to work together on the same model without stepping on each other’s toes, how to manage dataset versions, <a href="https://digma.ai/blog/ci-cd-cf-the-devops-toolchains-missing-link-continuous-feedback/">how to observe our code’s</a> performance in production environments, and much more.</p><p>Stay tuned.</p><h3>FAQ</h3><p>Q: Wait, what?</p><p>A: Feel free to start a conversation here or elsewhere about the notions brought in this blog series.</p><p>Q: What if in my query I need thousands of rows to test?</p><p>A: Write a parametric version of the query, e.g. <em>def get_n_smalles_children(family_df, n): … </em>and make the parameter small enough. Another option is to simulate the data programmatically, however this also presents new questions and challenges in turn.</p><p>Q: What if I keep changing the query? Does that mean I need to change the tests as well?</p><p>A: Ideally you won’t change the query over time, but I am aware of the exploratory nature of our field. So the answer is Yes. This is one of the reasons you may feel that your velocity is reduced when writing tests. However, velocity is weighted against accuracy/correctness. You may resort to writing tests later in the process, when the query structure is more solidified.</p><p>Q: How do I run the tests if I don’t use PyCharm?</p><p>A: Add the magic lines below to the end of your tests file and run it with <em>python test_pyspark.py</em>. Don’t forget to make sure the code root is included in PYTHONPATH for the imports to work (PyCharm does that automatically).</p><pre>if __name__ == &#39;__main__&#39;:<br>    unittest.main()</pre><p>Q: What if I don’t want to (or otherwise can’t) keep my data in a .csv?</p><p>A: Any way of storing and loading the data that works for you is fine, just try to keep it tidy. For very small datasets I’ve used dict-to-DataFrame (or if you’d like json-to-DataFrame), for larger datasets I used tables permanently stored on Hadoop.</p><p>Q: Aren’t the example functions you gave above, like, super simple?</p><p>A: Well, yes. That’s how I approach teaching — by giving simple examples and making them gradually more complex. Unfortunately the margins of this post are too small to contain the latter part.</p><p>Q: Do you have the code above in some repository so I can use it as a reference?</p><p>A: <a href="https://github.com/scf1984/clean-data-science/tree/main/pyspark_tests">Yes, yes I do.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629ad5209f28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-science-better-practices-part-1-test-your-queries-629ad5209f28">Data Science Better Practices, Part 1 — Test Your Queries</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>