<?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 Jacob Mazurkiewicz on Medium]]></title>
        <description><![CDATA[Stories by Jacob Mazurkiewicz on Medium]]></description>
        <link>https://medium.com/@jakemazurkiewicz6?source=rss-8ad9dfaa89f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RlfrXJkxHOE_9raNgCjV_A.png</url>
            <title>Stories by Jacob Mazurkiewicz on Medium</title>
            <link>https://medium.com/@jakemazurkiewicz6?source=rss-8ad9dfaa89f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:04:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jakemazurkiewicz6/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[When Correlation won’t cut it — Exploring Causal Models at Scale]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/when-correlation-wont-cut-it-exploring-causal-models-at-scale-9b547bc59254?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b547bc59254</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[causal-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 18:47:24 GMT</pubDate>
            <atom:updated>2026-03-02T18:47:24.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*fmnQup5ueTFt4R-Z" /></figure><p>We have all heard the phrase “correlation does not imply causation.”</p><p>It has been said so many times that many do not stop to consider the implications. Oftentimes in industry data science projects, the goal of a model <em>is</em> to find the causal effect of an intervention.</p><p>Want to find out if sending more emails to customers will equal more revenue? Will investing in a younger demographic lead to greater customer lifetime value? Will a new UI release result in an increased conversion rate on landing pages?</p><p>These questions require answers that traditional ML models cannot provide. They require an investigation into the predicted outcome of an intervention — a step beyond simple correlation and pattern matching.</p><p>Luckily, there’s a family of causal models we can leverage to answer such valuable business questions. In this article, I’ll walk through a demo of using the <strong>CausalML library</strong> to build a working causal model.</p><p><strong>Table of Contents:</strong></p><ol><li>Theory of Causal Models</li><li>Setup</li><li>Defining Features, Target, and Treatment Effects</li><li>Fitting the Model and Generating Predictions</li><li>Interpreting and Acting on Predictions</li></ol><h3><strong>Theory of Causal Models</strong></h3><p>Traditional ML asks: <em>What will happen?</em> (prediction).<br>Causal ML asks: <em>What will happen if we do X?</em> (intervention).</p><p>Causal machine learning measures the <strong>relative difference</strong> in an outcome under treatment versus control. Traditional ML predicts a single raw value. Causal ML estimates the <em>effect</em> of an action.</p><p>For example, suppose we want to know whether sending 20%, 40%, or 60% discount promotions increases average order value (AOV) for our customers. We can frame this causally. Shoppers are randomly assigned to a control group (no promotion) or to one of the discount levels. That randomized data forms the foundation of our training set.</p><p>We then train a model to answer: “<em>Given all else equal, how much higher (or lower) will a customer’s AOV be if they receive a promotion versus if they do not?”</em></p><p>We can also measure which promotion level (20%, 40%, or 60%) yields the largest increase in predicted AOV.</p><p>That estimated lift (called “uplift”) can be compared against the lost margin due to the discount to determine whether the promotion is economically justified.</p><h4>The R-Learner</h4><p>We’ll explore a causal model called the <strong>R-learner</strong>. It belongs to a family of models called <strong>meta-learners</strong> which use any machine learning algorithm (called base learners) to estimate the <em>Conditional Average Treatment Effect </em>(CATE) of each intervention. It consists of two modeling stages.</p><p><strong>Outcome learner</strong></p><p>The first model is the <em>outcome learner</em>. It predicts the target using the features, ignoring treatment assignment.</p><p>If our target is AOV and our features include age, shopping history, and location, the model predicts expected AOV purely from those features — regardless of whether a discount was given.</p><p>Formally:</p><p><em>m(X) = E[Y | X]</em></p><p>This is the expected AOV (Y) conditioned only on customer features (X).</p><p>In other words, it estimates the <strong>baseline</strong> outcome.</p><p><strong>Treatment Learner</strong></p><p>The second model is the <em>treatment learner</em>. This model estimates the treatment effect by fitting on residualized outcomes.</p><p>After the outcome learner predicts (<em>m(X)</em>), we compute residuals:</p><p><em>Yi — m(Xi)</em> (Actual AOV Yi minus predicted AOV m(Xi))</p><p>The treatment learner then estimates a function (τ(X)) that minimizes:</p><p><em>∑(Yi​−m(Xi​)−τ(Xi​)⋅Ti​)2</em> (Residual minus the treatment effect multiplied by the treatment residual)</p><p>Intuitively, this isolates the portion of the outcome that cannot be explained by features alone and attributes it to treatment exposure. By fitting on the residuals of the observed AOV and the baseline prediction, we gain an estimate of <em>how the treatment alone</em> influenced the target variable.</p><p>We train a separate treatment learner for each treatment category, or “arm”. In this case, a diffferent learner for the 20%, 40%, and 60% promotion group.</p><p>The final output of is the expected <strong>uplift</strong> in AOV for a customer receiving treatment t.</p><p><strong>Example</strong></p><p>Suppose:</p><ul><li>A customer who received a 20% discount has an AOV of $40</li><li>A similar customer in the control group (with similar feature values, like age and shopping history) has an AOV of $20</li><li>The outcome learner predicts a baseline AOV of $30 for customers with those features</li></ul><p>The treatment learner is fit on the residuals to isolate the incremental impact of the discount.</p><p>If it estimates a $15 uplift for this archetype of customer, we compare economics:</p><ul><li>Baseline + uplift = $30 + $15 = $45</li><li>After 20% discount: $45 × 0.8 = $36</li></ul><p>If $36 exceeds what we would have earned without the promotion, the discount is worth offering to customers of this type. If we assume our outcome learner to be accurate, <strong>$36 &gt; $30</strong> (baseline estimate) — which would justify sending these types of customers the 20% promotion!</p><p>The causal approach separates the treatment signal from the underlying feature signal. Instead of predicting what will happen, we estimate what happens to the target <em>because</em> we intervened.</p><h3>Set up</h3><p>Meta-learners in the CausalML library can estimate the CATE from both experimental and observational data. While randomized controlled trials are always the gold standard in isolating treatment effects, the starting point for using CausalML requires any sort of historical dataset.</p><p>Rolling along with our example, this dataset would need to include for each row:</p><ul><li>A customer identifier (customer_id)</li><li>Features about the customer (age, shopping history, etc.)</li><li>A treatment intervention they received (control, 20% discount, etc.)</li><li>The target outcome — their AOV</li></ul><p>Ideally, this dataset would be completely balanced across all intervention types, with customers having been randomly assigned a treatment throughout the length of the dataset. This would control for confounding variables. Estimating the propensity score <em>e(x)=P(T=1∣X=x)</em> (probability of being treated) is very simple under this condition.</p><p>In reality, it’s not always economically viable to give that many customers discounts to obtain the training data (giving out too many promotions without analysis hurts margins). Sometimes, analyses are planned after the data is already collected too, so the data is observational and we cannot exert control over how it was collected.</p><p>In these cases, the distributions across the treatment types might not be uniform (more customers in the control group than treatment groups). They also might not be random (e.g., we sent 20% discounts to shoppers in the loyalty program historically).</p><p>While this complicates the estimates for our causal machine learning task, the R-Learner can still handle these situations.</p><p>OK — let’s set up our R-Learner. We begin with installing the necessary packages:</p><pre>pip install causalml          # The R-Learner implementation (BaseRRegressor)<br>pip install lightgbm          # The base learner used inside the R-Learner<br>pip install scikit-learn      # Used by causalml internally + preprocessing<br>pip install mlflow            # Experiment tracking<br><br>from lightgbm import LGBMRegressor<br>from causalml.inference.meta import BaseRRegressor</pre><h3>Defining features, target, and treatment effects</h3><p>Now let’s assemble our data.</p><p>The input into the R-Learner requires data to be split into features, target values, and a separate column indicating the treatment type for each row. It is important to remember to exclude the treatment column from the feature matrix — otherwise it defeats the purpose of estimating CATE conditioned on features.</p><pre># Split into the three required inputs<br>X_train = df_train[model_features]             <br>y_train = df_train[target_var].values      <br>treatment_train = df_train[&quot;treatment&quot;]           </pre><p>The <em>treatment_train</em> column must be encoded as numeric values for the CausalML library. This can be done by simply mapping string values that denote the treatment type to integers</p><pre>treatment_mapping = {<br>    &quot;control&quot;: 0,<br>    &quot;20%&quot;: 1,<br>    &quot;40%&quot;: 2,<br>    &quot;60%&quot;: 3<br>}<br><br>treatment_train = treatment_train.map(treatment_mapping)</pre><p>We will have to specify the label for the control (0) later in model training so be sure to remember this label!</p><h3>Fitting model and generating predictions</h3><p>To construct our models, we need to define both the:</p><ol><li>Outcome learner (estimates base AOV conditioned on features only)</li><li>Effect learner (estimates relative impact of treatment on AOV)</li></ol><p>A great perk of using the CausalML library is that the R-learner framework can sit atop any base learner. This makes it super flexibile for using your favorite library!</p><p>For this example, we’ll use an LGBM Regressor model for both learners. The outcome learner in theory has a more difficult task, which makes it especially important to tune correctly.</p><pre># Outcome learner: heavily tuned — this is the &quot;hard&quot; task<br>outcome_learner = LGBMRegressor(hyperparams, verbose=-1,)<br><br># Effect learner: default params — this is the &quot;easier&quot; task (fits on residuals)<br>effect_learner = LGBMRegressor(verbose=-1)</pre><p>Then we can construct our R-learner using the <em>BaseRRegressor</em> module.</p><pre>rlearner = BaseRRegressor(<br>    outcome_learner=outcome_learner,    # Learns E[Y|X]<br>    effect_learner=effect_learner,      # Learns τ(X) = CATE<br>    control_name=0,                     # Which treatment value is control<br>)</pre><p>Then we can fit our model on the data</p><pre>rlearner.fit(<br>      X=X_train,                # (n_samples, n_features) <br>      y=y_train,                # (n_samples,) <br>      treatment=treatment_train, # (n_samples,) — pandas Series with values 0, 1, 2, 3<br>  )</pre><p>Once trained, we can predict the uplift per customer per discount rate with the <em>predict()</em> method. The predictions output will contain a separate column for each non-control intervention type (e.g. one for each discount level)</p><pre>uplift_predictions = rlearner.predict(X=X_new)</pre><h4>Validating Causal ML Models</h4><p>We may also want to validate our model’s predictions. Validating causal predictions is difficult and not as straightforward as in traditional ML. There are various proxies we can use to estimate whether our model is well-calibrated, however.</p><p>Causal machine learning validation is difficult because, for a given customer, we never know the true AOV under every discount rate (intervention type)— we only know the one treatment they did, in fact, receive and the AOV for that treatment.</p><p>One approach we can use is to validate the uplift predictions using <em>multiple estimates</em>. In this framework, one could use a variety of different CausalML models to estimate uplift and measure whether they are similar for the different customer archetypes. If the estimates are too volatile across models, we might need to reconsider our modeling approach.</p><p>Another method suggested by the CausalML authors is to generate <em>synthetic data with known causal relationships</em>. Then, by generating predictions using the trained model, we can estimate the error as a proxy for the model’s ability to capture causal signal.</p><p>There is no one best approach to validating causal models, and each context requires its own considerations for determining the level of comfort with the uncertainty inherent in these problems.</p><h3>Interpreting and acting on predictions</h3><p>Now that we have our predictions, it’s time to actually use our model to realize some business value.</p><p>For each customer, we now have an idea of the relative increase in AOV each discount rate will provide.</p><p>We can start our analysis by looking at the feature importance of the model. This will give an idea of which features per intervention type are most important (i.e., the features that most separate the different customer archetypes).</p><pre>feature_imp = rlearner.get_importance(<br>    X=X_train,<br>    tau=tau,<br>    normalize=True,<br>    method=&quot;auto&quot;,<br>    features=features,<br>)</pre><p>For example, if we see that “age” is a very important feature for the 60% discount rate, we can perhaps conclude that a younger or older portion of our customer base particularly cares about bargain hunting.</p><p>We can then target those segments of audiences with different promotions or messaging that best connects with their desires.</p><p>Performing this sort of qualitative analysis can provide some very useful insights.</p><p>On a practical level, we can determine for each customer which treatment (discount tier) leads to the highest expected uplift in AOV. Then we apply a profitability check: does the uplifted revenue, after absorbing the margin cost of the discount, still exceed the baseline revenue with no discount? If yes, that customer is a profitable target for that discount — we append them to a final audience dataframe that the marketing team can use to deploy personalized discount campaigns.</p><pre>import pandas as pd<br>import numpy as np<br><br># Maps each treatment arm to the fraction of revenue we RETAIN after discount<br># e.g., a 20% discount means we keep 80% of the sale<br>treatment_mapping = {<br>    &quot;control&quot;: 1.0,<br>    &quot;20_pct_off&quot;: 0.8,<br>    &quot;40_pct_off&quot;: 0.6,<br>    &quot;60_pct_off&quot;: 0.4,<br>}<br><br># Assume these come from the R-Learner<br># uplift_predictions: DataFrame with one column per treatment arm (excluding control)<br># Each value = predicted CHANGE in AOV vs. control (can be positive or negative)<br># Example columns: [&quot;20_pct_off&quot;, &quot;40_pct_off&quot;, &quot;60_pct_off&quot;]<br>uplift_predictions = rlearner.predict(X=customer_features)<br><br>uplift_df = pd.DataFrame(<br>    uplift_predictions,<br>    columns=[&quot;20_pct_off&quot;, &quot;40_pct_off&quot;, &quot;60_pct_off&quot;],<br>    index=customer_features.index,<br>)<br><br># baseline_aov: each customer&#39;s expected AOV with NO discount (from the outcome learner or historical data)<br># This is what they&#39;d spend anyway if we did nothing<br>uplift_df[&quot;baseline_aov&quot;] = baseline_aov  # e.g., Series of per-customer baseline values<br><br># For each customer, find the treatment with the highest predicted uplift<br>uplift_cols = [&quot;20_pct_off&quot;, &quot;40_pct_off&quot;, &quot;60_pct_off&quot;]<br># idxmax() will return index of highest treatment arm per customer<br>uplift_df[&quot;best_treatment&quot;] = uplift_df[uplift_cols].idxmax(axis=1)<br>uplift_df[&quot;best_uplift&quot;] = uplift_df[uplift_cols].max(axis=1)<br><br># Calculate the margin-adjusted revenue for the best treatment<br># Logic: (baseline_aov + uplift) is the TOTAL expected AOV under treatment<br>#        Multiply by retention rate to get the revenue we actually keep after discount<br>uplift_df[&quot;retention_rate&quot;] = uplift_df[&quot;best_treatment&quot;].map(treatment_mapping)<br>uplift_df[&quot;aov_after_discount&quot;] = (<br>    (uplift_df[&quot;baseline_aov&quot;] + uplift_df[&quot;best_uplift&quot;]) * uplift_df[&quot;retention_rate&quot;]<br>)<br><br># Profitability check:<br># Only keep customers where discounted-but-uplifted revenue &gt; undiscounted baseline revenue<br>uplift_df[&quot;is_profitable&quot;] = uplift_df[&quot;aov_after_discount&quot;] &gt; uplift_df[&quot;baseline_aov&quot;]<br><br># Final audience: customers where the uplift justifies the discount cost<br>df_audience = uplift_df[uplift_df[&quot;is_profitable&quot;]].copy()<br>df_audience = df_audience[[&quot;best_treatment&quot;, &quot;best_uplift&quot;, &quot;baseline_aov&quot;, &quot;aov_after_discount&quot;]]</pre><p>The final df_audience contains the collection of customers who, if they receive one of the promotion levels, will be expected to have an AOV exceeding that of if they did not receive a promotion.</p><p>This is the crux of causal machine learning. By isolating the effect that each promotion level had on AOV for each customer, we can construct a campaign that maximizes expected profit by sending each customer a personalized promotional level (or none if the control group had the highest uplift for them).</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J1vQo_GmTe3JcVMZ" /><figcaption>Photo by <a href="https://unsplash.com/@delanodzr?utm_source=medium&amp;utm_medium=referral">Delano Ramdas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>CausalML measures the cause-and-effect relationships in data. It asks the question, “What will be the impact on the target variable if we adjust Variable X?”</p><p>It is an extremely powerful tool for crafting effective interventions using data-driven insights in politics, healthcare, and business.</p><p>The CausalML library provides a great open-source framework for applying causal machine learning to classic data science setups.</p><p>We explored using a class of meta-learners called the R-Learner to estimate the CATE of different promotion levels per customer to optimize AOV. We also explored how to qualitatively analyze the results and make decisions that overall benefit the business.</p><p>Ultimately, causal machine learning cannot solve every problem, but is a valuable tool when measuring treatments.</p><p>I hope you learned something valuable today — if you did, please share this article with a friend!</p><p>I’m always open to new opportunities and chatting about my work!</p><p>Contact: Jacobmazurkiewicz6616@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b547bc59254" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to XGBoost on Billions of Rows of Data]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/how-to-xgboost-on-billions-of-rows-of-data-3b42b64605c2?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b42b64605c2</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rays]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 15:42:51 GMT</pubDate>
            <atom:updated>2026-02-26T15:42:51.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dIk7t-ZwQ2SSJZI0" /><figcaption>Big data presents unique challenges to building machine learning solutions. What works on 5k rows of data fails on 5B rows.</figcaption></figure><p>Sometimes, a simple Jupyter notebook just doesn’t cut it.</p><p>When you need to train a machine learning model on billions of rows, classical ML conventions go out the window.</p><p>A local machine, pandas, or a single XGBoost instance? Out of memory errors, insanely long training times, and unreliable results. These are the realities of big data.</p><p>Thankfully, there are ways to handle big data workloads effectively: welcome to the world of <strong>distributed model training.</strong></p><p>In this article, I am going to break down:</p><p>- Distributed compute</p><p>- Clusters, driver nodes, and workers</p><p>- Spark, Ray, and parallel processing</p><p>- Solving a machine learning problem with XGBoost Ray</p><p>By the end of this, you too will have the power to conquer big data, and create game-changing models!</p><h4>Distributed compute</h4><p><em>“Two heads are better than one” — John Heywood</em></p><p>A single laptop cannot solve every problem. Think about analyzing genome sequences with trillions of data points. Or running low-latency analyses on millions of stock market trades. Perhaps even building ML models on huge retail datasets.</p><p>These tasks would take far too long on a single machine. They probably would not even be possible.</p><p>The solution? Spread the computations across multiple machines. Each machine gets its own slice of the big task, breaking the main problem into smaller sub tasks.</p><p>The machines then work on their sub tasks independently. When finished, they aggregate their results back together through communication protocols. This division of responsibilies drastically increases efficiency.</p><p>There are several styles of distributed computing:</p><ol><li><strong>Server/client</strong>: the client interfaces with the user and makes requests to the server, which performs the majority of computation.</li><li><strong>Peer-to-peer</strong>: all machines in the network share equal responsibility for completing tasks.</li></ol><p>Parallel computing is a specialized form of distributed computing where all machines have access to the same shared memory, enabling tighter coupling of task completion.</p><p>Distributed computing is vital in today’s landscape where explosive data growth has led to massive problems of scale.</p><p>It allows you to scale horizontally (add more machines to the same problem), provides enhanced availability (if one machine goes down the process still proceeds), and drastically speeds up computation time. It forms the backbone of big data machine learning.</p><h4>Clusters, driver nodes, and workers</h4><p>The set of machines working together is called a “cluster”. A cluster contains the CPU and GPU hardware that actually performs the computations needed to solve big data workloads.</p><p>The individual machines within a cluster are referred to as “nodes”. So much jargon, I know.</p><p>Within each cluster there are generally two types of nodes: <strong>driver nodes and worker nodes.</strong></p><p>Worker nodes are primarily responsible for:</p><ol><li>Executing the computation on distributed sub-tasks — things like aggregating data, performing matrix multiplications, or computing point-wise estimates.</li><li>Communicating their task status back to the driver node.</li></ol><p>Driver nodes are responsible for:</p><ol><li>Delegating subtasks to the worker nodes.</li><li>Scheduling and orchestrating the overall workload.</li><li>Monitoring cluster health and ensuring worker nodes are properly allocated across subtasks.</li></ol><p>Typically, there is one driver node and multiple worker nodes — just like a manager overseeing several direct reports all working toward the same goal.</p><p>You’ll often want different hardware specs for driver vs. worker nodes. For example, your driver node doesn’t need a GPU since it isn’t performing the heavy matrix math of model training.</p><p>It’s also a good idea to plan how many worker nodes are needed to effectively utilize your hardware. Autoscaling can handle this automatically, but manual tuning is sometimes needed for complex tasks.</p><p>Spark and Ray are the distributed frameworks we’ll be using today, which spread out data and computation across nodes in a cluster.</p><h4>Spark, Ray, and parallel processing</h4><p>Two of the most popular engines for distributed computing are <strong>Spark and Ray.</strong></p><p>While their capabilities overlap, for this article we will focus on using Spark for data retrieval and Ray for machine learning training/prediction.</p><p>Spark can handle tasks such as:</p><ol><li>Retrieving data from data stores (Spark SQL)</li><li>Aggregating data efficiently</li><li>Creating DataFrame objects from pulled data</li></ol><p>Spark ships with its own SQL engine, and PySpark exposes it through a Python API — making it a go-to choice for big-data retrieval.</p><p>Under the hood, Spark distributes data (called partitions) across nodes in a cluster, unlocking all the distributed advantages we discussed above.</p><p>Ray is an open-source distributed computing framework that stands out for one key reason: it scales compute-heavy ML tasks with minimal changes to existing code. No intense refactoring needed!</p><p>Ray distributes work across nodes for tasks like training models, generating predictions, and calculating evaluation metrics on massive datasets.</p><p>Specifically, Ray can handle:</p><ol><li>Applying distributed functions to data</li><li>Training machine learning model on distributed data</li><li>Tuning a model on distributed data</li></ol><p>In the example that follows, our stack will consist of Spark, Pandas, and Ray working together to unlock a lightning-fast distributed ML pipeline!</p><h4>Solving a machine learning problem with XGBoost Ray</h4><p>Let’s make all of these ideas concrete by solving a machine learning problem with XGBoost Ray.</p><p>The <a href="https://xgboost.readthedocs.io/en/stable/tutorials/ray.html">XGBoost-Ray project</a> provides an interface to run XGBoost training and prediction on a Ray cluster — perfect for our needs.</p><p>Our sample problem: training a classifier to predict whether a customer is likely to sign up for a loyalty program based on their transaction history.</p><p>First, let’s set up the Ray cluster. We’ll assume we’re using Spark on Databricks in the cloud:</p><pre>rom ray.util.spark import setup_ray_cluster, shutdown_ray_cluster<br><br># Define the Ray cluster configuration<br>ray_cluster_config = {<br>    &quot;min_worker_nodes&quot;: 2,       # Minimum workers to keep available<br>    &quot;max_worker_nodes&quot;: 8,       # Maximum workers to scale up to<br>    &quot;num_cpus_head_node&quot;: 8,     # CPUs allocated to the driver (head) node<br>    &quot;num_cpus_worker_node&quot;: 8,   # CPUs allocated to each worker node<br>    &quot;num_gpus_worker_node&quot;: 1,   # GPUs allocated to each worker node<br>}<br><br># Initialize the Ray cluster on top of the existing Spark cluster<br>setup_ray_cluster(**ray_cluster_config)<br><br># Connect the driver to the Ray cluster<br>ray.init()</pre><p>The <em>ray.util.spark</em> module conveniently sets up a Ray cluster on top of an existing Spark cluster — ideal for Databricks. <em>setup_ray_cluster()</em> transforms Spark workers into Ray workers.</p><p>In the configuration dictionary, we define:</p><ol><li>The min/max number of worker nodes</li><li>CPUs for the head (driver) and worker nodes</li><li>GPUs for each worker node</li></ol><p><em>ray.init()</em> then connects the driver to the cluster, finalizing the setup.</p><p>With our cluster ready, let’s retrieve some sample data:</p><pre>rom pyspark.sql import SparkSession<br><br># Create a SparkSession<br># .appName() sets the name of your application<br># .getOrCreate() gets an existing session or creates a new one<br>spark = SparkSession.builder.appName(&quot;DataPull&quot;).getOrCreate()<br><br># SQL query to join user, transaction, and loyalty data<br># We retrieve raw features (num_units, unit_price) and our label (loyalty_status)<br>query = &quot;&quot;&quot;<br>SELECT<br>  user_id,<br>  date,<br>  product_id,<br>  num_units,<br>  unit_price,<br>  loyalty_status<br> FROM users<br> JOIN transactions USING(user_id)<br> JOIN loyalty USING (user_id)<br>&quot;&quot;&quot;<br><br># Execute the query and store the result as a Spark DataFrame<br>spark_df = spark.sql(query)</pre><p>We now have a Spark DataFrame with our raw features (<em>num_units, unit_price</em>) and our label (<em>loyalty_status</em>). This data represents users, their transactions, and their subscription status to an imaginary loyalty program.</p><p>We’ll train a model on these transaction indicators to predict existing customers’ loyalty status — and eventually identify new customers likely to become loyalty members. But first, we need to transform our data into a Ray-friendly format.</p><p><em>ray.data.from_spark() </em>converts a Spark DataFrame into a Ray Dataset. Since Ray <a href="https://www.scaler.com/topics/lazy-evaluation-in-spark/">evaluate lazily</a>, we call <em>materialize()</em> to force execution at call time:</p><pre># Convert the Spark DataFrame to a Ray Dataset<br># materialize() forces immediate execution instead of lazy evaluation<br>ray_df = ray.data.from_spark(spark_df, use_spark_chunk_api=False).materialize()</pre><p>Now it’s time for some distributed feature engineering. Let’s create two features from our raw data:</p><ol><li>SUM(unit_price) = total $ spend of user across their lifetime</li><li>date &gt;= (current_date — week) = did the user make a purchase within the past week?</li></ol><p>Ray’s map_groups() function lets us apply a function to each group of data independently across the cluster — drastically speeding up compute, especially for complex calculations.</p><p>It groups data by a key (like `user_id`) and runs an aggregation function across each group:</p><pre>import pandas as pd<br><br>def _sum_price(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;Aggregate total spend per user across all transactions.&quot;&quot;&quot;<br>    # Return type must match the batch_format argument (&quot;pandas&quot;)<br>    return pd.DataFrame({<br>        &quot;user_id&quot;: [df[&quot;user_id&quot;].iloc[0]],<br>        &quot;total_spend&quot;: [df[&quot;unit_price&quot;].sum()],<br>    })<br><br># Group by user_id and apply _sum_price to each group in a distributed fashion<br>agg_price = ray_df.groupby(&quot;user_id&quot;).map_groups(_sum_price, batch_format=&quot;pandas&quot;))</pre><p>Let’s create our second feature:</p><pre>def _purchase_within_week(df: pd.DataFrame) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;Flag whether a user made a purchase within the last 7 days.&quot;&quot;&quot;<br>    did_purchase_within_week = 0<br><br>    # Find the most recent purchase date for this user<br>    recent_purchase = pd.to_datetime(df[&quot;date&quot;]).max()<br><br>    # Define the cutoff as 7 days ago from now<br>    one_week_ago = pd.Timestamp.now() - pd.Timedelta(days=7)<br><br>    # If the most recent purchase is within the last week, flag it<br>    if recent_purchase &gt;= one_week_ago:<br>        did_purchase_within_week = 1<br><br>    return pd.DataFrame({<br>        &quot;user_id&quot;: [df[&quot;user_id&quot;].iloc[0]],<br>        &quot;did_purchase_within_week&quot;: [did_purchase_within_week],<br>    })<br><br># Group by user_id and apply _purchase_within_week distributedly<br>agg_week_purchase = ray_df.groupby(&quot;user_id&quot;).map_groups(<br>    _purchase_within_week, batch_format=&quot;pandas&quot;<br>)</pre><p>Now, we can join our two feature DataFrames on matching user_ids:</p><pre># Inner join the two feature datasets on user_id<br>feature_df = agg_price.join(agg_week_purchase, on=&#39;user_id&#39;, how=&#39;inner&#39;)</pre><p>To grab our label column, we can use the Ray <em>select_columns()</em> function. We can also use the inbuilt <em>train_test_split() </em>to prepare our training and test sets:</p><pre># Select only the label and key columns from the original dataset<br>label_df = ray_df.select_columns([&quot;loyalty_status&quot;, &quot;user_id&quot;])<br><br># Join features with the label to create the full training dataset<br>full_df = feature_df.join(label_df, on=&#39;user_id&#39;, how=&#39;inner&#39;)<br><br># Split into 80% train and 20% test sets <br>train_ds, test_ds = full_df.train_test_split(<br>    test_size=0.2, shuffle=True, seed=42<br>)</pre><p>Finally, to feed these Ray Datasets into XGBoost, we convert them into DMatrices — just like regular XGBoost. The only difference is we use <em>RayDMatrix</em>, which is essentially identical to the standard DMatrix:</p><pre>from xgboost_ray import RayDMatrix, RayParams<br><br># Convert Ray Datasets into RayDMatrix objects for XGBoost training<br># RayDMatrix accepts the data, the name of the label column, and feature names<br>train_dmat = RayDMatrix(<br>    train_ds,<br>    label=&quot;loyalty_status&quot;,<br>    feature_names=[&quot;did_purchase_within_week&quot;, &quot;total_spend&quot;],<br>)<br>test_dmat = RayDMatrix(<br>    test_ds,<br>    label=&quot;loyalty_status&quot;,<br>    feature_names=[&quot;did_purchase_within_week&quot;, &quot;total_spend&quot;],<br>)</pre><p>With our RayDMatrices created, we can perform distributed training!</p><p>On massive DataFrames, training in a distributed manner drastically speeds up the process.</p><p>We supply the configuration (hyperparameters, objective function, etc.) to the XGBoost Ray <em>train</em> API and get back a trained booster object:</p><pre>from xgboost_ray import train<br><br># Train the XGBoost model in a distributed fashion across the Ray cluster<br># xgb_params contains hyperparameters like max_depth, learning_rate, objective, etc.<br>booster = train(<br>    xgb_params,<br>    train_dmat,<br>    evals_result=evals_result,<br>    evals=[(train_dmat, &quot;train&quot;), (test_dmat, &quot;test&quot;)],<br>    ray_params=ray_params,  # Passes the Ray cluster configuration<br>)</pre><p>With training complete, we’ll want to evaluate our model offline.</p><p>Ray’s <em>map_batches()</em> function lets us generate distributed predictions and compute evaluation metrics. We can build a custom class that takes our trained booster and returns classifications based on a probability threshold. By defining the prediction calculation in a <em>__call__()</em> method, we can directly call the class in <em>map_batches() “</em>fn” argument:</p><pre>import numpy as np<br>import pandas as pd<br>from xgboost import Booster, DMatrix<br><br><br>class XGBClassifierPredictor:<br>    &quot;&quot;&quot;Custom predictor that converts XGBoost probabilities into<br>    binary classifications based on a configurable threshold.&quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        booster: Booster,<br>        score_col: str,<br>        label_col: str,<br>        threshold: float = 0.5,<br>    ):<br>        self.booster = booster<br>        self.score_col = score_col<br>        self.label_col = label_col<br>        self.threshold = threshold<br><br>    def __call__(self, batch: pd.DataFrame) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Generate predictions for a single batch of data.&quot;&quot;&quot;<br>        # Separate features from the label column<br>        features = batch.drop(columns=[self.label_col])<br>        dmat = DMatrix(features)<br><br>        # Get predicted probabilities and apply the threshold<br>        probas = self.booster.predict(dmat)<br>        batch[self.score_col] = (probas &gt;= self.threshold).astype(int)<br>        return batch<br><br><br>class RecallCounts:<br>    &quot;&quot;&quot;Per-batch true positive and false negative counter,<br>    used for computing recall across distributed batches.&quot;&quot;&quot;<br><br>    def __init__(self, pred_col: str, label_col: str):<br>        self.pred_col = pred_col<br>        self.label_col = label_col<br><br>    def __call__(self, batch: pd.DataFrame) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Count TP and FN for a single batch.&quot;&quot;&quot;<br>        y_true = batch[self.label_col]<br>        y_pred = batch[self.pred_col]<br>        tp = int(((y_pred == 1) &amp; (y_true == 1)).sum())<br>        fn = int(((y_pred == 0) &amp; (y_true == 1)).sum())<br>        return pd.DataFrame({&quot;tp&quot;: [tp], &quot;fn&quot;: [fn]})<br><br><br># --- Distributed prediction ---<br># map_batches() applies the predictor class to each batch independently<br>predictions = test_ds.map_batches(<br>    fn=XGBClassifierPredictor,<br>    fn_constructor_kwargs={<br>        &quot;booster&quot;: booster,<br>        &quot;score_col&quot;: &quot;prediction&quot;,<br>        &quot;label_col&quot;: &quot;label&quot;,<br>    },<br>    batch_format=&quot;pandas&quot;,<br>    concurrency=concurrency,<br>)<br><br># --- Distributed TP/FN counting ---<br># Each batch independently counts its true positives and false negatives<br>counts_ds = predictions.map_batches(<br>    fn=RecallCounts,<br>    fn_constructor_kwargs={&quot;pred_col&quot;: &quot;prediction&quot;, &quot;label_col&quot;: &quot;label&quot;},<br>    batch_format=&quot;pandas&quot;,<br>    concurrency=concurrency,<br>).materialize()<br><br># --- Aggregate on the driver node to compute global recall ---<br># Collect all per-batch counts into a single Pandas DataFrame<br>counts_df = counts_ds.to_pandas()<br>total_tp = counts_df[&quot;tp&quot;].sum()<br>total_fn = counts_df[&quot;fn&quot;].sum()<br><br># Recall = TP / (TP + FN)<br>recall = total_tp / (total_tp + total_fn) if (total_tp + total_fn) &gt; 0 else 0.0</pre><p>Notice that we cannot directly calculate recall across batches — each batch has a different denominator. Instead, we track true positives and false negatives per batch, then aggregate on the driver node to compute global recall.</p><p>And with that, we have a fully distributed framework to solve the business problem of identifying customers likely to sign up for our loyalty program!</p><h4>Conclusion</h4><p>Distributed training with Ray lets you unlock the power of concurrency with the ease of existing XGBoost and Python syntax.</p><p>It’s a go-to solution for big data, enabling model training and aggregation at massive scale.</p><p>Pandas, Spark, and Ray together form a convenient, approachable stack that can handle even the most intensive machine learning tasks. If you are looking to solve big problems with machine learning or aim to optimize an existing pipeline, these frameworks can be a life saver!</p><p>If you learned something valuable from this article, please share it with a friend!</p><p>You are now armed with the knowledge to capture the power of distributed machine learning.</p><p>I’m always open to opportunities and to chat about my work, contact me!</p><p>Email: Jacobmazurkiewicz6616@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b42b64605c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimating Machine Learning Features with Sparse Data]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/estimating-machine-learning-features-with-sparse-data-91b5ed769405?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/91b5ed769405</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sparse-data]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[ecommerce]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 12:15:16 GMT</pubDate>
            <atom:updated>2026-02-23T12:15:16.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*mwUkjEPeB1jgnHCW.png" /><figcaption><strong>Figure 1: Sparse data.</strong> A pain in every machine learning engineer’s a**!</figcaption></figure><p>One problem that routinely plagues data scientists in marketplace industries is <strong>sparse data.</strong></p><p>This is the kind of data where events are rare, and data points signaling nothing outnumber the few gems of information nestled in between.</p><p>As a data scientist in an e-commerce-led industry, I work with a large amount of purchase data. This data is extremely sparse, especially when taken at a clickstream granularity. After all, how many times have you browsed a website or store but never actually bought anything? (Window shopping is fun, but not for data scientists!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OEhGgF45gLDWUhjI" /><figcaption>Window shopping — fun for the shopper but a challenge for the data scientist. Photo by <a href="https://unsplash.com/@georgebakos?utm_source=medium&amp;utm_medium=referral">George Bakos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When trying to derive useful features for machine learning models from sparse data, it can be difficult to extract the true signal (events) from the noise (visits with no events).</p><p>For example, say we’re trying to model the total revenue of a product relative to its impressions to use as an ML feature. This essentially describes both how well a product converts (likelihood of purchase) as well as how much money we can hope to generate from it (revenue gained from a purchase).</p><p>To calculate this average revenue per impression fora product, we could simply take:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwec34LYBGNTBI-T6zUBBA.png" /><figcaption><strong>Figure 2: Modeling revenue rate of a product. </strong>By taking the sum of sales for a product divided by the number of impressions it received, we get an idea of both the value of a product as well as its conversion rate.</figcaption></figure><p>So what’s the issue with this approach?</p><p>If a product has only two impressions because it is a new item and receives one order for $60 — maybe by chance — it has a calculated revenue rate of $30. This is very high! And probably not realistic to the true revenue rate of the product.</p><p>Several biases exist with sparse data. A few chance events can drastically swing calculations, and products that are not in reality profitable or popular can seem so due to a few lucky purchases.</p><p>To obtain a more unbiased estimate of the revenue rate of a product, we can use a Bayesian-style model known as the <strong>hurdle log-normal model.</strong></p><h4>Step 1: Hurdle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T3Ejb-9xZ-4J6cFh" /><figcaption>Photo by <a href="https://unsplash.com/@libraryofcongress?utm_source=medium&amp;utm_medium=referral">Library of Congress</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The first part of the model is called the “hurdle”. This part estimates the probability that a product sells at all — or the conversion rate of the product.</p><p>In a data space where many products receive impressions but few are actually bought, this part of the model is especially important.</p><p>The question we’re trying to answer is: “What is the probability someone buys this product (converts), given they see it? (impression)”</p><p>To model this probability, we can use a <strong>beta-bernoulli model.</strong></p><p>This model estimates the probability of success (user buys the product) and the probability of failure (user sees the product but does not purchase it). By understanding these probabilities, we can construct a conversion rate for the product.</p><p>In Bayesian fashion, before looking at our observed (real) successes and failures for our products, we want to set <strong>a prior </strong>on our initial belief about this success probability. Essentially, <em>p(success)∼Beta(α,β)</em>.</p><p>This prior is parameterized by alpha and beta, where:</p><ol><li><em>Alpha α</em> = number of believed successful events</li><li><em>Beta β</em> = number of believed failing events</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_kKoBpEAjTlNv1KmFMEvLw.png" /><figcaption><strong>Figure 3: Mean of the beta prior. </strong>This value can be adjusted by either altering the ratio of alpha to beta or by altering the total magnitude of the estimates.</figcaption></figure><p>This prior can be guided by historic purchase data, industry averages, or simple intuition. In the context of our example, beta would be much larger than alpha because our initial belief is that most products receive impressions but do not convert.</p><p>After setting the prior, we then look at our observed data to obtain our final estimate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FEVPgHQwJuiuho2KJusfw.png" /><figcaption><strong>Figure 4: Posterior estimate of Beta distribution. </strong>This measures our believed conversion rate of a product given our priors and the new observed data.</figcaption></figure><p>Here, <em>s</em> is the number of true successes (conversions) we observe in our data, and n is the total number of true impressions. From it, we receive our final estimate of the conversion rate, also referred to as the <em>posterior predictive estimate.</em></p><p>Notice that if alpha and beta are large in magnitude, they dominate the fraction and shrink the value closer to the prior. If alpha and beta are small in magnitude, the observed data quickly takes priority.</p><p>This is why choosing sensible values for the parameters of the prior is important, because it drastically affects what the final estimated value is.</p><p>Using this model, for each product, we can obtain an estimate of the probability someone will buy it given they see it!</p><h4>Step 2: Log-Normal Revenue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/0*ujwd5U7bE8jmCIvK.jpg" /><figcaption>A distribution for revenue gained from sold products has a long right tail.</figcaption></figure><p>The next part of the model answers the question, “Given the product converts, how much revenue can we expect to gain it?”</p><p>This part models a log-transformed continuous distribution of possible positive values (revenue) gained from a product.</p><p>To model this, we can use a log-normal distribution: <em>logX∼N(μm,σ²m)</em>.</p><p>This distribution is parameterized by:</p><ol><li><em>mu μm</em>: The mean revenue we expect to gain from a product</li><li><em>sigma-squared σ²m</em>: The variance of revenue gained from a product</li></ol><p>We use a log version of the classic normal distribution because revenues gained from products in a marketplace are heavily skewed (some high ticket items generate exponentially more revenue than most products).</p><p>For example, in a store that sells medicine, the majoriy of purchases will be for cheap items (like cough syrup or Tylenol), but a few will be for very expensive items (like Insulin or rare-medications) that skew the distribution to the right.</p><p>We also want to set priors on these two parameters so that they are not influenced by sparse data.</p><p>The prior for μ can be a normal distribution with parameters <em>(μ0, σ²0)</em> — with the 0s denoting they are the parameters for the prior not the actual distribution. Confusing, I know. Welcome to the world of Bayesian modeling 🙄.</p><p>We can take <em>σ²</em> as a hyperparameter too, since it is unknown.</p><p>So we end up with 3 hyperparameters: σ²0, σ², and μ0.</p><h4>Step 3: Combining Both</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BuWRd2tB9XcCKBHV.jpg" /><figcaption>Bayesian estimates combine both the observed data and the prior beliefs about that data.</figcaption></figure><p>Now that we have defined the constituent parts of the hurdle log-normal model, it is time to combine them to construct a single posterior predictive estimate of our machine learning feature (e.g., revenue rate of a product).</p><p>We can achieve this estimate with the formula below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0E1szNu_GaGeWt94dttfFg.png" /><figcaption><strong>Figure 5: Hurdle Log-Normal posterior predictive estimate.</strong></figcaption></figure><p>The first part of the equation is the “hurdle” part, where:</p><ol><li><em>M</em> is the total number of converting impressions for a product</li><li>N is the total number of impressions for a product</li></ol><p>Notice that without the beta-bernoulli prior hyperparameters a<em>lpha and beta</em>, the first part simply measures the fraction <strong>M/N</strong> (The two M’s in the denominator cancel out) —which is the direct probability of the conversion rate calculated solely from the observed data.</p><p>The second part of the equation is the log-normal part, where we model the log of the mean of the posterior predictive estimate of the value (revenue) plus the variance of the observed data and the variance of the prior.</p><p>Remember that <em>μm</em> is actually the estimate from a log-normal distribution that has its own priors. To calculate <em>μm</em>, we take:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ss5ZrDD76PihNJeevguS2A.png" /><figcaption><strong>Figure 6: Posterior Predictive estimate of the log-normal distribution’s mean</strong></figcaption></figure><p>Notice that essentially we are taking our prior mean (initial belief of the value denoted by <em>μ0</em>) plus our observed mean (y, where y is the log(mean) of the observed value calculated from our data). But we multiply each by a ratio of our variance hyperparameters (<em>σ²</em> and <em>σ²0</em>) along with our total number of converting impressions for the product.</p><p>This allows us to tweak the estimate of <em>μm</em> to best fit our problem formulation. For example, increasing the ratio of <em>σ²</em> to <em>σ²0</em> places more emphasis on the prior mean estimate <em>μ0</em>. Look at the first multiplication statement, if <em>σ²</em> is bigger than <em>σ²0</em>, then the first fraction is going to be bigger, which leads to a larger <em>μ0</em> contribution to the μm.</p><p>The reverse is true, too. A smaller <em>σ²</em> to <em>σ²0</em> ratio leads to the observed data y contributing more.</p><p>But our log-normal distribution is also characterized by variance.</p><p>To obtain <em>σ²m </em>— the posterior predictive estimate of the log-normal variance, we use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1E9NMq3dV1kBnkxyeHMv7Q.png" /><figcaption><strong>Figure 7: Posterior predictive estimate of the the log-normal distribution’s variance</strong></figcaption></figure><p>Notice that it is simply a product of our hyperparameters guided by our sample size of converting impressions.</p><p>It is important to use exploratory data analysis and diagnostics to choose variance hyperparameters. These may be selected via prior predictive checks, estimated through marginal likelihood optimization (empirical Bayes), or modeled hierarchically with hyperpriors.</p><p>The second part of Figure 4 represents the exponentiated posterior estimate of the log-scale mean, adjusted by the variance, which produces the expected revenue of a product on the original scale under the log-normal model.</p><p>The final equation output gives us a less biased estimate of the average revenue per impression (revenue rate) we expect to see for any given product!</p><h4>Using the Estimates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mnXHNuQmn7gqi8Qz" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We now have a mathematically sound approach to estimating machine learning features in the presence of sparse data!</p><p>We can use the hurdle log normal estimates as inputs to other ML models or algorithms to increase the value of a business product.</p><p>These values can be used to:</p><ol><li>Decide on timely promotions and sales for products to maximize revenue</li><li>Optimize relevance ranking algorithms for search to increase click-through-rate</li><li>Estimate product demand and ensure optimal inventory allocation</li></ol><p>Dealing with sparse data in marketplaces is a challenge in building robust machine learning solutions. Using Bayesian techniques can help protect against the biases of using naive calculations!</p><p>I hope this article was helpful in understanding one way to approach modeling features when sparse data can throw a wrench in the process!</p><p>If you enjoyed this article — please share it with your friends! Also feel free to reach out to me — I’m always open to chat and new opportunities.</p><p>Email: Jacobmazurkiewicz6616@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91b5ed769405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineer to Data Scientist: The Ultimate Pivot Playbook]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/data-engineer-to-data-scientist-the-ultimate-pivot-playbook-b775ae73719f?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b775ae73719f</guid>
            <category><![CDATA[data-science-interview]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 21:55:07 GMT</pubDate>
            <atom:updated>2025-06-16T21:55:07.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JvYAJyJd4SnnPsGM" /><figcaption>Photo by <a href="https://unsplash.com/@mkvandergriff?utm_source=medium&amp;utm_medium=referral">Maranda Vandergriff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Tell me if this sounds familiar.</p><p>You earn your degree in a field you love, ready to join a company and show the world what you can do. You find yourself in a data engineering role, neat huh?</p><p>Arriving with enthusiasm, you are promptly beaten with a spoon by long hours, constantly putting out fires instead of building exciting things, and a nauseating sense of unfulfillment.</p><p>Tired of giving in to circumstances, you decide it is time for a change.</p><p>You want out of data engineering.</p><p>A quick stroll through alternative options yields a consistent winner for the perfect career change: <em>data science</em>.</p><p>It’s hot. It also pays well. It even contains multiple overlapping skills with data engineering that should, in theory, make the switch simple.</p><p>There’s only one problem: every open data science position already has <em>thousands</em> of applicants.</p><p>Yes, there was a time when data science was “the sexiest job of the 21st century”. Now it simply feels like the most bloated.</p><p>How do you land a data science interview amongst all the noise?</p><p>My journey as a college student who couldn’t land an internship (Walmart cashiering during your summers is <em>not</em> the move), to a data engineering intern at Travelers Insurance, to an entry-level data scientist at Dick’s Sporting Goods proved challenging. Along the way, I uncovered a few fundamental actions that you can leverage, however, to land data science interviews as a former data engineer, even in a crowded talent pool.</p><p>In this ultimate guide for landing data science interviews that will help you make your next career jump, we’ll cover the following:</p><ol><li><a href="#5ab0">Learning the fundamentals of data science.</a></li><li><a href="#e3af">Building a unique project portfolio.</a></li><li><a href="#3794">My number 1 way to get noticed as a data science applicant.</a></li><li><a href="#37b7">Roadblocks and obstacles for data engineers.</a></li><li><a href="#7442">Resume Do’s and Don’ts.</a></li><li><a href="#f93e">How to properly leverage targeted applying for maximal success.</a></li></ol><p>Ready to bypass the competition and leave data engineering behind? I thought so, let’s get into it.</p><h4>Learning the fundamentals of data science</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jdfQgOBnuZ_E6pEC.png" /><figcaption>One of the simplest data science models: linear regression.</figcaption></figure><p>You may assume you possess the skills necessary to thrive in a data science role.</p><p>This may be the case, depending on what kind of data engineering work you perform.</p><p>If you do not have a grasp of the fundamentals of the data science workflow, however, you may find it difficult to achieve your goal of beginning a career in the field.</p><p>Therefore, learning the basics of data science is very important at the beginning of your journey. I found that, apart from my university studies, there are three great ways to quickly pick up the gist of data science projects:</p><ol><li>Kaggle competitions/notebooks.</li><li>Udemy courses.</li><li>YouTube tutorials.</li></ol><p>Let’s walk through each one.</p><p>First, <a href="https://www.kaggle.com/">Kaggle</a> is an online community and hub of data scientists, data-centric projects, and competitions hosted by organizations.</p><p>It is also a great repository of beginner datasets that help aspiring practitioners learn the ins and outs of data science.</p><p>If you navigate to the “Competitions” section of the homepage and filter for the “Getting Started” section, you’ll be introduced to a variety of beginner datasets, including the famous <a href="https://www.kaggle.com/c/titanic/data"><em>Titanic</em></a> classification dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvZ8r7xFBxuPEGimbLUOpw.png" /><figcaption>Beginner datasets in Kaggle</figcaption></figure><p>These datasets provide a great starting point for performing basic regression or classification tasks and will help you understand the process of converting a business problem into code that solves it.</p><p>If you navigate to the “Code” section, you can see other’s code notebooks and their approach to exploring the same data and building models. These community notebooks are great for studying new techniques in the field and understanding how others approach data. As a complete beginner, it can be very useful to simply read through other’s code, as they often include extensive comments that explain their actions and thought processes.</p><p>Kaggle has its own built-in notebook IDE that allows coding within the website, making it perfect for beginners or those who want to quickly hop into the process.</p><p>If you prefer more lecture-oriented learning, <a href="https://www.udemy.com/">Udemy</a> courses can also be a great way to learn data science.</p><p>I learned several key concepts in data science by taking the <a href="https://www.udemy.com/course/machinelearning/">Machine Learning A-Z</a> course as a sophomore at university. The course provided me with both a theoretical understanding of data science but also an applied code skillset when it came to implementing machine learning knowledge, particularly in <a href="https://scikit-learn.org/stable/index.html">scikit-learn</a>.</p><p>Udemy courses can also be great for picking up data science jargon, which can prove useful when discussing your work with potential employers.</p><p>There are dozens upon dozens of effective data science courses on Udemy (and other online learning platforms), and if you’re willing to invest money into your learning journey, it can be a fantastic resource.</p><p>Additionally, the self-guided learning style of these platforms is perfect for busy professionals, as it allows you to work through the material at your own pace.</p><p>Selecting and completing a quality Udemy course can help you build the fundamental skillset needed to make the switch to data science.</p><p>Finally, the simplest of all learning methods is <a href="https://www.youtube.com/">YouTube</a> tutorials.</p><p>The hype around data science may be bad for those looking to break into the field, but it is great for fostering quality online learning resources.</p><p>YouTube can be a great way to learn various data science techniques like feature engineering or model validation. Simply type the concept you want to learn into the search bar, like “Exploratory Data Analysis”, and follow it with “data science tutorial”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-ZAV7mjnoQmCSAQAnhFkg.png" /><figcaption>A quick search for “Exploratory data analysis data science tutorial” on YouTube.</figcaption></figure><p>Chances are you’ll find several quality online guides that explain the concepts thoroughly. And best of all, it is free!</p><p>Be sure to select reputable sources if choosing to learn from YouTube. The lower bar of entry compared to sites like Udemy makes it easier to put out low-quality content.</p><p>Like properly laying down the foundation of a house is imperative for its structural integrity when building upwards, grasping the basics of the field is essential to excelling and landing an interview later on.</p><p>After you’ve mastered the data science basics, it&#39;s time to apply your skills.</p><h4>Building a unique project portfolio</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydv0aI-e3JYuWrZQHroamA.png" /><figcaption>A screenshot of a part of my online project portfolio.</figcaption></figure><p>The curse of the modern job market lies in entry-level roles that counterintuitively require “years” of prior experience.</p><p>How does a professional looking to break into data science do so when they have no prior experience?</p><p>While the best way to sidestep this obstacle is with internships (which may or may not be an option depending on where you are in your life/career), the second-best way is to build a project portfolio of 3–5 end-to-end data science projects that showcase your ability to perform in the field.</p><p>But what actually goes into creating a portfolio project?</p><p>I’ve found that Generative AI can be a great resource for brainstorming project ideas and getting started. Here’s a sample prompt you can copy and paste into your favorite AI assistant:</p><p><em>Hi there. I’m a data engineer looking to transition to data science and need to build a project portfolio that showcases my newfound skills in data science. Can you brainstorm 3–5 unique, end-to-end projects that will impress my employers? Be sure to include links and resources. The projects should include a problem statement, a dataset, and target specific skills relevant to data science. Thanks!</em></p><p>A project portfolio demonstrates that you are capable of “doing data science” and gives you projects to talk about in interviews in the absence of previous experience.</p><p>Your portfolio should be targeted to the specific type of data science work you aim to do.</p><p>For example, as a data scientist at Dick’s Sporting Goods, I’d most likely want to build a project around sales forecasting or recommendation engines on a retail-based dataset. This is the most relevant to the type of work I’d be performing at this organization.</p><p>If you are looking for a more AI-engineering focused role, for example, try experimenting with fine-tuning your own LLM on a custom dataset.</p><p>The key is to make your project portfolio niched down to your desired role. Generic projects will not win the attention of potential employers.</p><p>This leads me to my next piece of advice:<em> make your projects as unique as you can.</em></p><p>Almost everybody has done the <a href="https://data-flair.training/blogs/iris-flower-classification/">Iris classification</a>, and recreating what thousands have already done will not separate you from the crowd. Try doing something different!</p><p>For example, I <a href="https://github.com/jakemaz66/RecoveringSleepingBandit">recreated Duolingo’s multi-armed bandit notification algorithm</a> using data provided on their website as one of my projects. This is something not a lot of other people have tried to do!</p><p>One piece of advice when building projects is that <em>you will get stuck</em>. It is inevitable. But the time spent being stuck and working on getting past the roadblock <em>is part of the work. </em>I used to get frustrated when stalled, thinking that I was wasting my time and not making progress. I eventually realized that the time spent overcoming the problem <em>is</em> <em>the</em> <em>learning</em> that cements your skills and helps you grow.</p><p>After building your project, I recommend doing three additional things to showcase your work:</p><ol><li>Add all relevant code to an organized GitHub repository with a comprehensive README file.</li><li>Write a blog-style article detailing what your project is and how you built it. Then, post this article to your LinkedIn, Medium, or Substack.</li><li>Create a portfolio website (I use <a href="https://www.bluehost.com/">Bluehost</a>) and include images, written articles, and code snippets that break down your project in a compelling manner.</li></ol><p>These extra steps aren’t required, but the goal here is to attract attention from employers, and maintaining an online presence is necessary to land modern-day data science gigs.</p><p>I will not lie to you, building a project portfolio that is unique and tailored to your desired role is not easy. That is why many skip this step.</p><p>But building a portfolio is exactly what will make you an interesting candidate to employers!</p><p>There are also many great online examples of data science portfolios. Simply try googling “Data science portfolio inspiration” and you’ll be greeted by dozens of quality ideas.</p><p>After you’ve created a quality data science portfolio, it’s time to move into my secret weapon for attracting attention to data science opportunities.</p><h4>My number 1 way to get noticed as a data science applicant</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2BU-kVY0gDNSLydd" /><figcaption>Photo by <a href="https://unsplash.com/@alexbemore?utm_source=medium&amp;utm_medium=referral">Alexander Shatov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>People ask me all the time how I landed a data science job so early in my career.</p><p>I always tell them to practice this one thing, but they rarely listen.</p><p>They usually make excuses, dismiss it as redundant, or believe it&#39;s too “cringy” to be worth their time.</p><p>Yet I stand by this action more than any other piece of advice in this guide.</p><p>Ready for my secret sauce? Here it is:</p><p><strong>Write articles on LinkedIn.</strong></p><p>Yes, it is that simple. Simple, but not easy.</p><p>Writing articles on LinkedIn accomplishes a number of objectives that can aid you in transitioning to data science from data engineering:</p><ol><li>Positions you as an expert in the field and in your topic of interest.</li><li>Engages your current network and signals that you are an active member of the data science community.</li><li>Organically reaches data science recruiters and startups looking to hire fresh talent.</li><li>Hones your own data science skills and cements your understanding of complex data science topics.</li><li>Practices vital soft skills like translating data science projects into written words, communication, and summarizing work.</li></ol><p>I cannot stress enough how great of an opportunity it is to write content on LinkedIn. At the time of this writing, it is still, in my opinion, an underutilized medium, so the time to strike is now before it becomes too oversaturated. You will be amazed by the number of organic impressions you can garner with just one thoughtful, well-written article.</p><p>Whenever I tell people to write on LinkedIn, they always ask, “Well, what do I write about?”</p><p>This is a valid question, and here are the three main topics I prefer:</p><ol><li>Do a deep dive into one of your portfolio projects. Explain the data, your thought process in solving the problem, and your code.</li><li>Write a how-to guide on something you recently learned. For example, if you recently studied the <a href="https://en.wikipedia.org/wiki/Q-learning">Q-learning algorithm</a>, write a guide on how to implement it in Python with the OpenAI Gym. If you recently picked up ways to use AI to streamline your workflow, write a piece detailing your method. Illustrate your problem-solving skills.</li><li>Share your perspective on things happening in the data science community. If you are strongly opinionated about data privacy or generative AI, for example, you could write about your ideas on the topic and how you would apply the principles to your work.</li></ol><p>By writing on LinkedIn, I have received amazing opportunities for work and have fostered several quality connections, including becoming a push notifications engineer for the AI startup <a href="https://jungleai.com/">Jungle</a>.</p><p>When you consistently put out thoughtful, well-written content into the world, people begin to take notice.</p><p>Recruiters may come across your articles and contact you. Your peers may begin to ask you for help on their projects. At the very least, you’ll gain a more thorough understanding of your own work and data science concepts.</p><p>If you’re wondering how often you should write, I’d at minimum aim for a article every 2 weeks. This will allow you to engage a wide audience without oversaturating them.</p><p>Practice a daily habit of working on your articles, even if it is just for 20 minutes every morning, and you will witness the magic.</p><p>Now that you have everything set up for success in your transition to data science, it is time to anticipate and avoid some common roadblocks.</p><h4>Roadblocks and obstacles for data engineers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2CiKGfX4l0JC1s1_" /><figcaption>Photo by <a href="https://unsplash.com/@thatsmrbio?utm_source=medium&amp;utm_medium=referral">Matthew Hamilton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Like every difficult journey for something worthwhile, you will encounter obstacles in your quest to land a data science role.</p><p>When I was a data engineering intern at Traveler’s Insurance, I attempted to obtain entry into their data science program: <em>the DSLDP</em>. While I had an amazing experience as a data engineering intern, I felt that data science work aligned more closely with what I enjoyed.</p><p>There was one thing blocking my way, however: a baseline requirement of a master’s degree. I have found lack of formal education indicators to be the most common obstacle awaiting data engineers attempting to break into data science.</p><p>I tried to circumvent this requirement.</p><p>I personally contacted the program manager. I demonstrated my effective performance as a data engineer and my university education in data science. I begged for an interview to prove my skills.</p><p>In the end, it did not work out.</p><p>Many data scientists today transitioned to the field after studying a different topic and possess master’s or doctoral degrees. Even if the degrees are not 100% relevant to data science, they are formal indicators of job ability, and many employers still value them greatly when searching for job candidates.</p><p>If you find yourself up against this obstacle, I find three primary avenues to proceed:</p><ol><li>Go back to school and obtain the necessary education level for your desired role (time-consuming and expensive!)</li><li>Prove your worth through alternative means (only effective some of the time.)</li><li>Find a different data science role.</li></ol><p>The first is self-explanatory. If you want to be a cutting-edge data science researcher at a frontier lab like Google DeepMind, you are probably going to need a PhD in a quantitative field. There’s little chance of navigating around this requirement.</p><p>I cannot speak to the best options when embarking on this path (as I only have a bachelor&#39;s degree myself!) but it can definitely be a worthwhile route if you are clear on where you want to go.</p><p>The second option is my preferred one. If you can vouch for yourself and be persistent, you may be able to get past this obstacle.</p><p>I personally emailed the DSLDP program manager multiple times and demonstrated my competency for the role. While it did not work out in the end due to company policies, I was still able to secure an entry-level interview through my resilience.</p><p>Sometimes, it pays to be difficult for meaningful endeavors. Don’t stop at the first no, believe in yourself and continue to ask for interviews.</p><p>If all else fails, however, there are data science positions that do not have strict degree requirements.</p><p>For example, my role at Dick’s Sporting Goods did not have a requirement for a master’s degree, only a bachelor’s (although a master’s was preferred).</p><p>Many data engineers do not have advanced degrees, so it may be wise to simply filter your desired role to those that also do not require them. It can save you a lot of time and effort if going back to school is not a viable option.</p><p>I sincerely hope this barrier will change in the coming years, and data science will become more of a meritocracy. At the time of this writing, however, education barriers are a factor to consider when seeking to land a data science job.</p><p>After you have selected the role you wish to obtain and have overcome any obstacles, it is time to perfect your resume.</p><h4>Resume Do’s and Don’ts</h4><p>There are many exceptional resources out there that will detail every little thing to perfect with your resume.</p><p>And, truth be told, they are an essential part of the application process.</p><p>But, for the sake of brevity (and not bloating this article to gargantuan size), I will constrain this section to some major do’s and don’ts for applying to data science roles.</p><p>This is not a comprehensive list, but a collection of rules that I followed with success along my journey.</p><p>Do’s:</p><ol><li>Tailor your previous experience to fit the job description of the role.</li><li>Tailor your experience to fit the values and work of the desired company.</li><li>Highlight the more “data science-centric” parts of your previous roles (i.e. mathematics, Python coding, model validation).</li><li>Highlight a key project from your project portfolio.</li><li>Keep it concise, simple, and readable.</li><li>Keep it to one page.</li><li>Paint yourself in the best light possible, highlighting quantifiable impacts on business goals.</li></ol><p>Don’ts:</p><ol><li>List out every project you’ve ever completed.</li><li>Be too detailed about pure data engineering skills (ETL, Cloud Pipelines, etc.) Remember, you’re angling for a specific skillset in data science, even if there is overlap.</li><li>Try to fit too much information into the one-page resume.</li><li>Have a general resume for every role/company.</li><li>Fail to include your contact information, GitHub page, and/or project portfolio in your resume header.</li></ol><p>My resume made it past several screenings by following these guidelines. To illustrate, here’s the resume I used to apply to Dick’s Sporting Goods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*AxU7n1e_vE-z2WGSNFdMUw.png" /></figure><p>It’s not perfect, and there are things I would change if I reapplied today, but this should give you a decent understanding of good concepts to follow in crafting your resume.</p><p>Now that your resume is prepped, it’s time for the final stage to land the job of your dreams.</p><h4>How to properly leverage targeted applying for maximal success</h4><p>Many people flaunt their prowess in sending out the maximum number of applications possible.</p><p>I’ve heard friends brag about applying to 120 jobs in one week. These same friends then also complain that only one got back to them and it was a Multi-Level Marketing scam.</p><p>The quantity vs. quality approach to job hunting is flawed. In the age of automated resume screening software, lessened demand for technical roles, and AI, an alternative process must be utilized.</p><p>Therefore, I suggest you gather the 3 roles you really want and <em>limit your focus to only those three roles.</em></p><p>We think we are more “productive” by not putting all our eggs in one basket and applying to every single posting that has the word “data” in it, but this often leads to subpar results. To land a job, you only need to hit one homerun (one success), and it pays to deeply invest yourself into properly applying for a limited subsect of roles.</p><p>So, limit your scope to 3 roles you desire and feel you are qualified for. They can be at one company, or at different ones, it is completely up to you.</p><p>Once you have your three roles, there are two things you can do to properly leverage targeted applying:</p><ol><li>Use your network to bypass the resume screening. Scan your LinkedIn connections for people who also work at your desired company and ask them to refer you for the position. Send out emails to people you know, or cold email the hiring manager if you can locate them. If you can establish a relationship with the right person, you may be able to land an interview right out of the gate.</li><li>Apply through the company portal but also send a thoughtful letter (or email) to the company afterwards. In this message, specifically highlight your experience that would prove useful to the role, your passion and desire for data science, and your unique qualifications. Few people go the “extra step” in the application process because they are too busy sending hundreds of applications into the void. Now that you have limited your scope, you can afford to spend more time on these few key jobs.</li></ol><p>Targeted applying is more of a philosophy than a collection of concrete tactics.</p><p>What it recommends is that spending an inordinate amount of time on the three jobs you desire most will yield outsized returns compared to the mass-application method.</p><p>I found that <a href="https://hunter.io/">hunter.io</a> can be a great resource for cold emailing recruiters and companies in the absence of an established network.</p><p>But, for the most part, leveraging your network here will do the most good. And, hopefully, you’ve expanded this network through writing articles on LinkedIn and engaging with your readers.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*16uHTtanz8qWiGXT" /><figcaption>Photo by <a href="https://unsplash.com/@theblowup?utm_source=medium&amp;utm_medium=referral">the blowup</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you feel ready to make the jump from data engineering into data science, I truly hope you find value in this guide. These are the exact steps I followed to achieve the career of my dreams, so I hope you will commit to the principles and find success too!</p><p>The journey to a difficult goal is never linear, and at times the process will feel frustrating. During these moments, I find it helpful to remember that it is supposed to be hard. And when times get hard, most people quit, so it is the few that keep going that eventually find success.</p><p>If you have any questions about the above steps or any feedback on my process, please leave a comment! I’d love to start a discussion.</p><p>Until next time, best of luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b775ae73719f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Brutal Truths I Learned as a Freelance Push Notifications Engineer]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/5-brutal-truths-i-learned-as-a-freelance-push-notifications-engineer-cae5f6530c1c?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cae5f6530c1c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[freelancing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[freelance-engineer]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Thu, 15 May 2025 19:34:04 GMT</pubDate>
            <atom:updated>2025-05-15T19:34:04.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WtgVah8WdUS1n5L-" /><figcaption>Photo by <a href="https://unsplash.com/@christnerfurt?utm_source=medium&amp;utm_medium=referral">Christian Erfurt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Freelancing is significantly harder than your typical 9–5 job.</p><p>Why is this? You might ask.</p><ul><li>Ambiguous work hours and scheduling conflicts.</li><li>Communication and contractual overhead.</li><li>Performance based evaluations.</li></ul><p>The list goes on and on, but you get the idea.</p><p>Of course, these obstacles exist in every type of work, but working as a freelance push notifications engineer for the AI-assisted education startup <a href="https://jungleai.com/">Jungle</a> truly highlighted these unique challenges for me.</p><p>I worked on 3 primary projects over 4 months for Jungle, some proving successful, others not so much. Startups demand speed and rapid progress, as does most freelance work, which presents particular technical challenges, like detecting and avoiding bugs.</p><p>At one point in my journey, the stress of pushing a bug into production caused me to cancel everything else I had scheduled that day to solely focus on fixing the issue.</p><p>I eventually left Jungle on mutual terms, as it proved too difficult to balance with my full course-load at Duquesne University with my responsibilities. Now 3 months removed from this role, I took time to analyze what it takes to be successful as a freelance engineer.</p><p>Continue reading this guide if you’re interested in:</p><ul><li>Becoming a freelance engineer and landing high paying gigs.</li><li>Learning the unique challenges of startups, project selection, and execution.</li><li>Growing as a technical professional.</li></ul><p>I will help you avoid the pitfalls I experienced myself through these 5 truths and hopefully will propel you to great success!</p><h4>Brutal Truth #1: Results Talk, Work Walks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oLz8FNFzQPpCUbEB" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a data engineering intern at <a href="https://www.travelers.com/">Travelers</a>, I learned that “success” as a standard employee is measured in several ways.</p><p>My performance evaluations were based off many factors:</p><ul><li>Technical proficiency.</li><li>Ability to communicate and collaborate cross-functionally.</li><li>Contribution to the workplace culture.</li><li>Managing and completing projects with deadlines.</li></ul><p>I entered my role at Jungle with a mindset that my performance would be measured in similar ways.</p><p>I was wrong.</p><p>As a freelance engineer at a startup, my boss cared about one primary thing:</p><p><strong>Did my work directly contribute to increased metrics? (AKA business results)</strong></p><p>He didn’t particularly care if I networked with the team, or if I fine-tuned my work to be more transparent. He simply wanted evidence that the money and energy he was investing in me had a positive ROI for the venture.</p><p>This realization came during our 3rd meeting (we set up a weekly connect to touch base) where, after I delved into ideas I had for more notifications and various tools I could use to drive engagement, he paused me.</p><p>He asked me what the confidence intervals were on our new notification templates click-through-rates (CTR) and the relative increase compared to the previous notification copy.</p><p>I paused, quickly panicking and coming to the realization I did not have such numbers. My heart fluttered in my chest.</p><p>I told him that I was unprepared with that information, and he advised me to collect these metrics for future meetings.</p><p>This experience taught me an important lesson:</p><p><strong>Startup leaders who hire freelancers are often looking for lift, for measurable progress in the task you were hired for. That’s it.</strong></p><p>Another way of saying this: numbers (results) talk, work walks.</p><p>Of course, my boss cared about many things and was very professional and friendly in guiding me to my realizations.</p><p>Opposed to the regular 9–5 performance review, however, you may be measured by your results and not the total cumulative effort of your work.</p><h4>Brutal Truth #2: Speed Matters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Bl5dYWKKbZ4Vahk" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Returning to my time at Travelers, projects had well-defined timelines (and often included cushion in case things went wrong).</p><p>In fact, I spent the entire summer working on one primary project to create a program to automatically generate documentation for a vital data pipeline.</p><p>As I began working with Jungle, I realized that startups have wildly different timelines for their projects compared to a company like Travelers.</p><p>At established companies, the majority (but not all) of work is focused on improving existing processes. Few projects require creating systems from the ground up.</p><p>This is the opposite within a startup, where engineers architect almost every project from scratch.</p><p>Throw in limited resources, market pressures to grow, and an ambitious leadership team and you get the perfect mix for a particular project philosophy:</p><p><strong>Speed matters. Urgency matters. Ship projects as soon as they are viable.</strong></p><p>Now, this doesn’t mean shoddy work is acceptable, but fundamentally speed is more important in a startup environment.</p><p>During a project to implement desktop notifications for Jungle, my boss asked me if I could produce a minimum viable demo (with accompanying code) within a week.</p><p>As a full-time student and part-time freelancer (who also maintains a social life), I was startled for a moment. The timeline was ambitious, to say the least.</p><p>But gradually, I realized these hard-driving timelines are necessary to get a company off the ground, and that getting something working quickly is usually more important than getting it perfect in this environment.</p><p>In other words, getting 80% of the way there in a week is worth much more than getting to 95% in a month.</p><h4>Brutal Truth #3: You Will Break Things</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pARATHOsNzC7pd6u" /><figcaption>Photo by <a href="https://unsplash.com/@katelyn_g?utm_source=medium&amp;utm_medium=referral">Katelyn Greer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This one hurt me. A lot.</p><p>The speed and pressure of working as a freelance engineer at a startup forges quick learning and experience with impactful projects.</p><p>But this pressure can also create cracks, cracks that turn into failures.</p><p>When implementing a certain notifications initiative, I was sure I had tested all my code thoroughly. I mulled over the testing environment for an entire day, scanning for edge cases and potential bugs.</p><p>I reviewed the pull-request with the eyes of a hawk.</p><p>But here’s another brutal truth that snuck up on me:</p><p><strong>Success in local testing does not directly translate to success in production, or at scale.</strong></p><p>After merging my code, there was a hidden flaw that caused harm to our users.</p><p>This was a bug that did not reveal itself in local testing but was only uncovered when deployed to thousands of real users.</p><p>When I received indication of this mistake, a pit formed in my stomach. I had never failed so spectacularly in something so important.</p><p>I felt embarrassed, ashamed of my oversight. I considered quitting right there, afraid to speak to my boss at our next meeting.</p><p>After some time, I came to realize that breaking things is an inevitable obstacle when performing this type of challenging engineering work.</p><p>Indeed, my boss was incredibly gracious, and while he didn’t sugarcoat the error, he conceded that I was not the first to break something, and that I would probably not be the last.</p><p>Failing sucks.</p><p>But failing in a way that directly harms your team, a company and mission you care about, feels 10x worse.</p><p>If you are entering this world of freelance engineering, it helps to develop some thick skin. It’s important to take failure on the chin, accept fault when necessary, but to not linger on mistakes you may have made.</p><p>Because the going will get tough, but how we respond in the face of our failures is what defines us, not our initial errors.</p><h4>Brutal Truth #4: Soft Skills Trump Hard Skills</h4><p>As engineers we often dismiss the so-called “soft skills” of the workplace.</p><p>Those <em>touchy-feely</em> skills like communication, leadership, and time management seem secondary to the challenging problems of our primary tasks.</p><p>As a freelancer, however, these skills are not secondary. In fact, I would say they are equally, if not more important than “hard” skills.</p><p>At travelers, it was relatively easy to silo myself within my project. I could spend an entire day hammering away at my computer, with my manager right around the corner if I needed assistance.</p><p>We would sometimes go for coffee breaks, and I could spend 30 minutes explaining any problems I had.</p><p>At Jungle, concise, proper communication became a necessity.</p><p>I no longer had the luxuries of time, constant access to others in my team, or work on siloed projects.</p><p>I had a concrete mission to fulfill, and needed to identify the right people, tools, and processes to carry it out.</p><p>Certain soft skills proved vital in working through my projects at Jungle:</p><ul><li>Communicating ideas in a compelling manner to my boss to obtain buy-in.</li><li>Articulating trade-offs in varying tools and processes for solving the same problem.</li><li>Defining the business objective in technical terms and translating back and forth.</li><li>Speaking to others about code documentation.</li><li>Time-blocking my calendar to ensure I worked efficiently.</li><li>Synthesizing information into a single sentence.</li></ul><p>These skills apply to every type of work, but I found them more vital in my role at Jungle compared to my previous experiences at Travelers and as a university student.</p><p>Time is always in short supply within a startup and learning to communicate clearly and briefly proved to be an immense boon.</p><p>As a freelance engineer, don’t skimp on honing your soft skills. They are what keeps the trains running on the technical work.</p><h4>Brutal Truth #5: Take Full Responsibility For Your Work</h4><p>Finally, we arrive at the last brutal truth: accepting 100% responsibility for everything you do.</p><p>At a large company, a mistake can easily be blamed on something else.</p><p>So-and-so might have left the codebase in a poor state. The project might have been poorly defined by management. Your co-workers were distracting during the week up to the deadline.</p><p>As a freelance engineer, failure is not so easily pushed onto others.</p><p>When signing a contract, you accept full responsibility for the outcome of your projects.</p><p>As the new external expert within the company, solving obstacles is part of the job description, and seeing the project to fruition is the expectation.</p><p>Whether you push a bug to production, have to manage a poorly documented codebase, or find a way to contact an inaccessible employee, the responsibility of pushing through these obstacles is completelty yours.</p><p>It is a lot of pressure. Errors cannot be easily wiggled out of. Freelance engineering shines a spotlight directly on you and your work.</p><p>It can make the work very stressful.</p><p>But the opposite is true here as well. When you succeed, when you make progress and drive impact, your work shines.</p><p>Accepting responsibility for your projects makes you a mature worker, one that can learn from mistakes and revel in success.</p><p>Many difficult experiences defined my time at Jungle. I made errors, learned new coding languages, and talked to people with vastly different life experiences.</p><p>Accepting responsibility for my failures and shortcomings was difficult.</p><p>But this also allowed me to work past some of these problems and find solutions. It enabled me to truly internalize the lessons learned from my work.</p><p>And the wins I achieved felt <em>amazing</em>. When people talk about finding purpose and passion in their work, this is secret: accepting responsibility for every part of the project you take on.</p><p>This commitment frees you to grow and contribute fully as an engineer, even if it brings hardship.</p><h4>So What?</h4><p>Freelance engineering at a startup is not for the faint of heart. It brings several distinct challenges — but also the opportunity for immense growth and learning.</p><p>My time at Jungle as a push notifications engineer was not easy. I made many mistakes. I celebrated some wins. But it fundamentally taught me important lessons in succeeding in the space.</p><p>To recap, to be a great freelance engineer:</p><ol><li>Emphasize the quantifiable impact of your work.</li><li>Work with urgency, iterate on a minimum viable build.</li><li>Expect to break things, do not give up when faced with failures.</li><li>Focus on soft skills like communicating clearly and briefly.</li><li>Accept full responsibility for completing your projects.</li></ol><p>I hope you use these lessons I learned to go out and do great things!</p><p><em>Top 3 Articles to Read Next</em></p><p>[1] <a href="https://medium.com/@jakemazurkiewicz6/the-cheat-code-for-landing-a-data-science-job-right-out-of-college-eb7cb040cfd2">The Cheat Code for Landing a Data Science Job Right Out of College | Medium</a></p><p>[2] <a href="https://medium.com/@jakemazurkiewicz6/i-completed-100-sql-interview-questions-heres-what-i-learned-8ee15d6e5e4b">I Completed 100 SQL Interview Questions. Here’s what I Learned. | Medium</a></p><p>[3] <a href="https://medium.com/@jakemazurkiewicz6/7-things-ive-learned-as-a-data-engineering-intern-cf915d553948">7 Things I’ve Learned as a Data Engineering Intern | Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cae5f6530c1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the Heck are Gaussian Processes?]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/what-the-heck-are-gaussian-processes-9ebdc3d73ba2?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ebdc3d73ba2</guid>
            <category><![CDATA[statistical-modeling]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gaussian-process]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 16:57:02 GMT</pubDate>
            <atom:updated>2025-03-18T16:57:02.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*muRPMpL-PkX5SYuc.png" /></figure><p>In my search to expand my repertoire of machine learning and statistical models, I discovered a model known as a <strong>Gaussian Process</strong>.</p><p>Now, I had never heard of such a technique, and was curious about this new discovery, and how I could use it to better model certain types of data.</p><p>I quickly fell down the statistical rabbit-hole, finding myself in niche corners of the internet that described this complex, but very useful, way to non-parametrically model small-to-medium datasets.</p><p>In this article I’m going to give you the low-down on Gaussian Processes, so you don’t have to do the same. Remember, knowledge is power, and you’re about to add a very powerful tool to your toolkit!</p><h4>Gaussian Process: The Basics</h4><p>Gaussian Processes are <em>distributions over functions</em>. This means that they model a variety of possible functions that produce outputs, with a distribution of how probable a datapoint comes from a certain function.</p><p>This flexibility helps them model complex, non-linear relationships in which multiple functions can describe different parts of the dataset.</p><p>Gaussian processes can be used for both classification and regression tasks and are parametrized by:</p><ol><li>A mean function <em>m(x)</em></li><li>A covariance function <em>k(x, x’)</em></li></ol><p>These functions stand in place for the mean and variance of what would be a normal Gaussian distribution.</p><h4>Loading in the Data</h4><p>To demonstrate the use of a Gaussian process in practice, I’m walking through a complete analysis of the Student Performance dataset, <a href="https://archive.ics.uci.edu/dataset/320/student+performance">which can be found here</a> at the UCI Machine Learning Repository.</p><p>This dataset contains various features of Portuguese students (age, alcohol consumption, time spent studying) and a target variable of their final grade, labeled ‘G3’.</p><p>I load in my data using the <em>Pandas</em> library, using the semi-colon delimiter option as the data is not comma-separated (even though it arrives in a csv file format)</p><pre>df = pd.read_csv(r&quot;student-por.csv&quot;, delimiter=&#39;;&#39;)</pre><p>I also check that everything has loaded in properly by calling the <em>df.head()</em> function, which yields me this output:</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPJ2xRTFvQ8oTVnAQpfmVQ.png" /></figure><p>You can see several independent variables, along with the target ‘G3’ at the very right-most column.</p><p>Everything looks good! Let’s move on to exploring this data.</p><h4>Exploratory Data Analysis</h4><p>The first thing I want to do is check what kind of variables we are dealing with (continuous, nominal, ordinal, etc.) I do this by calling the info() function, which gives the dtype of each variable along with additional information:</p><pre># Checking dataset dtypes<br>df.info()</pre><p>In this dataset, we are dealing with two primary variable types:</p><ol><li>Int64 (integers)</li><li>Objects (usually string values representing levels of a categorical variable)</li></ol><p>I then proceed to observe the distribution of our target variable.</p><pre># Examining the target variable&#39;s distribution<br>sns.histplot(data=df, x=df[&#39;G3&#39;])<br>plt.title(&quot;G3 Distribution&quot;)<br>plt.axvline(df[&#39;G3&#39;].mean(), color=&#39;red&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*TLvGh4r7rC_EBv4wHPvA0w.png" /></figure><p>It seems like it’s not quite normally distributed. We can perform a log transformation to make it more normal-like:</p><pre># Performing a log-transformation to see if we can get G3 more normal<br>log_y = np.log1p(df[&#39;G3&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*qBmifoAmGENsr7MqEXOPag.png" /></figure><p>It looks like G3 is a little more normally distributed now (although not entirely so), which will make it easier to model with a Gaussian Process.</p><p>When we apply a log transformation to a target variable, we must ‘undo’ the transformation at prediction time to model the actual G3, since our model will be trained to predict the log(G3).</p><p>In practice, this means that the actual G3 prediction will be:</p><p>E(y) = exp(predicted(log(y)) + (σ² / 2))</p><p>We cannot simply exponentiate our outputs but must adjust for bias by adding (σ²) where σ² is the variance of the errors in the log-space.</p><p>Next, we check for multi-collinearity of the independent variables. Having multiple predictors that are highly correlated with each other can lead to instability within the model:</p><pre># Checking for correlation between features<br>continuous_columns = [col for col in X_train.columns if X_train[col].dtype == &#39;int64&#39;]<br>X_train[continuous_columns].corr()py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwqzQ81lSmB-fYyCSi9_TQ.png" /></figure><p>We see that two sets of variables are highly correlated:</p><p>1. <em>Medu</em> and <em>Fedu</em></p><p>2. <em>Walc</em> and<em> Dalc</em></p><p>I chose to drop Fedu and Walc because they had less predictive power over G3.</p><p>For sake of brevity, I will conclude the EDA section here, but note some other procedures I performed:</p><ol><li>Checked for outliers using the 1.5 * IQR +- (Q1, Q3) method</li><li>Checked for missing values using the <em>df.isna().sum()</em> function (there were none)</li><li>Performed a univariate analysis (examined the distribution of each independent variable)</li></ol><h4>Feature Engineering</h4><p>In machine learning modeling, we often worry less about model saturation compared to formal statistical processes. The emphasis instead is often placed on the prediction, not the steps the model took to produce the output.</p><p>While feature selection and maintaining parsimony (building the simplest model possible) are still important, it is often useful to “engineer” new features from existing ones in the hope to create new informative predictors.</p><p>Several lines of reasoning can lead to new features, like:</p><ol><li>Extracting additional information from one feature (e.g. obtaining a “Month” and “Day” feature from a complete timestamp column)</li><li>Creating new features from interactions with existing features (e.g. multiplying a ‘sex’ and ‘age’ feature when the output is dependent upon both the sex and age at varying levels)</li></ol><p>Here, there are several interesting variables to consider.</p><p>For example, I examined the interaction between <em>Dalc</em> and <em>Health</em>, which is the alcohol consumption of a student during the workday (Dalc) and the overall health of the student (Health).</p><p>I hypothesize that students score lower on G3 when Dalc is high, because they are drunk and not studying, but also that this negative effect is way worse when their health is also low, as physical activity and overall wellbeing is important to fight off hangovers.</p><p>OK, this reasoning may not be very scientific, but these kinds of thoughts can lead to powerful new features. This is why feature engineering is commonly referred to as an “art” rather than a “science”. Here, I create a new feature called ‘health_Dalc’</p><pre># Health/Workday Alcohol Comsumption interaction<br>df[&#39;health_Dalc&#39;] = df[&#39;health&#39;] * df[&#39;Dalc&#39;]<br>print(df[[&#39;health_Dalc&#39;]].corrwith(df[&#39;G3&#39;]))<br><br>#health_Dalc   -0.201246</pre><p>The feature has a pretty low correlation with our target variable (-0.201) but could be a useful addition in large datasets.</p><p>This stage is also where I preprocess the data, taking the following steps:</p><ol><li>Scaling the continuous features (standardization)</li><li>One-hot-encoding the categorical features</li><li>Dropping our redundant columns</li></ol><p>I do this with a preprocessing pipeline:</p><pre># Creating a Preprocessing Pipeline<br>if &#39;Fedu&#39; in continuous_columns and &#39;Walc&#39; in continuous_columns:<br>  continuous_columns.remove(&#39;Fedu&#39;)<br>  continuous_columns.remove(&#39;Walc&#39;)<br><br>categorical_columns = [col for col in df.columns if col not in continuous_columns]<br>columns_to_drop = [&#39;Fedu&#39;, &#39;Walc&#39;]<br><br>preprocessor = ColumnTransformer(<br>    transformers = [<br>        (&#39;num&#39;, Pipeline(steps=[<br>            (&#39;scaler&#39;, StandardScaler())<br>        ]), continuous_columns),<br>        <br>        (&#39;cat&#39;, Pipeline(steps=[<br>            (&#39;encoding&#39;, OneHotEncoder())<br>        ]), categorical_columns),<br>        <br>        (&#39;drop&#39;, &#39;drop&#39;, columns_to_drop)<br>    ],<br>    # Keep columns not explicitly processed<br>    remainder=&#39;passthrough&#39;<br>)<br><br>pipeline = Pipeline(<br>    steps=[(&#39;preprocessor&#39;, preprocessor)]<br>)<br><br># Transforming the data frame<br>df = pipeline.fit_transform(df)</pre><pre># Reconstructing the dataframe<br>continuous_names = continuous_columns<br><br>categorical_names = pipeline.named_steps[&#39;preprocessor&#39;].named_transformers_[&#39;cat&#39;].named_steps[&#39;encoding&#39;].get_feature_names_out(categorical_columns)<br><br>all_names = np.concatenate([continuous_names, categorical_names])<br><br># Using the &quot;from sparse matrix&quot; function in Pandas because the preprocessor outputs a sparse matrix<br>df = pd.DataFrame(pd.DataFrame.sparse.from_spmatrix(df), columns=all_names)</pre><p>Now our data is ready to be modeled with a Gaussian Process!</p><h4>Implementing Gaussian Process</h4><p>One of the most important decisions to make when modeling with Gaussian Processes is the <strong>choice of kernel</strong>.</p><p>Kernels quantify the covariance (<em>k(x, x’) function</em>) of datapoints by determining their similarity. They act as a ‘prior’, encoding beliefs about the smoothness, linearity, and behavior of the data before the modeling process.</p><p>Some common kernel types are:</p><ol><li>Radial Basis Function (RBF) — Flexible and widely used for smooth, predictable functions.</li><li>Matérn Kernel — Hyperparameters allow one to adjust for less smooth functions.</li><li>Periodic Kernel — Useful for when the data exhibits periodic behavior, like seasonal cycles.</li></ol><p>Domain knowledge and EDA are essential to choosing an appropriate kernel type for a dataset.</p><p>Now, the formula for inference using a Gaussian Process is as follows:</p><ol><li>Compute a covariance matrix of the training features using the selected kernel (denoted K(x, x), or <em>K</em>)</li><li>Compute a covariance matrix of the training features and the test-set features using the selected kernel (denoted K(x*, x), or <em>K*</em>)</li><li>Compute a covariance matrix of the test-set features using the selected kernel (denoted K(x*, x*), or <em>K**</em>)</li><li>Compute the mean (estimate of dependent variable) using the following formula: <em>μ ​= K*^T​[K+σ^2​I]^−1y</em>, or in words, K* transposed multiplied by K + sigma_squared inversed multiplied by the training dependent variable y.</li><li>Compute the covariance (uncertainty associated with mean estimate) using the formula: <em>cov(f∗​) = K** ​− K*^T​[K+σ^2​I]^−1K*</em></li></ol><p>This will produce a mean estimate of the dependent variable for every record in the provided set of test features.</p><p>I use the following code to implement what I previously described:</p><pre># Contructs a RBF kernel matrix<br>def rbf_kernel(x1, x2, sigma_squared, l):<br><br>    x1 = x1.to_numpy()<br>    x2 = x2.to_numpy()<br><br>    # Compute squared Euclidean distances (efficiently)<br>    x1_sq = np.sum(x1**2, axis=1, keepdims=True)<br>    x2_sq = np.sum(x2**2, axis=1, keepdims=True).T<br>    pairwise_sq_dists = x1_sq - 2 * x1 @ x2.T + x2_sq<br><br>    # Compute RBF kernel<br>    e = 2.7182818<br>    K = (-pairwise_sq_dists / (2 * l**2))<br>    K = np.array(K, dtype=float)<br>    result = sigma_squared * e**(-pairwise_sq_dists / (2 * l**2))<br>    return np.array(result, dtype=float)<br><br><br># Returns a Gaussian Process estimate (mean) with variance<br>def gaussian_process(sigma_squared, l, train_x, train_y, test):<br>  train_train_covariance = rbf_kernel(train_x, train_x, sigma_squared, l)<br>  train_test_covariance = rbf_kernel(train_x, test, sigma_squared, l)<br>  test_test_covariance = rbf_kernel(test, test, sigma_squared, l)<br><br>  mean = train_test_covariance.T @ inv(train_train_covariance + (sigma_squared * np.eye(len(train_train_covariance)))) @ train_y<br><br>  # We use the squared-exponential covariance function<br>  covariance = test_test_covariance - train_test_covariance.T @ inv(train_train_covariance + (sigma_squared * np.eye(len(train_train_covariance)))) @ train_test_covariance<br><br>  return (mean, covariance)</pre><p>Note my use of the Radial Basis Function as my kernel. <em>sigma_squared </em>and <em>l</em> are hyperparameters that control the degree of covariance calculated between data points. We’ll focus on finding the optimal values for these in the next section!</p><h4>Tuning Hyperparameters</h4><p>Gaussian processes that use the RBF kernel are very sensitive to the values one chooses for sigma_squared and l.</p><p>The good news is one can find optimal values for these hyperparameters using the standard set of approaches for hyperparameter tuning in machine learning.</p><p>Here, I chose to use <a href="https://www.geeksforgeeks.org/hyperparameter-optimization-based-on-bayesian-optimization/">Bayesian Search</a>, a more sophisticated method of searching for the optimal values compared to common methods like grid search.</p><p>The first step in Bayesian Search is to define an objective function, so that different values for the hyperparameters can be directly compared in their performance.</p><pre># Creating an objective function for the hyperparameter search<br>def objective_function(params):<br>    sigma_squared, l = params<br><br>    # Create the Gaussian Process model (using the features that are preprocessed)<br>    means, covariance = gaussian_process(float(sigma_squared), float(l), X_train_dummies, y_train, X_test_dummies)<br><br>    # Evaluate the model using MAE<br>    scores = mean_absolute_error(np.array(y_test), means)<br>    return scores</pre><p>Here, I simply use the mean absolute error (MAE) of my predictions from the Gaussian Process and the true test set values of G3.</p><p>Next, I define the space in which to search for values:</p><pre>search_space = [<br>    Real(0.001, 100, name=&#39;sigma_squared&#39;),<br>    Real(0.001, 100, name=&#39;l&#39;)<br>]</pre><p>Here, I’ll search for values between 0.001 and 100 for both hyperparameters.</p><p>Finally, we run the search using the <em>gp_minimize</em> module from <em>skopt:</em></p><pre>from skopt import gp_minimize<br><br># Perform Bayesian optimization<br>result = gp_minimize(<br>    objective_function,<br>    search_space,<br>    n_calls=50,<br>    random_state=42,<br>    n_initial_points=10<br>)<br><br># Best hyperparameters<br>best_sigma_squared, best_l = result.x<br>print(f&quot;Best sigma_squared: {best_sigma_squared}, Best l: {best_l}&quot;)</pre><p>The output decided that the best value for sigma_squared was 44.58 and the best for l was 9.99.</p><p>I now have everything I need to validate that I have a working Gaussian Process model!</p><h4>Model Training/Validation</h4><p>To validate my model, I wanted to employ a more robust approach than using the classic train-test split.</p><p>So, I decided to approach validation using K-Folds cross-validation, <a href="https://www.statology.org/k-fold-cross-validation-in-python/">a technique you can read about here.</a></p><p>I wrote my own function to implement this:</p><pre># Validating model with k-folds cross validation<br>def k_folds_cross_val(n_folds, features, target, metric=mean_absolute_error):<br>  scores = []<br><br>  bottom = 0<br>  top = (len(target) // n_folds)<br><br>  for fold in range(n_folds - 1):<br><br>    means, covariance = gaussian_process(sigma_squared, l, pd.concat([features.iloc[:bottom, :], features.iloc[top:, :]]), pd.concat([target.iloc[:bottom], target.iloc[top:]]), <br>                                         features[bottom:top])<br><br>    mae = mean_absolute_error(np.array(target[bottom:top]), means)<br>    scores.append(mae)<br><br>    bottom = top<br>    top = top + top<br><br>  return np.mean(scores)</pre><p>This helps me ensure that my model performs well on unseen data, AKA actually solving the task it&#39;s supposed to!</p><p>And that’s a wrap on this guide to modeling data with a Gaussian Process!</p><p>Gaussian Processes are very flexible models with deep statistical underpinnings and are perfect for small to medium size datasets with complex relationships that can’t easily be captured with a method like multiple-linear regression.</p><p>If you’d like the accompanying code for this analysis, <a href="https://colab.research.google.com/drive/1qmD4Ts-sLy8O9g_gt1JbICNTgjiHk6y5?usp=sharing">you can check it out here!</a></p><p>Also, in my quest of life-long learning, I’d love to hear your thoughts about things I could have done better in this analysis, concepts I did not explain well enough, or what you would like to know more about. Feel free to leave a comment or reach out to my email mazurkiewiczj@duq.edu!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ebdc3d73ba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieve Remarkable Speedup with Python Threads]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/achieve-remarkable-speedup-with-python-threads-2356e35b99dc?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2356e35b99dc</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 18:55:08 GMT</pubDate>
            <atom:updated>2025-01-11T18:55:08.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gse--B9uuWGyn5Y4ypukcQ.png" /></figure><p>I love Python. It’s a versatile programming language that grants me the power to manipulate data, create compelling visualizations, and run lightweight programs.</p><p>I also hate Python. Because it’s slow. Like, really slow.</p><p>I was curious about ways I could speed up my Python programs when I uncovered the world of multi-threading and parallel computing. These are mechanisms that take advantage of idle compute resources to optimize programs.</p><p>I took no hesitation in purchasing a <a href="https://www.udemy.com/course/parallel-computing-in-python/?couponCode=PLOYALTY0923">Parallel Computing Udemy course in Python</a> so I could fully learn about these features and add them to my skillset.</p><p>Are you sick and tired of slow, sputtering Python programs? Let me lead you into the magic world of threads!</p><h3>Threads</h3><p>Threads can be seen as “workers” stored within your computer. They can be resources in your CPU utilized to perform functions such as adding and subtracting numbers, searching for files, or building graphs of data.</p><p>Threading is a tactic by which you can create multiple workers to simultaneously complete Python tasks, thereby speeding up your program.</p><p>For example, suppose you have the goal to build a Python program that scrapes financial data from a variety of websites, downloads and parses this data, and then tabulates summary statistics about the trends and directions of the markets.</p><p>In a typical python program, built sequentially, you could have a function called <em>download_webpage()</em> that uses the <em>urllib</em> library to download information from a given website:</p><pre>import urllib<br>def download_webpage(URL):<br>  website = urllib.request.urlopen(URL)<br>  site_data = website.read()</pre><p>In a loop, you could repeatedly call this function to download all the webpages you desire:</p><pre>for webpage in webpages:<br>  download_webpage(webpage)</pre><p>What’s the problem with this approach? Well, during the time your Python program takes for the download to occur, no other work is being done! Each download has to wait until the previous one is completely done to begin. This can balloon to a particularly cumbersome issue if it takes a long time to download these pages.</p><p>What if, while our program was waiting for one page to download, we could call this download_webpage() function again to begin downloading the next webpage at the same time.</p><p>Consequently, we would not have to wait until the first page was entirely downloaded before beginning the next one. This would result in a dramatic speedup in our program!</p><p>This is what threads can accomplish in Python. Imported from the “threading” module, threads are workers that can run asynchronously from each other and are perfect for handling I/O intensive tasks like waiting for network downloads!</p><pre>from threading import Thread</pre><h3>Downloading Financial Websites Program with Threads</h3><p>Now, let’s make our program run a little faster! We begin by defining our download_webpage() method, just as before:</p><pre>def download_webpage(URL):<br>  website = urllib.request.urlopen(URL)<br>  site_data = website.read()</pre><p>Now, instead of merely calling this function for every webpage in our loop, for each iteration we create a new thread to run the function:</p><pre>for webpage in webpages:<br>  Thread(target=download_webpage, args=([webpage])).start()</pre><p>Notice how we create a thread. We supply it a<em> target function</em> to complete, in this case the download_webpage function we defined earlier. Then, we pass the <em>arguments</em> in a list, which is just the current URL of the website we wish to download. Finally, we must start the thread with the <em>start()</em> function.</p><p>Now, as each loop iteration passes, a new thread worker will be created to download the current webpage. As these threads wait for the network to download the page, the next one will activate its own download. This allows for the illusion of downloading every webpage at the same time, but the speedup is real!</p><p>For example, let’s take a look at the speed of this program with and without multiple threads. For this example, I compiled 50 Wikipedia articles about Finance I wanted to download:</p><pre>webpages = [<br>    &quot;https://en.wikipedia.org/wiki/Finance&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Economics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Investment&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Accounting&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Banking&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Stock_market&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Cryptocurrency&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Insurance&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Corporate_finance&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Public_finance&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Personal_finance&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Financial_planning&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Risk_management&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Financial_analysis&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Financial_markets&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Economic_policy&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Monetary_policy&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Fiscal_policy&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Economic_growth&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Inflation&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Deflation&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Exchange_rate&quot;,<br>    &quot;https://en.wikipedia.org/wiki/International_trade&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Global_economy&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Microeconomics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Macroeconomics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Economic_development&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Labor_economics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Health_economics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Educational_economics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Behavioral_economics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Environmental_economics&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Game_theory&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Market_structure&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Competition_law&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Business_cycle&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Capital_market&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Money_market&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Derivatives_market&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Bond_market&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Real_estate&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Venture_capital&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Private_equity&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Hedge_fund&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Mutual_fund&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Financial_institution&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Central_bank&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Commercial_bank&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Investment_bank&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Financial_crisis&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Economic_inequality&quot;,<br>    &quot;https://en.wikipedia.org/wiki/Taxation&quot;<br>]</pre><p>Here’s the single threaded version:</p><pre>start = time.time()<br>for webpage in webpages:<br>  download_webpage(webpage)<br>end = time.time()<br><br>print(f&quot;The time taken to complete: {end-start}&quot;)<br>The time taken to complete: 16.552650451660156</pre><p>And here’s the multi-threaded version:</p><pre>from threading import Thread<br>start = time.time()<br><br>for webpage in webpages:<br>  Thread(target=download_webpage, args=([webpage])).start()<br>end = time.time()<br><br>print(f&quot;The time taken to complete: {end-start}&quot;)<br>The time taken to complete: 0.0703892707824707</pre><p>Here, with multi-threading, the program only takes <strong>0.076 seconds</strong> to run as opposed to 16.55 seconds! <strong>That’s a 235-X speedup!</strong></p><p>In these download-heavy programs where waiting until one download completes to start another can cause bottlenecks, multi-threading can be a lifesaver!</p><p>I hope this simple example illustrates the power that using multiple threads holds in speeding up certain Python programs. I hope that you can take advantage of this knowledge to offset some of the downsides of programming in Python (namely, it’s slow speeds).</p><p>There are limitations to threads, most notably the <a href="https://wiki.python.org/moin/GlobalInterpreterLock">Python Global Interpreter Lock</a> (which is solved with Processes), but I’ll save that for the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2356e35b99dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Logistic Regression Actually Works]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/how-logistic-regression-actually-works-7a04a57158a1?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a04a57158a1</guid>
            <category><![CDATA[linear-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[maximum-likelihood]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 14:06:08 GMT</pubDate>
            <atom:updated>2024-10-14T14:06:08.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*AR_7dPZsfFNjwfWm" /></figure><p>Logistic regression is one of the most powerful linear models for predicting a nominal dependent variable from a linear combination of independent variables.</p><p>But how exactly do regression coefficients β0 + β1X + β2Y … combine to output a probability? In this article, we’ll break down the key pieces of logistic regression and explore them in detail.</p><h4>The Logistic Model</h4><p>Early statistical methods tried to fit regression lines to nominal dependent variables. Unsurprisingly, these models were not accurate, as regression model outputs are not bounded between 0 and 1.</p><p>To obtain the probability of a class, statisticians turned to the <strong>sigmoid function</strong>. The sigmoid function is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*kQjtFeIZtGP-k9Ny.png" /></figure><p>For any input of x, S(x) will yield a value between 0 and 1, exactly the property needed to predict a probability.</p><h4>Odds Ratios</h4><p>The building blocks of logistic regression models are <strong>odds ratios</strong>. Odds ratios are ratio statistics defined as the</p><p>f<em>requency of an event occurring / frequency of an event not occurring</em></p><p>Odds ratios evaluate <strong>risk</strong>. They illustrate the likeliness of events. But they are <strong>not</strong> <strong>probabilities.</strong> Probabilities fall between 0 and 1, whereas odds ratios can range from very small (0.0001) to very large (1,000,000).</p><p>To make this concrete, consider the following 2-way table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*8OcWMY0xLaTm27Wx8DQPkw.png" /></figure><p>To calculate the odds ratio for a female surviving, we use the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*gKSUEkpOqmIey-keleONDg.png" /></figure><p>This calculation becomes (53/131) / (78/234) = <strong>1.214</strong>.</p><p>Now, the data concludes that females are 1.214 times more likely to survive than males.</p><h4>Logistic Function and Odds</h4><p>Remember the odds of an event is the frequency of occurrence divided by the frequency of non-occurrence. This can be expressed as p / (1-p).</p><p>The odds of the logistic function can be formulated by the following fraction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*vKeRHUhoZ5wbwAMyPXquxw.png" /></figure><p>With some algebra, this simplifies to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/94/1*Wlf4cI5jzCw02yAKtkPvfA.png" /></figure><p>Considering x a linear combination of coefficients and independent variables <em>β0 + β1X + β2Y</em>, then e^x equals the odds of an event occurring.</p><p>In this way, the logistic function can predict the odds of a nominal variable.</p><h4>Log Odds</h4><p>If you’ve heard of the terms <em>log odds</em> or<em> logit, </em>it refers to the following algebraic simplification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*SErPuMuZAJt5CQPFFe36TA.png" /><figcaption>Taking the log of e raised to a power simplifies to the power.</figcaption></figure><p>Thus, the linear combination x is equal to the log of the odds.</p><p>The coefficients in x can be interpreted similarly to that of a regression. β1 is the rate of change in the log(odds) of y per unit change in x.</p><h4>Maximum Likelihood Estimation</h4><p>To make this concrete, let’s consider how we train a logistic regression model.</p><p>Hailing from the family of <em>supervised learning</em> methods, we assume a dataset with independent predictor variables and a nominal dependent variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*647vYUPJuf8Sj0ImvHCvpg.png" /><figcaption>Dependent variable is “Survived”</figcaption></figure><p>This is our <em>observed data. </em>We want to fit a sigmoid logistic function to this data so that, given new data points, we can predict the probability of the “Survived” dependent variable.</p><p>If we plot our data points in 2-dimensions, with x = age and y = survived, we obtain the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*SeJA57WYX3cLmxtPiumIpQ.png" /></figure><p>Notice the linear line doesn’t capture the relationship between age and survival all too well. Let’s create some new data points and fit a logistic curve for a clearer illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*JrOOyFUFo9o4e4TkjIkdPA.png" /></figure><p>The sigmoid curve represents the probability of survival for any input age x. Notice that the model is very confident for high and low ages but reaches a 50/50 prediction around age 37.</p><p>This represents our model, which will allow us to predict the class (survived or died) with new training inputs age. But how is this curve derived?</p><p>The idea behind training a logistic regression is maximizing the likelihood of our training data. Essentially, given our input features x (age), an algorithm finds the coefficients to our linear model β0 + β1X + β2Y that maximizes the probability of attaining our true labels y.</p><p>We need to maximize the likelihood function to accomplish this. The likelihood function for a logistic regression is:</p><p>P(yi​=1∣X)) + (1−yi​)(1−P(yi​=1∣X)</p><p>In words, it’s the probability of class 1 given the features plus 1 — the probability of class 1 multiplied by the probability of class 2. When the class predictions match the real classes, this value will be large. When the classes do not align, they will be small.</p><p>We then maximize the log of the likelihood function. This is an equivalent calculation to maximizing the regular likelihood function, but maximizing the log of the function creates simpler derivatives to compute, so it’s what’s used in practice.</p><h4>Gradient Descent (or Ascent)</h4><p>To obtain the optimal coefficients β0, β1, and β2 for our linear combination, gradient ascent is performed on the log of the likelihood function. This is equivalent to performing gradient descent on the negative of the log of the likelihood function.</p><p>Gradient ascent is a method to quantify the change in y (the probability of survival) given a change in the feature of x.</p><p>The gradient is computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*gAekiAr-IZA4VbAcv0f53w.png" /></figure><p>This equation means that the change in ℓ (the log-likelihood function) with respect to x (age) is the sum of the differences between the actual outcomes and the predicted probabilities for each age, multiplied by the corresponding age value.</p><p>We want to maximize ℓ, so we iteratively update our coefficients to adjust our prediction <em>P(yi = 1 | X)</em> to a value that minimizes the difference between it and the actual observed class <em>yi. </em>For example, if the real class is 1 (survived), we want a prediction that is close to 1 (like 0.97 or 0.95).</p><p>The gradient of ℓ tells us how much to change the coefficients to maximize ℓ. If the ℓ is small, the model’s predictions are close to the real values, so we slightly adjust our coefficients.</p><p>If the ℓ is large, then the model’s predictions are far away from the real data, and we must adjust our coefficients to a greater degree.</p><p>This iterative process yields the β0, β1, and β2 coefficients that maximize the log of the likelihood function. This produces the logistic regression model which can predict the class of a data point given their features.</p><h4>Assumptions of a Logistic Regression</h4><p>As with any linear model, logistic regressions rely on assumptions about the training data to perform well.</p><p>It’s imperative to validate these assumptions before deploying a logistic regression model or the model might perform very poorly on unseen data.</p><p>Here are the assumptions for the model:</p><ol><li>The dependent variable is binary (predicting a class, not a continuous value)</li><li>The observations are independent (the data points are not influenced by each other)</li><li>There is little multi-collinearity among the independent predictors (they are not highly correlated)</li><li>The sample size is sufficiently large (there are enough data points for each class)</li></ol><p>Armed with this knowledge, you are now ready to harness the power of logistic regression models for classification!</p><p>Logistic regression models are not as sexy as high-powered models like neural networks, but their explainability, simplicity, and light-weight nature make them desirable models in a variety of circumstances.</p><p><em>Top 3 Articles to Read Next</em></p><p>[1] <a href="https://medium.com/@jakemazurkiewicz6/the-cheat-code-for-landing-a-data-science-job-right-out-of-college-eb7cb040cfd2">The Cheat Code for Landing a Data Science Job Right Out of College | Medium</a></p><p>[2] <a href="https://medium.com/@jakemazurkiewicz6/i-completed-100-sql-interview-questions-heres-what-i-learned-8ee15d6e5e4b">I Completed 100 SQL Interview Questions. Here’s what I Learned. | Medium</a></p><p>[3] <a href="https://medium.com/@jakemazurkiewicz6/7-things-ive-learned-as-a-data-engineering-intern-cf915d553948">7 Things I’ve Learned as a Data Engineering Intern | Medium</a></p><p>Questions or comments? Reach out to me at <strong>mazurkiewiczj@duq.edu</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a04a57158a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Science Degree is Worthless in 2024. Here’s why.]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/a-data-science-degree-is-worthless-in-2024-heres-why-77198af70f7a?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/77198af70f7a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[college]]></category>
            <category><![CDATA[data-science-careers]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[degree]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 14:57:09 GMT</pubDate>
            <atom:updated>2024-10-11T14:57:09.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n62SKJ4N4cdijvBAJpQ_Uw.png" /></figure><p><strong>$142,880. </strong>That’s the average cost of a college education in the United States. That’s over 100 grand sunk into a piece of paper that may or may not help you land a job you actually enjoy.</p><p>$142,880. That’s enough money to buy a car, put a down payment on a house, and treat yourself to steak dinners 52 times a year.</p><p>I’m on the cusp of graduating from Duquesne University with a bachelor’s degree in data science. Next summer, I’ll be working as a full-time data scientist in the Dick’s Sporting Goods TDP. I’ve accomplished a lot over my 3.5 years here, but more frequently I find myself questioning the value of my data science education.</p><p>$142,880 is a lot of money to sink into a piece of paper. And after going through the wringer in my job hunt, I’ve come to a simple conclusion: <em>a data science degree is worthless in 2024.</em></p><p>Now, I’m not all doom and gloom. Obviously, there’s <em>some </em>value in a classic university education. I believe that the outsized returns in my data science career thus far, however, have come from things not taught in the classroom.</p><p>So, what should an aspiring data scientist do to land their dream job? I think it boils down to three main things.</p><h4>A Degree that Matters</h4><p>When I say a data science degree is worthless, I don’t mean <em>all</em> degrees are junk.</p><p>In fact, I think pursuing certain degrees is a no-brainer for those who want to break into data science.</p><p>The issue with data science degrees is their generalized nature and lack of structure. I made several data science major friends during my data engineering internship at Travelers Insurance. Whenever I asked them what their courses looked like, I always got a different answer. In fact, it seemed like <em>they</em> had a hard time explaining to me what they studied.</p><p>Of course, this isn’t the case for <em>every</em> data science program out there. I personally had some wonderful professors who taught me plenty of valuable skills. But, from my experience, a large quantity of data science programs lack structure, rigor, and defined purpose. They’re a classic example of a “jack of all trades, master of none”</p><p>From speaking to hiring managers, companies prefer specialized degrees. This is because data science contains lots of transferrable skills that can be taught on the job. Companies want candidates with hard skills that can’t be taught as easily on an office whiteboard.</p><p>Broadly speaking, they’re looking for:</p><ol><li>Computer science degrees</li><li>Statistics and applied mathematics degrees</li><li>Physics degrees</li></ol><p>These concentrations have much more depth in complex programming and math, skills that are harder to pick up compared to ones like data visualization.</p><p>If you’re going to drop $142,800 on an education, I think you’d be best served studying the more difficult and specific areas of data science. The companies I’ve worked for seem to agree.</p><h4>Practice, practice, practice</h4><p>When I was trying to get an internship at Duolingo, I reached out to a data scientist who worked there on LinkedIn. I asked them what a data science major should do to maximize their chances of landing a job out of college.</p><p>Their reply?</p><p><em>“From an industry perspective, typically the research side is less the bottleneck in projects than engineering chops, so I’d encourage you to learn more about data engineering and strengthen your Python skills. I’m a big believer in hands-on learning and participated in Kaggle competitions when I was transitioning out of academia. A strong data scientist is a storyteller — what is the hypothesis, and does the data support it?”</em></p><p>This was two years ago, but I see the wisdom in their advice clearer than ever after landing my own data science job offer.</p><p>I decided to intern as a Data Engineer at Travelers last summer even though my final goal was to become a data scientist. From this, I learned about what really allows large-scale data projects to succeed or fail. I also learned about the infrastructure and processes necessary to construct a working-grade model.</p><p>But more than anything, the one thing that propelled my success was <em>practice. </em>Becoming a skilled Python programmer gave me an edge over my data science peers.</p><p>But it didn’t come easy. I spent hours on <a href="https://leetcode.com/">LeetCode</a>, refining my eye for algorithmic coding. I participated in all the basic <a href="https://www.kaggle.com/">Kaggle</a> competitions, scanning through other’s notebooks for ideas to improve my models. And I planned and excited self-directed data science projects for <a href="https://jacobmaz.com/">my portfolio</a>.</p><p>Data science is a skill, just like anything else. And to improve a skill, it needs daily tending. Like a flower in a garden bed, daily practice feeds the sprout. Over time, what started as a seed becomes a strong root of knowledge and skills.</p><p>So, practice every day, or as much as you can. Don’t fall into the trap of thinking you already know enough.</p><h4>The Network Effect</h4><p>Are you starting to see the pattern here? The primary levers to pull in landing a data science job don’t come from a lecture hall.</p><p>This last piece of advice follows suit. It’s about the <strong>power of your network.</strong></p><p>Speaking to other data science hopefuls, there seems to be a false assumption about technical jobs. Many people seem to believe that networking is reserved for business majors. They believe that technical people don’t have to attend those awkward “networking” events.</p><p>I find this blatantly false.</p><p>I’m sure you’ve heard the saying it’s not what you know, but <em>who</em> you know that drives success. My network landed me the initial phone screening for my Data Science offer. Skipping the dreaded resume screening can be a major advantage to those looking to land a data science career.</p><p>A lot of aspiring data scientists don’t have a portfolio website, a LinkedIn page, a GitHub, an e-mail list, or strong connections. A lot of aspiring data scientists don’t have jobs.</p><p>Simply put, it’s pretty important that you meet people in the field and make your work known to those around you.</p><p>Here are just a few simple things I did to grow my network:</p><ol><li>Got to know my professors well (went to their office hours and had actual conversations about their interests)</li><li>Wrote articles on LinkedIn (mostly about my school projects or new data science concepts I was studying)</li><li>Set up meetings and lunch chats with employees at my internship</li><li>Established an online presence with a good LinkedIn page, portfolio website, and GitHub</li><li>Cold emailed data scientists in Pittsburgh with thought-out questions</li></ol><p>I know meeting people, especially those older and more experienced than you, can be intimidating. But having a strong network can open up so many doors for you come graduation time.</p><h4>Worthless Degrees</h4><p>Perhaps it’s a bit of an exaggeration to call data science degrees worthless in 2024. I learned many valuable skills from my time at Duquesne. Regardless, I have found that the primary drivers of my successes so far have come from concentrated effort outside of the classroom.</p><p>Taking Udemy courses on SQL, writing articles to expand my network, and accepting professional internships during my summers. These are the actions that truly benefited me.</p><p>If I could summarize this concisely, I’d say:</p><ol><li>Get a more specialized degree than data science like statistics</li><li>Practice your skills through Kaggle competitions and LeetCode</li><li>Grow your network by establishing an online presence.</li></ol><p>Simple, but not easy to do.</p><p>I continue to learn each day about the landscape of data science, as it evolves so rapidly. You can choose to ignore this advice, but it is what I have personally experienced through my journey from a data science freshman to landing a full-time offer.</p><p>Until next time, adiós!</p><p><em>Top 3 Articles to Read Next</em></p><p>[1] <a href="https://medium.com/@jakemazurkiewicz6/the-cheat-code-for-landing-a-data-science-job-right-out-of-college-eb7cb040cfd2">The Cheat Code for Landing a Data Science Job Right Out of College | Medium</a></p><p>[2] <a href="https://medium.com/@jakemazurkiewicz6/i-completed-100-sql-interview-questions-heres-what-i-learned-8ee15d6e5e4b">I Completed 100 SQL Interview Questions. Here’s what I Learned. | Medium</a></p><p>[3] <a href="https://medium.com/@jakemazurkiewicz6/7-things-ive-learned-as-a-data-engineering-intern-cf915d553948">7 Things I’ve Learned as a Data Engineering Intern | Medium</a></p><p>Questions or comments? Reach out to me at <strong>mazurkiewiczj@duq.edu</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77198af70f7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explainable AI with SHAP: See What Your Model’s Really Thinking!]]></title>
            <link>https://medium.com/@jakemazurkiewicz6/explainable-ai-with-shap-see-what-your-models-really-thinking-f953eae873e6?source=rss-8ad9dfaa89f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f953eae873e6</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[shapley-values]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[interpretability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jacob Mazurkiewicz]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 17:19:40 GMT</pubDate>
            <atom:updated>2024-10-10T17:19:40.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf-lHGv79lm3YfL6_xX67w.png" /></figure><p>Many people believe machine learning models don’t <em>have</em> to be explainable. They argue that the only important metric to optimize is predictive power.</p><p>But this viewpoint misses how models are actually deployed. For legal reasons, institutions like banks and insurance companies must be able to interpret their models. After all, it wouldn’t be fair to reject a loan application with a model that uses ‘race’ as its primary predictor variable.</p><p>Furthermore, understanding the machinations of machine learning models allow us to improve them, debugging and tuning their parameters. To uncover these benefits, we need a way of digging into complex models like neural networks and boosted decision trees.</p><p>Many techniques have been proposed within the past decade to accomplish just this. Today, we’ll explore <strong>SHAP values</strong>, a framework for explaining black box models through local predictions.</p><h4>What are SHAP Values?</h4><p>SHAP is an acronym for <strong>SHapley Additive exPlanations. </strong>It’s a method of using game-theoretic Shapley values to explain the outputs of any machine learning model. It accomplishes this by assigning an importance score to each predictor variable of the model, granting insight into, for a local prediction, which features were most prominent in producing the output.</p><p>SHAP values are derived from Shapley values, which distribute a “payout” (model’s output) fairly among a coalition of players (features of a model).</p><p>So how does it work? Let&#39;s first consider the question of what makes a feature important.</p><p>Shapley values define feature importance as the relative change in the output of a model with a feature X_i included compared to when it&#39;s not included.</p><p>For instance, let’s say we have 3 variables in a linear regression model predicting house price:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*iaLq82gQ0CuTGfVfywkToA.png" /></figure><p>To get the importance of a feature, we train a model f on all three variables f(X_1, X_2, X_3) and obtain an output of 180,000 for an input data record.</p><p>Now, we train a second model but exclude the first variable square footage X_1 in the training process. This model f’ is defined as f’(X_2, X_3) and its output for the same data record is 150,000.</p><p>The difference between the output of the two models is 180,000–150,000 = 30,000. This difference gives an estimate of the importance of Square Footage (feature X_1) in predicting house price.</p><h4>Shapley Regression Values</h4><p>To get accurate importance estimates for all predictor variables, we need to consider models trained on all combinations of feature subsets S ⊆ F where F is the set of all features.</p><p>To use the previous example, to calculate the importance of X_1, we need to take a weighted average of all possible model combinations that include and exclude feature X_1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*nFo9kfN6VbsdstVEZcgsbw.png" /></figure><p>We then take a weighted average of these combinations to get an importance score for each feature for single input vector of features. This is defined by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*jAcpgKOieGDhL3mNX4Ld-w.png" /><figcaption>[1]</figcaption></figure><p>Where:</p><ol><li>φ_i is the Shapley importance value for the i-th predictor variable</li><li>S is a subset of features in the feature space F</li><li>f_S∪{i} is a model trained with the feature X_i present</li><li>f_S is a model trained with the feature X_i excluded</li><li>x_S are the values of the input features in the current subset combination S</li></ol><p>Let’s walk through an example of computing the Shapley regression value for X_1 using the housing prices example.</p><p>First consider the outputs of our models trained on subsets S of the feature space F for a given data record:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*315oq-5bt9RaHg1HEWWLhw.png" /></figure><p>Now, we compute the absolute value of the differences between the corresponding models’ outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Njouf_k3OEnusU2T760NEw.png" /></figure><p>Now, we multiply each difference by the weight of that model. The weight is given by the formula below. Here’s an example of our first model trained on a subset of 2 features f’(X_2, X_3):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WmJe0_GKP5KE0_6byWQ8Cg.png" /></figure><p>We then sum all of these weighted differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_7tjJ1GTo89B1kqSX_EYoQ.png" /><figcaption>Model f’(X_2)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5KkUPRPHuwEubGU7bRLEQw.png" /><figcaption>Model f’(X_3)</figcaption></figure><p>Our final Shapley regression value of Square Footage X_1 for this data record is then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*oZ1EIps-dU4vD5Tj9y89dg.png" /></figure><p>We perform this procedure for every feature X_i in F to get our importance scores. For a single input vector, we can now know which variables were more influential in creating the output. Note that these values are <strong>local</strong> to a single data instance and will likely change for a different row.</p><h4>Shapley Sampling Values</h4><p>By now, you probably have noticed how inefficient calculating Shapley regression values can be. After all, you have to train models on every possible combination of features. This quickly becomes infeasible when the feature space F is large.</p><p>Luckily, we can apply Monte-Carlo sampling approximations to the formula above to estimate the Shapley values for each feature without the exorbitant computational cost.</p><p>Instead of calculating all 2^|F| feature subsets, we randomly sample k combinations for each predictor variable X_i and average their values to retrieve Shapley importance scores.</p><p>Additionally, instead of directly computing the difference between models f and f’, we marginalize over the possible values for feature X_i from the training data.</p><p>For example, for the feature Number of Bedrooms X_2, we take 2 samples from our dataset. These samples are complete data records, we can call them x and z. We now construct two new data points x+ and x-.</p><p>x+ is the record x with all feature values up to and including X_2 (which is just X_1 in this example taken from x and all values after X_2 taken from z (which is just X_3).</p><p>x- is the same, but with X_2 not taken from x but from z. Then we calculate the difference in the predictions based on these two points x+ and x- to calculate our importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KcIgf5kcCrCE0vjr9tK2IA.png" /><figcaption>For two randomly chosen records x and z, we compute new records x+ and x-; x+ has every value up to and including X_i from x and everything after from z. x- has every value up to but not including X_i from x and everything else from z.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*jRHydljfyxXeGJe82PGosQ.png" /><figcaption>Then, we take the difference in the predictions from these two datapoints.<a href="https://christophm.github.io/interpretable-ml-book/shapley.html"> (Source)</a></figcaption></figure><p>This allows us to view the relative contribution of feature X_2 (Number of Bedrooms) directly through inference, rather than retraining a model from scratch. Assuming that inference is less expensive than training (which it usually is), this method significantly speeds up the process of computing Shapley values.</p><h4>Kernel SHAP</h4><p>One of the primary benefits of SHAP values are their versatility. Model-specific SHAP implementations have been developed to explain certain types of models at a more granular level.</p><p>One of these methods is called Kernel SHAP, which are more powerful than classic Shapley values. Here’s how Kernel SHAP works</p><ol><li><strong>Randomly Sample Coalitions of Feature Subsets.</strong> Begin by creating several<strong> </strong>random subsets of features (called “coalitions”) from the complete feature set F. For a given instance x, each coalition represents a scenario where some features are known, and others are excluded. These coalitions are represented as binary vectors, where each element corresponds to whether a feature is included (1) or excluded (0).</li><li><strong>Generate Complete Data Records for Each Coalition. </strong>For each coalition (subset of features), we complete the data record by filling in the values for the excluded features. To do this, we replace the missing features with data from our dataset (like the mean or median). This ensures that every coalition is converted into a full data point that can be evaluated by the original model.</li><li><strong>Calculate Model Predictions for Each Coalition. </strong>Pass the complete data records (from step 2) through the original model f to obtain predictions. These outputs reflect how the model would behave if only the included features were known, and the others were filled with baseline values.</li><li><strong>Weight the Coalitions Based on Feature Presence. </strong>Assign weights to each coalition based on the number of features present in that subset. Coalitions with many or few features present are weighted more heavily, as they explain more about the features (compared to a 50/50 included/excluded split). The weight for each coalition is computed using the Shapley Kernel formula below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*p2NWxRgovfwLL84wZ0NWkw.png" /></figure><p>5. <strong>Fit a Linear Model to Approximate the Original Model. </strong>Fit a weighted linear regression model. The goal is to approximate the original model’s predictions as a weighted sum of the contributions of each feature. The linear model is trained by minimizing the weighted sum of squared errors between the original model’s predictions on the full feature space and the predictions of the linear model for each coalition.</p><p><strong>6. Extract Shapley Values</strong>: The coefficients of the regression model are the SHAP values. These represent the contribution of each feature to the model’s prediction for the instance being explained.</p><p>You can see the similarities of Kernel SHAP to the previous methods. We still study the outputs of models including an original feature X_i and an output that excludes or has an altered version of X_i.</p><p>Kernel SHAP values allow us to explain predictions more precisely and quicker compared to methods like Shapley regression values.</p><h4>Consistency and Accuracy</h4><p>You may be wondering what makes SHAP values more effective at deciphering models compared to other methods like XGBoost’s <em>feature_importance </em>module or LIME values.</p><p>It turns out, it boils down to two desirable properties that SHAP values exhibit that the others do not: consistency and accuracy.</p><p>Consistency is defined by the following theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*gCK7gnxep8E-ILoRKYjJtg.png" /><figcaption>[1]</figcaption></figure><p>Now, I know this looks scary, but let’s break it down. Essentially, consistency says that if a model relies more on a feature for its output, this should be reflected in the SHAP values. This means that for a single prediction, if a model f truly relies more on feature X_1 to makes its prediction compared to a different model f’, then the SHAP value for X_1 should be greater in model f compared to f’.</p><p>In the above equation. f’_x(z’) — f’_x(z’ \ i) is simply the difference between the outputs of a model trained with and without the feature, exactly the same as we computed above. The equation states that if this difference is larger for model f’, then the Shapley value φ_i(f’ , x) for model f’ and feature x should also be larger.</p><p>SHAP values are proved to be consistent.</p><p>If a model is accurate, then the sum of all the feature importances should equal the total importance of the model. For example, in a linear model, the sum of each parameter’s R² value should equal the total R² for the model.</p><p>This property allows us to view the even partitions of importance of each predictor variable in a model. If these importance terms did not sum to the total importance, we could not interpret how the combinations of importances interact with the output of the model.</p><p>SHAP values are also accurate.</p><p>These properties give SHAP robustness over methods like XGBoost feature importance.</p><p>For example, in the XGBoost importance calculation, we measure the number of times a feature is used to split data within the trees, called the <em>weight. </em>This value can differ depending on where the feature is in the tree (near the root or leaves), and will vary between random trees in ensemble models, violating consistency.</p><p>Errors like this in other explainability procedures make SHAP values the preferred method for interpreting predictions today. They also allow us to make local explanations, granting insight into the workings behind specific predictions.</p><h4>On the Importance of Explainability</h4><p>If you reached this point of the article, you may be asking yourself “So what?”</p><p>Model explainability isn’t the sexiest topic, as explainable models often come at reductions in predictive power and slowed deployment. But it&#39;s essential that data scientists and engineers understand the behavior of our models.</p><p>We use machine learning today in ways that truly affect people’s lives. Models determine if a newly expecting couple can secure a loan for their dream home, whether a well-behaved inmate receives parole, and where police should patrol within a city to stop the maximum amount of crime.</p><p>If we blindly deploy these models without considering their underlying mechanisms, we risk harming people, discriminating against populations, and coming to false conclusions. These are all undesirable outcomes for the ethical data scientist or engineer.</p><p>SHAP values allow us to probe our models and see what’s going on under the hood. With this knowledge, we can tune our models away from biased predictors, debug over-reliance on outliers, and produce more transparent models that foster trust in data science.</p><p>Then, we can continue to make a positive impact with our work.</p><p>References:</p><p>[1] Scott M. Lundberg and Su-In Lee. 2017. A unified approach to interpreting model predictions. In Proceedings of the 31st International Conference on Neural Information Processing Systems (NIPS’17). Curran Associates Inc., Red Hook, NY, USA, 4768–4777.</p><p>[2] Molnar, C. (2024, July 31). <em>Interpretable machine learning</em>. 9.6 SHAP (SHapley Additive exPlanations). <a href="https://christophm.github.io/interpretable-ml-book/shap.html">https://christophm.github.io/interpretable-ml-book/shap.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f953eae873e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>