<?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 Leon Sun on Medium]]></title>
        <description><![CDATA[Stories by Leon Sun on Medium]]></description>
        <link>https://medium.com/@layonsan?source=rss-aca259440c6b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M8988xwlxW5hrTyrTWe46A.jpeg</url>
            <title>Stories by Leon Sun on Medium</title>
            <link>https://medium.com/@layonsan?source=rss-aca259440c6b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:47:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@layonsan/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[Modularise your Notebook into Scripts]]></title>
            <link>https://medium.com/data-science/modularise-your-notebook-into-scripts-5d5ccaf3f4f3?source=rss-aca259440c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d5ccaf3f4f3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Leon Sun]]></dc:creator>
            <pubDate>Mon, 23 May 2022 13:38:25 GMT</pubDate>
            <atom:updated>2022-05-23T15:34:25.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple guide to transform your code from notebooks to executable scripts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4K4bRuPOWN1nyFeGCf4lew.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Harrison</a> on <a href="https://unsplash.com/s/photos/python-code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Hello World! In this article, I will present a simple guide on modularising your notebooks into executable scripts.</p><p>Previously <a href="https://medium.com/@geoffreyhung">Geoffrey Hung</a> shared an extremely comprehensive article on how you can transform your <a href="https://towardsdatascience.com/from-jupyter-notebook-to-sc-582978d3c0c">Jupyter Notebooks into Scripts</a>. However, during my quest to productionise models, I found that there are some gaps in modularising the notebooks from .ipynb into .py and running the entire pipeline of scripts.</p><p>If you work in the analytical space, chances are you will find yourself writing python code in notebooks at some point in time. You may or may not have experienced issues with this approach, but if you are looking for a way to execute your notebook in scripts instead, then this article is for you.</p><p>I will not be focusing on the benefits of writing code in scripts, nor attempt to compare both approaches as notebooks and scripts have their own benefits and drawbacks. If you’re wondering why you should make the switch, this article may provide more clarity.</p><p><a href="https://towardsdatascience.com/5-reasons-why-you-should-switch-from-jupyter-notebook-to-scripts-cb3535ba9c95">5 Reasons why you should Switch from Jupyter Notebook to Scripts</a></p><p>I have created a demo repository to perform a clustering analysis on a credit card dataset obtain from <a href="https://www.kaggle.com/datasets/arjunbhasin2013/ccdata">Kaggle</a>. I’ll be using this repository throughout the article to share snippets of examples.</p><p><strong>Table of Contents:</strong></p><ol><li>Project and Code Structure</li><li>Abstraction and Refactoring</li><li>Executing the Pipeline</li></ol><h4>Project and Code Structure</h4><p>Having a proper repository structure is essential. Instead of a gigantic notebook, or multiple notebooks with different models containing the entire pipeline from data extraction to modelling, we first have to compartmentalise this complexity by breaking them down into their different purposes.</p><p>The typical data analytical workflow broadly consists of 3 components: Extraction, Transformation/Preprocessing and Analysis/Modelling. This means that you can already dissect the notebook into at least 3 separate scripts — extraction.py, preprocessing.py and model.py.</p><p>In my demo repository, extraction.py is missing as the dataset was obtained from Kaggle so an extraction script is unnecessary. However, if you’re leveraging on APIs, web scraping or dumping data from a data lake, it will be useful to have an extraction script. Depending on the type of data models adopted by your team, you will likely find yourself having to write an array of queries to extract the data and perform join statements to merge them into a singular table or dataframe.</p><p>A typical structure of a project might look something like this. To view your project structure:</p><pre>$ tree</pre><pre>.<br>├── LICENSE<br>├── README.md<br>├── config.yml<br>├── data<br>│   ├── CC_GENERAL.csv<br>│   └── data_preprocessed.csv<br>├── main.py<br>├── notebooks<br>│   ├── dbscan.ipynb<br>│   ├── kmeans.ipynb<br>│   └── preprocessing.ipynb<br>├── requirements.txt<br>└── src<br>    ├── dbscan.py<br>    ├── executor.py<br>    ├── kmeans.py<br>    ├── preprocessing.py<br>    └── utility.py</pre><p>In this project repository, we break down the pipeline into its key components. Let’s look into each of their purposes.</p><ul><li>/notebooks: This folder serves as a playground where your original code is written in a flat structure for simpler display of outputs and iterating through code chunks.</li><li>/data : This folder contains the various data files your scripts will be using. Some of the popular data formats stored here include .csv, .parquet , .json etc.</li><li>/src: This folder stores all your executable scripts.</li><li>main.py: The main script to run the entire pipeline, with the code abstracted and refactored from the notebooks.</li><li>config.yml: A human readable file to store your configurable parameters used to run the scripts</li></ul><h4>Abstraction and Refactoring</h4><p>Once you have your project structure in place, the next step is to refactor and abstract your code to reduce complexity. Instead of writing code that forces the reader to understand the how, abstracting code into functions and classes (coupled with proper variable naming) can help to compartmentalise the complexity.</p><p>The article below provides an amazing summary of how you can refactor your notebook.</p><p><a href="https://www.thoughtworks.com/en-sg/insights/blog/coding-habits-data-scientists">Coding habits for data scientists</a></p><p><strong>Preprocessing</strong></p><p>After extracting your data, it&#39;s common to clean them up before using them for your analysis or models. Some of the common preprocessing includes imputing missing values, removing outliers and transforming the data etc.</p><p>Some of the preprocessing involved in the demo repository include removing outliers and imputing missing values. These specific jobs can be abstracted into functions and stored in a utility.py script, which can later be imported into preprocessing.py.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da79e6f602f333086cb07882edb44001/href">https://medium.com/media/da79e6f602f333086cb07882edb44001/href</a></iframe><p>For instance, the function for imputing missing values with median was placed in the utility.py file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5d1de467df65a497aaf4fd9e7049d74/href">https://medium.com/media/e5d1de467df65a497aaf4fd9e7049d74/href</a></iframe><p><strong>Models</strong></p><p>If you have to use different models on the same set of preprocessed data, we can also create <em>classes </em>to create a model instance. In the demo repository, I explored two types of algorithms when performing clustering, with each model separated into executable scripts. For instance, kmeans was abstracted into kmeans.py while DBSCAn was abstracted into dbscan.py.</p><p>Let’s import the necessary packages and create a class for the kmeans model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97118c08e1b3dd363221bf3d57cb2a27/href">https://medium.com/media/97118c08e1b3dd363221bf3d57cb2a27/href</a></iframe><p>If we want to create a model instance, we can simply define an object to initialise a model and store the kmeans model instance.</p><pre>kmeans = kmeans_model(df) # instantiate kmeans model</pre><pre>kmeans_models = kmeans.kmeans_model(min_clusters=1, max_clusters=10) # run multiple iterations of kmeans model</pre><p>This article by <a href="https://spierre91.medium.com/">Sadrach Pierre</a> provides an extensive elaboration on how you can utilise classes when building models.</p><p><a href="https://towardsdatascience.com/using-classes-for-machine-learning-2ed6c0713305">Using Classes for Machine Learning</a></p><h4>Executing the Pipeline</h4><p>With the various key components of the analytical pipeline now abstracted into functions and classes and transformed into modularised scripts, we can now simply run the entire pipeline. This is achieved using two scripts — main.py and executor.py.</p><p><strong>Main</strong></p><p>The main script, main.py, will run the entire pipeline when executed, taking in the necessary configurations that were loaded. In the demo repository, I leveraged on using a config file to store the parameters, and <a href="https://click.palletsprojects.com/en/8.1.x/">click</a> to interface with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0830009730fbc12e19baf6b5c6ef7470/href">https://medium.com/media/0830009730fbc12e19baf6b5c6ef7470/href</a></iframe><p><strong>Executor</strong></p><p>Once the model choice and its respective parameters have been loaded, we can parse these model inputs to execute it using the execution script, executor.py. The steps for instantiating the model, optimising it and stitching the cluster labels are then laid out within the executor function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ec347fcf5a2947638391fd277cc0c3d/href">https://medium.com/media/7ec347fcf5a2947638391fd277cc0c3d/href</a></iframe><p>To run the entire pipeline:</p><pre># execute entire pipeline with default model<br>python3 main.py</pre><pre># execute entire pipeline using DBSCAN<br>python3 main.py --model=dbscan</pre><pre># execute entire pipeline using another config file and DBSCAN<br>python3 main.py another_config.yml --model=dbscan</pre><h4>Conclusion</h4><p>Putting them all together, we now have a logical project structure with the modular scripts each carrying out its specific purpose with the underlying code abstracted and refactored. The pipeline can then be executed using a configuration file which stores the input parameters for the models.</p><p>Please leave comments 💬 if there’s more to add and I will be happy to include them in an edit!</p><p>Thanks for reading! :)</p><h4>References</h4><ul><li><a href="https://towardsdatascience.com/from-jupyter-notebook-to-sc-582978d3c0c">From Jupyter Notebook To Scripts</a></li><li><a href="https://towardsdatascience.com/from-jupyter-notebook-to-deployment-a-straightforward-example-1838c203a437">From Jupyter Notebook to Deployment — A Straightforward Example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d5ccaf3f4f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/modularise-your-notebook-into-scripts-5d5ccaf3f4f3">Modularise your Notebook into Scripts</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[GitHub Analytical Workflow for Data Analysts]]></title>
            <link>https://medium.com/data-science/github-analytical-workflow-for-data-analysts-31a28035b563?source=rss-aca259440c6b------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a28035b563</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Leon Sun]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 06:06:24 GMT</pubDate>
            <atom:updated>2022-02-15T14:24:02.793Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how you can leverage Git to increase collaboration and transparency within the data analytical team</h4><figure><img alt="GitHub figurine in front of a laptop" src="https://cdn-images-1.medium.com/max/1024/1*DbJrZ73enNNmnB_UxBDcmQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych">Roman</a> on <a href="https://unsplash.com/s/photos/github">Unsplash</a></figcaption></figure><p>Hello world! I’m writing my very first article on Medium and decided to share how I introduced GitHub to my data team to promote collaboration.</p><p>I’ll talk about why having GitHub can help a team (more than 2 data folks) collaborate more effectively, and how you can implement GitHub into your day-to-day data analytical workflows. This should help set you up for establishing some form of collaborative framework within your team.</p><p>In this article, I will focus on the following topics:</p><h3>Table of Contents:</h3><ol><li>Why GitHub</li><li>What you need before starting</li><li>Branching Strategy</li><li>What else you can add</li></ol><h4>Why GitHub</h4><p>If you’re working in the data space and have worked with at least one other teammate, chances are you have encountered collaborative issues like working on the latest code version, tracking <em>who</em> has edited <em>what</em> code or frustratingly trying to recall what purpose was this code written for which was last edited XX days ago.</p><p>These are just some of the pain points that I have heard from fellow data folks and my personal experience. Though I suspect all of these are merely scratching the tip of the iceberg.</p><p>So how exactly can GitHub tackle these?</p><blockquote>With <a href="https://docs.github.com/en/get-started/using-git/about-git">GitHub</a>, analysts can utilise its Version Control System (VCS) and Git to work on the same data project together. Any changes made to the project can be <strong>updated, tracked and reviewed</strong> by fellow analysts, and any earlier versions of the work can also be <strong>recovered</strong>.</blockquote><p>While GitHub is most popularly used with software development, we can take a leaf out of the book and incorporate some of it into data analytical workflows.</p><h4>What you need before starting</h4><p>Before introducing GitHub to your team, it’s important to first understand the basics of GitHub. Knowing how to add, commit, push files and create pull requests. I will not be going into these basics as there are plenty of resources and articles out there already that provides a comprehensive guide on mastering these basics. Here are some useful quick links:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRGOj5yH7evk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRGOj5yH7evk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRGOj5yH7evk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/59d7151e76cc8bd11bfef4fca8e53790/href">https://medium.com/media/59d7151e76cc8bd11bfef4fca8e53790/href</a></iframe><p><a href="https://towardsdatascience.com/introduction-to-github-for-data-scientists-2cf8b9b25fba">Introduction to Github for Data Scientists</a></p><p>Once you have a basic grasp on how git works, the next thing to decide is what type of branching strategy to employ for your team.</p><h4>Branching Strategy and Directories</h4><p>What exactly is a branching strategy? It’s essentially a <strong>strategy</strong> used typically by software developers to <strong>write, merge, and ship code</strong> in the context of a VCS like Git. Choosing a suitable model is important to determine when and how changes are made and committed back to the codebase.</p><p><a href="https://medium.com/@patrickporto/4-branching-workflows-for-git-30d0aaee7bf">4 branching workflows for Git</a></p><p><strong>Personal Branches<br></strong>The simplest form of branching strategy is to have the main branch serve as the main source of the codebase, and have each team member create a branch off mainwith their name as the branch name (i.e. person-A, person-B etc.). All of the personal branches will merge into main. This works when the team is small (&lt; 3), and there are few complexities in terms of the work involved (i.e. frequency of new projects is low).</p><p>As the projects scale up, this approach may be insufficient to handle the various commits and could lead to confusion.</p><p>Here’s a snippet on how it looks like.</p><p>First, create a new repository:</p><pre>## git template for creating a new repository on the command line<br>echo &quot;# playground&quot; &gt;&gt; README.md<br>git init<br>git add README.md<br>git commit -m &quot;first commit&quot;<br>git branch -M main<br>git remote add origin &lt;git url&gt;<br>git push -u origin main</pre><p>Now that you have a main branch that tracks remote branch ‘main’ from ‘origin’, you and your team can create new branches from main.</p><pre># new branches for each teammate<br>git checkout -b &quot;person-A&quot;<br>git checkout -b &quot;person-B&quot;<br>git branch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*QlUBKSp7i4zjODA0I-nUpg.png" /></figure><p>BAM. Now you have two branches for each user to work on their projects separately to be pushed to main once their part or the entirety of the project is completed.</p><p><strong>Project-based Branching<br></strong>A more efficient yet lightweight approach is to adopt a project-based branching model, which is essentially a simplified model of Git Flow. The main branch serves as the main source of codebase, and project branches are used to develop new projects to be merged into main.</p><pre>git checkout -b &#39;project-A&#39;<br>git checkout -b &#39;project-B&#39;<br>git branch</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*h99ISfFQPoe_n2E_agve5g.png" /></figure><p>If there is more than one user working on the same project, more downstream branches can be created from the main project branch. E.g. project-A/person-A, project-A/person-B.</p><p>Double BAM.</p><p><strong>How it works<br></strong>Let’s take a look at how a change can be incorporated for a team member, <em>Dave</em>, working on project titled <em>“analytics101”</em> using project-based branching as an example.</p><p>These are some of the branches that will exist:</p><ul><li>main</li><li>analytics101</li><li>analytics101/dave <em>(present only if there are more than 1 person working on the same project)</em></li><li>etc.</li></ul><p>Once Dave has completed a part or the project itself within the branch analytics101, he wishes to commit all the changes to the main branch for anyone else to reference from.</p><pre>git add -A # staging all the changes</pre><pre>git commit -m &quot;Commit for Project A&quot;</pre><pre>git push</pre><p>He can then proceed to create a Pull Request for this commit to be merged to the main branch.</p><p><strong>Directory Structure<br></strong>It is important to note that branching is not the same as directory. The directories within your git repository should be set up in a way that make sense for the team, similarly to how files are stored in different categories of folders and with various levels, either locally or on a shared enterprise cloud.</p><p>However, I do recommend having a folder each for a new project to not complicate things, with each folder having a README.md to describe the project folder.</p><h4>What else you can add</h4><p>Once you have GitHub and a branching strategy in place, you can add on more tools that can help the team to collaborate further!</p><p><strong>Environments<br></strong>A common programming tool that data analysts use is <a href="https://www.python.org/">python</a>, an object-oriented language that is efficient in data wrangling, visualisation and machine learning etc. Most analysts will interact with python via <a href="https://jupyter.org/">Jupyter Notebook</a>, either on the Conda environment itself or through IDEs such as <a href="https://code.visualstudio.com/">Visual Studio Code</a>. An issue with using python and notebooks when collaborating with numerous teammates is the risk of dependencies breaking apart as a result of different versions used.</p><p>This is where environments and git come in handy. For each of the new projects, simply initiate and activate a new environment and store all the dependencies into a file (requirements.txt). Anyone can simply access the project subdirectory, activate a new environment and install the required dependencies to run the code successfully.</p><p><strong>Inserting Credentials</strong></p><p>If you find yourself having to query data into your local machine, one issue you might face is having to manually insert your credentials into an engine. While there are numerous methods to circumvent this, an example would be to leverage on environment variables via <a href="https://pypi.org/project/python-dotenv/">python-dotenv</a> package.</p><p>Using this method together with Git becomes handy as you can simply add the .envfile to a .gitignore and the file containing all your credentials will be safely stored only on your local machine.</p><p><a href="https://medium.com/developer-secrets/storing-credentials-the-right-way-78074ae21727">Storing credentials the right way!</a></p><p>Once you have your credentials stored on a .env file, you can load the variables.</p><pre># load env variables </pre><pre>import os<br>%load_ext dotenv <br>%dotenv</pre><pre>USERNAME = os.getenv(&quot;USERNAME&quot;) <br>PASSWORD = os.getenv(&quot;PASSWORD&quot;)</pre><p>Now that you have your credentials loaded as variables, you can simply insert them to your SQL engine to extract the relevant data.</p><p>Triple BAM.</p><p>Hopefully with all of these, anyone can get started with Git and incorporating them into their data analytical workflows.</p><p>Please leave comments 💬 if there’s more to add and I will be happy to include them in an edit!</p><p>Thanks for reading! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a28035b563" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/github-analytical-workflow-for-data-analysts-31a28035b563">GitHub Analytical Workflow for Data Analysts</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>