<?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 Do Lee on Medium]]></title>
        <description><![CDATA[Stories by Do Lee on Medium]]></description>
        <link>https://medium.com/@dolee?source=rss-607ad4750966------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*is9kyu0SutUDlY7Htdl1mw.png</url>
            <title>Stories by Do Lee on Medium</title>
            <link>https://medium.com/@dolee?source=rss-607ad4750966------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:12:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dolee/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[Arvato Financial Services: Customer Segmentation]]></title>
            <link>https://dolee.medium.com/arvato-financial-services-customer-segmentation-27cd76487994?source=rss-607ad4750966------2</link>
            <guid isPermaLink="false">https://medium.com/p/27cd76487994</guid>
            <dc:creator><![CDATA[Do Lee]]></dc:creator>
            <pubDate>Fri, 22 Apr 2022 05:10:49 GMT</pubDate>
            <atom:updated>2023-08-25T19:35:14.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4i2RF1DqFUGfyviNMNWJhA.jpeg" /></figure><h3>Project Overview</h3><p>We are given a demographics data set (Udacity_CUSTOMERS_052018.csv) containing approximately 200k customers and 369 features for a mail-order company in Germany. In addition, a demographics data set covering the German population (Udacity_AZDIAS_052018.csv) is given with about 900k persons and 366 features. I will refer to the general population data set as <em>general</em> and the customer data set as <em>customers</em>. There are two goals for this analysis.</p><ul><li>First, we want to use unsupervised learning techniques (PCA and KMeans) to understand the customer base of a mail-order company and match the customer profiles to the general population. We are answering the question: Who are the target customers in the general population?</li><li>Second, we want to use the learnings from this analysis and create a supervised predictive model to determine if a customer would be a good fit for the mail-order company — identify customers who will most likely convert to paying customers.</li></ul><h3>Methodology</h3><h4><strong>Exploratory Analysis</strong></h4><ul><li>The primary goal of the exploratory analysis stage is assessing missing values in both data sets and understanding the underlying feature types (e.g., categorical, continuous, feature distribution, etc.).</li><li>We dropped features with over 40% of missing values and ambiguous features.</li><li>We also dropped rows where missing values were greater than 50%. Each row is represented as a user.</li><li>In addition, during the exploratory analysis stage, we analyzed feature dtypes, prefix groupings, and skewness.</li></ul><h4><strong>Data Preprocessing</strong></h4><ul><li>We applied the following imputation strategies to address missing values in the data sets.</li><li>Imputation strategy 1: All categorical and binary features were imputed by their most-frequent values.</li><li>Imputation strategy 2: The continuous features were imputed with their mean values.</li></ul><h4><strong>Unsupervised Learning</strong></h4><ul><li>In this analysis stage, we combine Principal Component Analysis (PCA) and KMeans to conduct a powerful set of transformations to deduce important features and create relevant clusters.</li><li>PCA Step 1: First, both data sets were standardized. Using the general data set, we fitted and transformed the data using PCA.</li><li>PCA Step 2: We applied dimensionality reduction to the feature set, and the goal was to retain the most important principal components. More specifically, we used the general data set to fit the PCA model, and then we conducted dimensionality reduction with the fitted PCA model on the customers data set.</li><li>KMeans Step 1: We determined the number of clusters using the elbow plot. We iterated through the general data set a few dozen times by taking a 10% random sample each time and fitting PCA to calculate inertia. Scikit-Learn’s documentation states, “The K-means algorithm aims to choose centroids that minimize the inertia, or within-cluster sum-of-squares criterion.” The x-axis is the number of clusters, and the y-axis is a range of inertia scores. Essentially, we are looking for the elbow shape to determine the number of clusters.</li><li>KMeans Step 2: Once the number of clusters is determined, the KMeans model is fitted with the general PCA-transformed data set. Using the fitted model, the predict() method is applied to both general and customers data sets to generate cluster labels for each user. Next, we compared the two prediction outputs and examined which clusters were overrepresented in the customers data set using the general data set as the baseline.</li><li>KMeans Step 3: We selected the most overrepresented cluster and examined the actual categorical labels. We used pca.inverse_transform() method to map back to the original features and then examined which labels were prominently attached to these users. This allowed us to understand the dominant categorical labels associated with these users.</li></ul><h4><strong>Supervised Learning</strong></h4><ul><li>Step 1: First, we closely examined the train data with the response variable and addressed missing values and ambiguous features. We applied the same imputation techniques used earlier to preprocess the train data set.</li><li>Step 2: The oversampling/undersampling approach comes from an ML blog post, which can be found <a href="https://machinelearningmastery.com/random-oversampling-and-undersampling-for-imbalanced-classification/">here</a>. In this approach, we oversampled the minority class to create a 10:1 ratio and then undersampled the majority class to create a 2:1 ratio by removing rows from the majority class.</li><li>Step 3: The transformed train data set was plugged into several ML models, and the best-performing model was chosen using ROC AUC. In the end, Random Forest won out. We also leveraged Random Forest’s impurity-based feature importance method to identify important features.</li></ul><h4><strong>Hyperparameter Tuning</strong></h4><ul><li>Step 1: Randomized Search CV tuned the model by optimizing Random Forest’s hyperparameters. Exhaustive GridSearchCV was also used but did not show incremental improvement in ROC AUC.</li><li>Step 2: In the end, a fitted Random Forest model optimized with RandomSearchCV was used to make the predictions on the test data set.</li></ul><h3>Metrics</h3><p>To measure how models perform, we need metrics to help us gauge if what we observe is moving in the right direction. If not, we must implement techniques and strategies to mitigate against low-performing models.</p><p>For the unsupervised learning section, we leveraged PCA to mitigate against high dimensionality in the data set so that Euclidean distance-related calculations are not inflated when the input data set is plugged into KMeans. Therefore, the most helpful metric for PCA would be explained variance, which helps to determine the cutoff point and the number of principal components. In addition, for KMeans, the important metric or threshold would be the number of clusters.</p><p>For supervised learning, the metric that stood out for this particular case was ROC AUC, which is great for imbalanced data sets. Therefore, ROC AUC was used as the success metric in the supervised learning section. We also applied oversampling and undersampling techniques to generate a relatively more balanced data set.</p><h3>Exploratory Analysis</h3><h4><strong>Missing Values</strong></h4><p>All features in both data sets have missing values. Some have a lot more than others. Six features are missing 65% or more observations for the general data set. The chart shown in Figure 1 illustrates % of observations missing relative to each other. Although fonts are too small to see the feature names, the importance of the visualization is to show that all features are missing some values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-NxnwdSSlxz3Kc1HB1z7g.png" /><figcaption>Figure 1: All features are missing certain % of values; Gray box highlights the extreme cases</figcaption></figure><p>We are seeing similar patterns with the customers data set; some are missing a lot more than others. It will be important going forward to assess how these features will impact the analysis. I will soon dive into strategies and techniques to handle these features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5K_VPFXScNoVSpJva6Wjw.png" /><figcaption>Figure 2: All features are missing a certain % of values; the gray box highlights the extreme cases</figcaption></figure><h4><strong>Drop features with over 40% of missing values and ambiguous features</strong></h4><p>At this stage, the goal is to go after the low-hanging fruits. It made sense to drop features with 40% or more missing values in both data sets. In addition, several very ambiguous and highly skewed features will most likely not add much value to our analysis.</p><p>The code snippet below shows the six features missing more than 40% across both data sets. The next line captures the ambiguous and highly skewed features. What does it mean that a feature is ambiguous? This means the feature had no description in the additional supplementary Excel files and no real way to decipher these. At the same time, the features are skewed, meaning most labels are a specific value or label.</p><pre>missing_features =[&#39;ALTER_KIND1&#39;,&#39;ALTER_KIND2&#39;,&#39;ALTER_KIND3&#39;,&#39;ALTER_KIND4&#39;,&#39;EXTSEL992&#39;,&#39;KK_KUNDENTYP&#39;]</pre><pre>ambiguous_skewed_features = [&#39;STRUKTURTYP&#39;,&#39;GEMEINDETYP&#39;,&#39;ARBEIT&#39;,&#39;RELAT_AB&#39;,&#39;ANZ_HH_TITEL&#39;,&#39;KONSUMZELLE&#39;,&#39;FIRMENDICHTE&#39;,&#39;AGER_TYP&#39;,&#39;TITEL_KZ&#39;,&#39;GEBURTSJAHR&#39;, &#39;EINGEFUEGT_AM&#39;,&#39;VERDICHTUNGSRAUM&#39;,&#39;D19_LETZTER_KAUF_BRANCHE&#39;]</pre><h4><strong>Drop user rows where missing values are greater than 50%</strong></h4><p>This step dropped user rows missing 50% or more of the feature values. For each person, if features were missing or flagged as NaN, these were dropped to reduce the number of individuals with incomplete or highly sparse profiles.</p><p>Before qualified rows were dropped, the general data set rows and columns had these dimensions (891221, 349). Once this logic was applied, it reduced the number of rows by about 100k (791987, 349).</p><pre>Before dropping user rows: (891221, 349)<br>After dropping user rows: (791987, 349)</pre><p>The same logic was applied to the customers data set and reduced the number of rows by about 50k. The below code output shows where we stand at this point.</p><pre>Before dropping user rows: (191652, 352)<br>After dropping user rows: (140899, 352)</pre><h4><strong>Analyze the dtypes, prefix groupings, and skewness</strong></h4><p>At this stage, I examined the dtypes and grouped features by prefix in preparation for imputing the features with missing values. Most features contain floats and integers except four from general and six from customers. This is good to know, and we’ll address these objects later in the feature transformation step.</p><pre>Azdias<br>float64    253<br>int64       92<br>object       4<br>Name: dtype, dtype: int64<br><br>Customers<br>float64    253<br>int64       93<br>object       6<br>Name: dtype, dtype: int64</pre><p>At this point, I want to examine the general data set more closely. I wanted to see what features were still missing values and extract the prefix to create an imputation strategy to group these features. Although the features are mostly numeric values, almost all are ordinal or nominal categorical features. The breakdown by prefix analysis shows that 235 features can be grouped into 26 prefixes in the general data set.</p><pre>Number of prefixes: 26<br>Number of features: 235<br><br>Count of Prefixes:<br>[(&#39;KBA13&#39;, 116), (&#39;KBA05&#39;, 63), (&#39;CJT&#39;, 8), (&#39;D19&#39;, 8), (&#39;PLZ8&#39;, 7), (&#39;LP&#39;, 6), (&#39;CAMEO&#39;, 3), (&#39;RT&#39;, 3), (&#39;VK&#39;, 3), (&#39;UMFELD&#39;, 2), (&#39;ALTERSKATEGORIE&#39;, 1), (&#39;BALLRAUM&#39;, 1), (&#39;EWDICHTE&#39;, 1), (&#39;GEBAEUDETYP&#39;, 1), (&#39;GFK&#39;, 1), (&#39;HH&#39;, 1), (&#39;INNENSTADT&#39;, 1), (&#39;KKK&#39;, 1), (&#39;KONSUMNAEHE&#39;, 1), (&#39;MOBI&#39;, 1), (&#39;ONLINE&#39;, 1), (&#39;ORTSGR&#39;, 1), (&#39;REGIOTYP&#39;, 1), (&#39;RETOURTYP&#39;, 1), (&#39;VHN&#39;, 1), (&#39;W&#39;, 1)]</pre><p>To get a sense of skewness by prefix, I created a function that generates histograms for each prefix and Pandas’ skew() function was used to calculate the skew value for each feature.</p><ul><li>The data are considered fairly symmetrical if the skewness is between -0.5 and 0.5.</li><li>The data are moderately skewed if the skewness is between -1 and 0.5 or between 0.5 and 1.</li><li>The data are highly skewed if the skewness is less than -1 or greater than 1.</li></ul><p>Here is an example of the output for the “UMFELD” prefix, which is attached to two features. The output shows two histograms with corresponding skew values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*uUqKQ3MZ0cIoN-YcPoD2pQ.png" /><figcaption>Figure 3: Pandas skew() function values and histograms</figcaption></figure><h3><strong>Data Preprocessing</strong></h3><h4><strong>Imputation strategy</strong></h4><p>At this stage of the preprocessing step, we are ready to impute the data after removing sparse features and user rows. A few features in this group had no descriptions in the provided Excel files. In these cases, I examined their histograms and identified the features as ordinal or nominal. In Figure 4, all the features are categorical except one. And most categorical features are ordinal. There are a few nominal features, one continuous, and one binary feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*DewRm0kZjpQJmSOMwTrGoA.png" /><figcaption>Figure 4: Count features by prefix; Under description, I have labeled the prefix features as ordinal or nominal.</figcaption></figure><p>After analyzing these features, the imputation procedure involves two main approaches:</p><ul><li>Strategy 1: All categorical and binary features are imputed by their most-frequent values.</li><li>Strategy 2: The continuous features will be imputed with their mean values.</li></ul><p>I leveraged sklearn to create an imputation pipeline for features missing values. Here is the code that creates the imputation preprocessors. Once the features were imputed, they were merged with the rest of the complete features to create the final data sets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69e10b5b88e741fa383a67eefed448ef/href">https://medium.com/media/69e10b5b88e741fa383a67eefed448ef/href</a></iframe><h3>Unsupervised Learning Models: PCA + KMeans</h3><p>A large portion of the customer segmentation analysis will perform principal component analysis on the two data sets to linearly reduce the number of dimensions (fewer features) using singular value decomposition and applying the clustering technique, KMeans, to better understand the underlying user base.</p><p>Let’s quickly articulate the goal for using PCA and applying KMeans. We are essentially using unsupervised learning techniques to describe the relationship between the demographics of the mail-order company’s customers and the general population of Germany. In the end, we will identify a group of folks in the general population that are a good representation of the mail-order company’s customer base.</p><h4><strong>PCA</strong></h4><p>Here’s a quick recap of where we stand. The general and customers data sets have the following rows and columns:</p><ul><li>General: 791,987 user rows and 346 features</li><li>Customers: 140,899 user rows and 346 features</li></ul><p>First, both data sets need to be scaled so that they can be fitted and transformed using PCA. I’m using sklearn’s StandardScaler() class object to scale the data. We instantiate the PCA object and fit the standardized general data set. In the code below, the instantiated PCA object only retains 95% of the variance. This is an arbitrary threshold that I have decided to use for this analysis. At the same time, we pass fit and transform to the general data set. The direct result is dimensionality reduction, where we had 346 features before, and after the transform step we are left with 212.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76a672fc2a369c677356b097531dc223/href">https://medium.com/media/76a672fc2a369c677356b097531dc223/href</a></iframe><p>Let’s take a closer look at what is going on by visualizing the cumulative explained variance as we increase the number of principal components and the exponentially decreasing curve to observe how much each component contributes to the overall explained variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*6_kbXjbSUD1KVZWiON805w.png" /><figcaption>Figure 5: Cumulative explained variance with an increasing number of principal components.</figcaption></figure><p>We often see the first few principal components capturing most of the explained variance. In this analysis, we have to go up to the 212th principal component to capture 95%. To further dissect each principal component, I’ll leverage sklearn’s pca.components_ attribute to understand what features are attributing the most to principal component 1, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*70eILzlf1xPWnxCk1lHZAw.png" /><figcaption>Figure 6: % explained variance contribution for each principal component.</figcaption></figure><p>It will help to review what pca.components_ attribute is comprised of and what the numbers represent. The pca.components_ attribute contains the loading scores, and under singular value decomposition (SVD), the principal components are scaled from -1 to 1. Regardless of the sign associated with the numbers, anything close to -1 or 1 indicates a strong influence on the components. The scaling of these numbers basically gives us singular vectors or eigenvectors for the principal components. Therefore, the loading scores are the coefficients paired with each feature in the first principal component and so on.</p><p>I’m only going to take a closer look at the first principal component, which, in my analysis, contributes about 8.34% to the total explained variance. I visualized the top 30 positive loading scores and the top 30 negative loading scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*nygH1_K_u_5gNr1AWo91YA.png" /><figcaption>Figure 7: Principal component 1: Top 30 positive and negative feature loading scores.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5070ad8252287fe7f18746449cda74df/href">https://medium.com/media/5070ad8252287fe7f18746449cda74df/href</a></iframe><h4><strong>KMeans</strong></h4><p>We are ready to apply KMeans to our general pca (azdias_pca) data set. First, we generate the kmeans elbow plot to eyeball the number of clusters we want in our final analysis. To generate this plot, we take about 10% sample data from azdias_pca data set and instantiate KMeans algo object with an increasing number of n_clusters. For every loop, we calculate the inertia_, which is the sum of squared distances of samples to their closest cluster center. We are starting at n_clusters = 1 and going up to n_clusters = 40. Here is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*RHMCojPQLImuYe_BwWpbhw.png" /><figcaption>Figure 8: Elbow Plot</figcaption></figure><h4>Scikit-Learn Clustering section has a great description of why we apply PCA before applying KMeans: (<a href="https://scikit-learn.org/stable/modules/clustering.html">source</a>)</h4><blockquote>Inertia can be recognized as a measure of how internally coherent clusters are. It suffers from various drawbacks:</blockquote><blockquote>* Inertia makes the assumption that clusters are convex and isotropic, which is not always the case. It responds poorly to elongated clusters, or manifolds with irregular shapes.</blockquote><blockquote>* Inertia is not a normalized metric: we just know that lower values are better and zero is optimal. But in very high-dimensional spaces, Euclidean distances tend to become inflated (this is an instance of the so-called “curse of dimensionality”). Running a dimensionality reduction algorithm such as <a href="https://scikit-learn.org/stable/modules/decomposition.html#pca">Principal component analysis (PCA)</a> prior to k-means clustering can alleviate this problem and speed up the computations.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0db57828313ae431ac69231dee15f7c1/href">https://medium.com/media/0db57828313ae431ac69231dee15f7c1/href</a></iframe><p>We settled at n_clusters = 15 after closely examining the elbow plot. Now we are fitting the KMeans algo object with 15 clusters using azdias_pca (general pca data set). Once KMeans object is fitted, we can start passing the general and customers pca data sets to the predict() function to generate the cluster labels for each user row. Basically, every row will be assigned a cluster number ranging between 1 and 15 because we went with n_clusters = 15.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e2c8111f62443d14bdf34b62fba37b6/href">https://medium.com/media/4e2c8111f62443d14bdf34b62fba37b6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*9z4ROwfG-gHT0T0tsAkz7A.png" /><figcaption>Figure 9: km_clusters data frame from the above computation.</figcaption></figure><p>There are eight clusters where the mail-order customers are more represented than the general population. Let’s take a closer look at these eight clusters. Cluster 12 definitely stands out from the rest and represents about 26.3% of the customer base of the mail-order company. Clusters 6 and 7 are interesting as well. We’ll dive deeper into profiling the users in cluster 12, which should give us a better picture of the mail-order company’s main customer base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*j9bsqj7ZIUoy41xTqqRRhw.png" /><figcaption>Figure 10: Clusters where customers are more represented than general.</figcaption></figure><pre># 8 clusters where the customers are larger than general population <br>km_clusters[‘diff’] = km_clusters.cust_cluster_pct — km_clusters.azdias_cluster_pct<br>km_clusters.sort_values(by=[‘diff’], ascending=False).head(7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*cuiuIfQTY7SMtd3a0LJZuw.png" /><figcaption>Figure 11: Bar chart of the table view from above.</figcaption></figure><p>To further our understanding of the customer base, we want to know the dominant features associated with users in cluster 12. We’re leveraging pca.inverse_transform() method to map back to the original features and then examine which labels are attached to these users. Keep in mind that almost all features are categorical. We’ll leverage the supplemental Excel files to look up the definitions of these categorical labels. Here are the functions we’ll use to inversely map back to the original features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc284d3369e92d33b074d7722db3efec/href">https://medium.com/media/fc284d3369e92d33b074d7722db3efec/href</a></iframe><h4>Results</h4><p>Because we are interested in cluster 12, it makes sense to examine the top 10 original feature PCA’s positive and negative loading scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*ENt0lTNe3Q-nqXY54mEZZA.png" /><figcaption>Figure 12: pca.inverse_tranform() original PCA top 10 positive and negative loading scores.</figcaption></figure><p>At this point, we want to examine these 20 features closely and see if we can extract some insights about the users who largely represent the customer base of the mail-order company. We map the general cluster labels to the original general data set and isolate users attached to cluster 12. Next, we examined the distribution of the labels in each feature. To streamline this process, we took the most frequently occurring label in each feature and generalized this segment of users.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b568b23731c375376008439ca76fe791/href">https://medium.com/media/b568b23731c375376008439ca76fe791/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*J3MTYJiPVQyn8DpIrLP0zw.png" /><figcaption>Figure 13: LP_LEBENSPHASE_FEIN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*uRyFG0J2vCKufsTWxeveJA.png" /><figcaption>Figure 14: CAMEO_DEUG_2015</figcaption></figure><p>Figures 13 and 14 capture two feature distributions. For the mail-order company, 26% of the customers fell into cluster 12. In other words, for every 4 customers, one of them fell into this cluster. At a closer glance, the customers in cluster 12 are predominantly represented by these attributes:</p><ul><li>Mostly low-income earners</li><li>Not versed with the online world</li><li>Most are working-class folks</li><li>Most are in their advanced age</li><li>Many have multi-cultural backgrounds</li><li>Many have low financial interests</li><li>Doesn’t drive expensive cars</li></ul><h3>Supervised Learning Model: Random Forest + Feature Importance</h3><p>We are now venturing into supervised learning to understand what features are highly associated with converting users into customers by using the train data containing the “RESPONSE” column. The train file, Udacity_MAILOUT_052018_TRAIN.csv, contains 42,962 user rows and 367 features. Similar to the earlier (PCA and KMeans) data sets, the train data set contains many features with missing values. We’ll be applying similar imputation strategies used in the unsupervised learning section to impute the features as well as drop ambiguous features.</p><p>First, we dropped features with 40% or more missing values and dropped ambiguous/skewed features using the same criteria used earlier. Second, we impute features using sklearn’s ColumnTransformer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a1d8e46ad3d700b90588c00413cf803/href">https://medium.com/media/9a1d8e46ad3d700b90588c00413cf803/href</a></iframe><p>Before deciding on Random Forest, the train data set was standardized and plugged into several algorithms to see which one performed the best. However, when examining the distribution of the response variable, the majority class (0) is overrepresented by about 80:1 ratio compared to the minority class (1), which is what we are interested in detecting. We want to mitigate the class imbalance and improve model performance as much as possible.</p><p>The oversampling/undersampling approach comes from an ML blog post, which can be found <a href="https://machinelearningmastery.com/random-oversampling-and-undersampling-for-imbalanced-classification/">here</a>. In this approach, we are oversampling the minority class to create a 10:1 ratio and then undersampling the majority class to create a 2:1 ratio by removing rows from the majority class. The output_model_stats function captures all the details and it’s designed to iterate through list of models. We measure model performance using roc_auc metric.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03a13a56f8ec04e05cd743555e15492a/href">https://medium.com/media/03a13a56f8ec04e05cd743555e15492a/href</a></iframe><h4>Results</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*PPytgobD0ni4H3y9hFFaaQ.png" /><figcaption>Figure 15: roc_auc score per model</figcaption></figure><p>As shown in Figure 15, Random Forest performed the best. Because Random Forest has a feature importance built-in using the impurity approach to ranking features, we are going to leverage this to examine the top 20 most important features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*7IEHjLAVVEdd2H7BsFlOxQ.png" /><figcaption>Figure 16: Random forest feature importance</figcaption></figure><h3>Hyperparameter Tuning</h3><h4><strong>RandomizedSearchCV: Random Forest Classifier</strong></h4><p>In order to improve the roc_auc metric, one of the ways is to run some form of grid search to tune hyperparameters. These hyperparameters are model specific and we can use RandomizedSearchCV in Scikit-Learn to further tune our Random Forest’s hyperparameters. This approach is less exhaustive and saves time. We want to try this approach first and maybe move on to running a full grid search using GridSearchCV leveraging the learnings from this iteration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99d6155acaf95148a01cd5fd6e6a705c/href">https://medium.com/media/99d6155acaf95148a01cd5fd6e6a705c/href</a></iframe><h4>Results</h4><p>It is time to test to see if these tuned hyperparameters will make a tangible difference in our model performance. Using our optimized Random Forest model, we’ll conduct cross-validation using RepeatedStratifiedKFold to generate the new roc_auc score. The new roc_auc of 0.70165 is an improvement from the initial number of 0.662905.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b15bb7b7933f2c8f35fbbf3e69331bc/href">https://medium.com/media/0b15bb7b7933f2c8f35fbbf3e69331bc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*LfWr76QkIpBijy6bvFJy_g.png" /><figcaption>Figure 17: ROC Curve</figcaption></figure><p>After observing an improvement in the roc_auc score using RandomizedSearchCV, we went ahead and ran GridSearchCV based on our learnings from previous tuning work. The GridSearchCV procedure did not generate a better roc_auc metric versus the RandomizedSearchCV. For the Kaggle competition, we’ll use the randomized search fitted model to make the predictions and submit our results.</p><h3>Conclusion</h3><p>With Random Forest, we can use labeled train data to understand what features are important. In applying PCA with KMeans, we reduced the number of features and understood relevant clusters of people that represented the customer base of the mail-order company.</p><p>Two powerful approaches — supervised and unsupervised learning techniques — identified important user attributes to discover prevailing patterns associated with mail-order conversion. In conclusion, we provided two views. First, a view of customers’ attributes that best fit the mail-order company. Second, a view of leveraging past conversion data and mining to see what features best describe the core customer base.</p><h3>Improvements</h3><p>A few improvements can be made further to enhance the performance in unsupervised and supervised learning approaches. First, rather than dropping features with a high % of missing values, applying different imputation strategies might have helped retain more information about the data set.</p><p>Second, although ambiguous features were dropped due to lack of documentation and skewness, they could be retained and eliminated iteratively by understanding their contribution to explained variance during PCA analysis. In doing so, during KMeans clustering analysis, we could have increased our probability of seeing an actual elbow in the elbow plot.</p><p>In the supervised learning section, different imputation methods could have been adopted to retain more information and thus create a more predictive model. We could also have tried different hyperparameter settings to tune the Random Forest model further. We could have also used a different metric to select the best-performing model after applying oversampling and undersampling techniques.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27cd76487994" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Surviving the RMS Titanic: A Brief]]></title>
            <link>https://dolee.medium.com/surviving-the-rms-titanic-a-brief-59e8a7b80d02?source=rss-607ad4750966------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e8a7b80d02</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[titanic-dataset]]></category>
            <category><![CDATA[rms-titanic]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Do Lee]]></dc:creator>
            <pubDate>Wed, 10 Nov 2021 00:25:10 GMT</pubDate>
            <atom:updated>2023-05-18T19:31:42.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>Highlights of what it took to survive the sinking ship and what determined survival in a nutshell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pm93NkTaIHz0t_KW" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>On April 15, 1912, the RMS Titanic sank into the depths of the Atlantic Ocean. This mighty ship was traveling from Southampton, England, to New York City with 2,224 souls, and the unthinkable happened — a collision with an iceberg. Without enough lifeboats to save all the passengers and crew on board, more than 1,500 people died.</p><p>In Kaggle’s <a href="https://www.kaggle.com/c/titanic">Titanic — Machine Learning from Disaster</a> challenge, you are given train and test data, and using machine learning your goal is to predict which passengers will survive or die. Before diving deep into the prediction part of the challenge, we must ask a few critical questions to understand the underlying data better.</p><ol><li>How many passenger classes did Titanic have, and what was the median age in each class?</li><li>Were there more families or single passengers on the Titanic?</li><li>What is the one characteristic among the passengers that determined the highest probability of survival?</li><li>Lastly, what are the important features (or characteristics) highly correlated to survival?</li></ol><h3>How many passenger classes did Titanic have, and what was the median age in each class?</h3><p>On the Titanic, there were three classes for passengers. First-class was the most expensive and mainly for the wealthier passengers and then the second and third-class fares. Let’s take a closer look at the age distribution for each class. In Figure 1, the three age density plots are pretty telling. The median age for first-class passengers was about 40 years old while second and third were 30 and 29, respectively. We can delineate that wealth was positively correlated with age during this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTnuCCN16mWMejQbfN-8lQ.png" /><figcaption>Figure 1: Age Density Plot per Pclass</figcaption></figure><p>It’s also interesting to note that the third-class passenger age density plot showed lower variability around the mean and higher peak than the rest. This finding indicates that most third-class passengers were relatively young. In addition, the third-class passengers made up about 55% of the total passenger population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6LmgGUtoIM4NEo21-YWaA.png" /><figcaption>Figure 2: Age Boxplot per Pclass</figcaption></figure><p>The boxplots in Figure 2 show another perspective. We observe decreasing variability (interquartile range) as we move from first-class to second and third. This data indicates that first-class passengers’ age varied more from young to old while third-class passengers were relatively more clustered around the median (around the 50th percentile).</p><h3>Were there more families or single passengers on the Titanic?</h3><p>Let’s take a quick look to see if passengers were traveling alone or part of a family. This particular data point would show us if survival increased for solo passengers versus families. To get the most accurate view of this, I combined train and test data.</p><p>To determine each passenger’s family size, it’s logical to add SibSp, ParCh, and the current passenger (+1). However, rather than defining this at the passenger level, it made more sense to determine the maximum family size based on ticket number and surname.</p><p>I’m sticking with the assumption that families traveled together and, in this case, on the same ticket. As a result, the sum of SibSp, ParCh, and current passenger, which represents the family size, is matched with a ticket number and surname.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Ae74IX_OFGV2RgF6QH1WPg.png" /><figcaption>Figure 3: Family Size on RMS Titanic</figcaption></figure><p>Figure 3 shows that most passengers were traveling alone. If the remaining crew on board prioritized saving families over single passengers, the latter group would face a more dire situation.</p><h3>What is the one characteristic among the passengers that determined the highest probability of survival?</h3><p>As you dive deeper into the data, a clear pattern begins to emerge — female passengers had the highest survival rate of approximately 74.2%. The single overwhelming driving force determining survival was being female. On the other hand, the overall male survival rate was about 18.9%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*qtrZWMLX8PazYpwZcSKhKQ.png" /><figcaption>Figure 4: Survival Rate by Sex</figcaption></figure><p>One might think that a predictive model, in this scenario, would need one feature (sex) to determine survival, and the prediction would be pretty close to the truth. However, to improve model predictions, we often tease out more information from the available train data. As a result, if we were to examine only the male passengers and slice the data with the given titles, such as “Mr” or “Master”, we are essentially dividing the male passenger group into adults and boys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*q0-Wq9OTR9cPeDmFRwrmjA.png" /><figcaption>Figure 5: Survival Rate by Titles</figcaption></figure><p>If we focus our attention on Mr and Master in Figure 5, we see that (male) children had a survival rate of 57.5% while adult male survival rate was about 16.01%.</p><h3>What are the important features (or characteristics) highly correlated to survival?</h3><p>In summary, I shared a few compelling characteristics among the Titanic passengers that determined their survival. The reality was that many of the passengers had no chance of surviving even though they most likely fought to survive.</p><p>To make pretty robust predictions, I used Random Forest algorithm to complete my model. I also created my own features using the original training data and measured all features for importance. After leveraging two frameworks to weigh each feature for importance, I ranked them and eliminated non-important features. Figure 6 shows all the relevant features used in the predictive model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbpRM3TQG0dzKwh4UsRRVA.png" /><figcaption>Figure 6: Ranking of most important features.</figcaption></figure><p>Under Feature Importance in Figure 6, the top three features are highly related to gender. The top three features indicate that if you had the right title, a woman or a child, and the right surname, your chance of surviving would have increased dramatically. Furthermore, if you were in the right cabin level, part of a family, and in first-class, survival also increased. In the end, it came down to having the right calibration in each important feature as well as a little bit of luck to survive the sinking ship and see another day on planet earth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e8a7b80d02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand & Implement Logistic Regression in Python]]></title>
            <link>https://medium.com/data-science/understand-implement-logistic-regression-in-python-c1e1a329f460?source=rss-607ad4750966------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1e1a329f460</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[cross-entropy]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[maximum-likelihood]]></category>
            <category><![CDATA[cost-function]]></category>
            <dc:creator><![CDATA[Do Lee]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 00:52:11 GMT</pubDate>
            <atom:updated>2021-09-03T01:58:01.571Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sigmoid Function, Linear Regression, and Parameter Estimation (Log-Likelihood &amp; Cross-Entropy Loss)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ag1WGm58e7O5cGIe" /><figcaption>Photo by <a href="https://unsplash.com/@mboulden?utm_source=medium&amp;utm_medium=referral">Meg Boulden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Objective</h3><p>The primary objective of this article is to understand how binary <a href="https://en.wikipedia.org/wiki/Logistic_regression">logistic regression</a> works.</p><ul><li>I’ll go over the fundamental math concepts and functions involved in understanding logistic regression at a high level.</li><li>In the process, I’ll go over two well-known gradient approaches (ascent/descent) to estimate the 𝜃 parameters using log-likelihood and cross-entropy loss functions.</li><li>I’ll use Kaggle’s Titanic dataset to create a logistic regression model from scratch to predict passenger survival. The train.csv and test.csv files are available on <a href="https://www.kaggle.com/c/titanic/data">Kaggle’s Titanic data page</a>. To expedite the model build, I’ll only use three features, <strong>age</strong> (continuous), <strong>pclass</strong> (1st Class = 1, 2nd Class = 2, and 3rd Class = 3), and <strong>sex</strong> (female = 1 and male = 0).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5Hy2K45v4s8O3Pago1yhg.png" /><figcaption>Figure 0: Image by <a href="https://dolee.medium.com/">Author</a>; Data Source: <a href="https://www.kaggle.com/c/titanic/data">Kaggle’s Titanic Data</a></figcaption></figure><h3>Table of Contents</h3><ul><li>Algorithm Synopsis</li><li>Math Concepts &amp; Functions</li><li>Code in Action</li><li>Final Thoughts</li></ul><h3>Algorithm Synopsis</h3><p>Logistic regression, a classification algorithm, outputs predicted probabilities for a given set of instances with features paired with optimized 𝜃 parameters plus a bias term. The parameters are also known as weights or coefficients. The probabilities are turned into target classes (e.g., 0 or 1) that predict, for example, success (“1”) or failure (“0”). Although I’ll be closely examining a binary logistic regression model, logistic regression can also be used to make multiclass predictions.</p><p><strong>How do we take linearly combined input features and parameters and make binary predictions?</strong> The answer is natural-logarithm (log base e). More specifically, log-odds. The linearly combined input features and parameters are summed to generate a value in the form of log-odds. Then, the log-odds value is plugged into the sigmoid function and generates a probability. At its core, like many other machine learning problems, it’s an optimization problem. The best parameters are estimated using gradient ascent (e.g., maximizing log-likelihood) or descent (e.g., minimizing cross-entropy loss), where the chosen <a href="https://www.courses.psu.edu/for/for466w_mem14/Ch11/HTML/Sec1/ch11sec1_ObjFn.htm">objective (e.g., cost, loss, etc.) function</a> determines the gradient approach.</p><h3>Math Concepts &amp; Functions</h3><p>For everything to be more straightforward, we have to dive deeper into the math. In logistic regression, the sigmoid function plays a key role because it outputs a value between 0 and 1 — perfect for probabilities. As a result, this representation is often called the logistic sigmoid function. Keep in mind that there are other <a href="https://deepai.org/machine-learning-glossary-and-terms/sigmoid-function">sigmoid functions</a> in the wild with varying bounded ranges. And because the response is binary (e.g., True vs. False, Yes vs. No, Survived vs. Not Survived), the response variable will have a Bernoulli distribution. Furthermore, each response outcome is determined by the predicted probability of success, as shown in Figure 5.</p><blockquote><strong>About Math Notations:</strong> The lowercase “i<em>” </em>will represent the row position in the dataset while the lowercase “j<em>” </em>will represent the feature or column position in the dataset. You will also come across lowercase bolded non-italic “<strong><em>x</em></strong>”. This represents a feature vector. More specifically, when “i” is accompanied by “<strong><em>x</em></strong>” (<strong><em>x</em></strong>i), as shown in Figures 5, 6, 7, and 9, this represents a vector (an instance/a single row) with all the feature values.</blockquote><blockquote>When you see “i” and “j” with lowercase italic “x” (xi,j) in Figures 8 and 10, the value is a representation of a jth feature in an ith (a single feature vector) instance. The number of features (columns) in the dataset will be represented as “n” while number of instances (rows) will be represented by the “m” variable.</blockquote><h4>Sigmoid Function</h4><p>In Figure 1, the first equation is the sigmoid function, which creates the S curve we often see with logistic regression. The output equals the conditional probability of <em>y</em> = 1 given <strong>x</strong>, which is parameterized by 𝜃. In this case, the <strong>x</strong> is a single instance (an observation in the training set) represented as a feature vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29l5zQ4dgRxS822_nksnuA.png" /><figcaption>Figure 1: Sigmoid function [sigma(z)] and [1 — sigma(z)]; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p>Each feature in the vector will have a corresponding 𝜃 parameter estimated using an optimization algorithm. I’ll talk more about this later in the gradient ascent/descent section. It’s also important to note that by solving for <em>p </em>in log(odds) = log(<em>p</em>/(1-<em>p</em>)) we get the sigmoid function with <em>z = </em>log(odds).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmuotVGWJCMR54f0Xh04GQ.png" /><figcaption>Figure 2: Sigmoid Curve; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><pre><br>proba1, proba0 = [], []<br>feature_example = [i for i in range(-10, 11)]</pre><pre>for instance in feature_example:<br>    p1 = 1/(1 + np.exp(-instance)) # sigmoid function<br>    p0 = 1 — p1<br>    proba1.append(p1)<br>    proba0.append(p0)</pre><pre>plt.figure(figsize=(12,6))<br>plt.plot(feature_example, proba1, marker=’.’, label=’predict proba “1”’)<br>plt.plot(feature_example, proba0, marker=’.’, linestyle=’dashed’, label=’predict proba “0”’)<br>plt.title(‘Sigmoid Curve’)<br>plt.xlabel(‘feature_example (in log-odds)’)<br>plt.ylabel(‘probability’)<br>plt.legend(prop={‘size’: 12});</pre><h4>Odds and Log-Odds</h4><p>The estimated y value (y-hat) using the linear regression function represents log-odds. The process of wrapping log around odds or <a href="https://stats.idre.ucla.edu/other/mult-pkg/faq/general/faq-how-do-i-interpret-odds-ratios-in-logistic-regression/">odds ratios</a> is called the <strong>logit transformation</strong>. The key takeaway is that log-odds are unbounded (-infinity to +infinity). However, we need a value to fall between 0 and 1 to predict probability. So, in essence, log-odds is the bridge that closes the gap between the linear and the probability form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DLdPzg7mv3eTXdzBq767g.png" /><figcaption>Figure 3: Linear regression function and y-estimate as log-odds; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p><strong>What is log-odds?</strong> We first need to know the definition of odds — the probability of success divided by failure, P(success)/P(failure). For example, the probability of tails and heads is both 0.5 for a fair coin. Therefore, the odds are 0.5/0.5, and this means that odds of getting tails is one. If we were to use a biased coin in favor of tails, where the probability of tails is now 0.7, then the odds of getting tails is 2.33 (0.7/0.3). As shown in Figure 3, the odds are equal to p/(1-p). The next step is to transform odds into log-odds.</p><p>An essential takeaway of transforming probabilities to odds and odds to log-odds is that the relationships are monotonic. When probability increase, the odds increase, and vice versa. When odds increase, so do log-odds and vice versa. In Figure 4, I created two plots using the Titanic training set and Scikit-Learn’s logistic regression function to illustrate this point. We can clearly see the monotonic relationships between probability, odds, and log-odds.</p><p><strong>Why is this important?</strong> The higher the log-odds value, the higher the probability. In Figure 2, we can see this pretty clearly. Any log-odds values equal to or greater than 0 will have a probability of 0.5 or higher. And this is due to the monotonic relationships we observed in Figure 4. This will also come in handy when we are interpreting the estimated parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4t7IOaHu8QJWdm6XVNDa5A.png" /><figcaption>Figure 4: Probability vs. Odds &amp; Odds vs. Log Odds; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><pre>import pandas as pd<br>import numpy as np<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.pipeline import make_pipeline<br>import matplotlib.pyplot as plt<br>plt.style.use(‘ggplot’)<br>%matplotlib inline</pre><pre>logreg = LogisticRegression(random_state=0)<br>model_pipe = make_pipeline(StandardScaler(), logreg)<br>X = train[[‘age’,’pclass’,’sex’]]<br>y = train[‘survived’]<br>model_pipe.fit(X, y)<br>model_pipe.predict_proba(X)</pre><pre>y_pred_proba_1 = model_pipe.predict_proba(X)[:,1]<br>y_pred_proba_0 = model_pipe.predict_proba(X)[:,0]<br>odds = y_pred_proba_1 / y_neg_pred_proba_0<br>log_odds = np.log(odds)</pre><pre>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16,6))<br>ax1.set_title(‘Probability vs. Odds’)<br>ax1.set(xlabel=’Probability’, ylabel=’Odds’)<br>ax1.scatter(y_pos_pred_proba, odds)<br>ax2.set_title(‘Odds vs. Log Odds’)<br>ax2.set(xlabel=’Odds’, ylabel=’Log Odds’)<br>ax2.scatter(odds, log_odds);</pre><h4>Sigmoid Combined Probability, Likelihood, and Log-likelihood</h4><p>We covered a lot of ground, and we are now at the last mile of understanding logistic regression at a high level. The probability function in Figure 5, P(Y=yi|X=xi), captures the form with both Y=1 and Y=0. Based on Y (0 or 1), one of the terms in the dot product becomes 1 and drops off. This combined form becomes crucial in understanding likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LMD2Xb-HsiN00AnAA6pFw.png" /><figcaption>Figure 5: Probability function as a combined form with Y=0 and Y=1 terms; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p><strong>Let’s walk through how we get </strong><a href="https://en.wikipedia.org/wiki/Likelihood_function"><strong>likelihood</strong></a><strong>, L(𝜃).</strong> For every instance in the training set, we calculate the log-odds using <strong>randomly estimated parameters (𝜃’s) </strong>and predict the probability using the sigmoid function corresponding to a specific binary target variable (0 or 1). The multiplication of these probabilities would give us the probability of all instances and the <a href="https://stats.stackexchange.com/questions/2641/what-is-the-difference-between-likelihood-and-probability">likelihood</a>, as shown in Figure 6. It is important to note that likelihood is represented as the likelihood of 𝜃 while probability is designated as the probability of Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bSwPlxsYIMMBotSRldCIg.png" /><figcaption>Figure 6: Likelihood function; Source Reading: <a href="https://stanford.edu/~cpiech/bio/index.html">Chris Piech</a>, CS109 @ Stanford University; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p>As a result, by maximizing likelihood, we converge to the optimal parameters. In other words, maximizing the likelihood to estimate the best parameters, we directly maximize the probability of Y. This is called the Maximum Likelihood Estimation (MLE). Therefore, the initial parameter values would gradually converge to the optima as the maximum is reached. The convergence is driven by the optimization algorithm — gradient ascent/descent.</p><p><strong>How does log-likelihood fit into the picture?</strong> By taking the log of the likelihood function, it becomes a summation problem versus a multiplication problem. We know that log(XY) = log(X) + log(Y) and log(X^b) = b * log(X). Therefore, we can easily transform likelihood, L(𝜃), to log-likelihood, LL(𝜃), as shown in Figure 7. Because likelihood to log-likelihood is a monotonic transformation, maximizing log-likelihood will also produce the best parameters — this is called the Maximum Log-Likelihood. Again, keep in mind that it is the log-likelihood of 𝜃, which we are optimizing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhLZTyQuxP9CAv1cfI1N0g.png" /><figcaption>Figure 7: Log-likelihood function; Source Reading: <a href="https://stanford.edu/~cpiech/bio/index.html">Chris Piech</a>, CS109 @ Stanford University; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p><strong>How do we reach the maximum using log-likelihood? </strong>We take the partial derivative of the log-likelihood function with respect to each 𝜃 parameter. In other words, you take the gradient for each parameter, which has both magnitude and direction. For example, in the Titanic training set, we have three features plus a bias term with x0 equal to 1 for all instances. The partial derivative in Figure 8 represents a single instance (<em>i) </em>in the training set and a single 𝜃 parameter (<em>j)</em>. The <em>x (i, j) </em>represents a single feature in an instance paired with its corresponding 𝜃 (<em>i, j</em>)parameter. As a result, for a single instance, a total of four partial derivatives — bias term, pclass, sex, and age — are created. These make up the gradient vector.</p><p>The η is the learning rate determining how big a step the gradient ascent algorithm will take for each iteration. We don’t want the learning rate to be too low, which will take a long time to converge, and we don’t want the learning rate to be too high, which can overshoot and jump around. The learning rate is also a hyperparameter that can be optimized, but I’ll use a fixed learning rate of 0.1 for the Titanic exercise.</p><p>Once you have the gradient vector and the learning rate, two entities are multiplied and added to the current parameters to be updated, as shown in the second equation in Figure 8. Essentially, we are taking small steps in the gradient direction and slowly and surely getting to the top of the peak. This updating step repeats until the parameters converge to their optima — this is the <strong>gradient ascent algorithm</strong> at work. Because the log-likelihood function is concave, eventually, the small uphill steps will reach the global maximum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fz3EvHHDhoFBNracwpGU4A.png" /><figcaption>Figure 8: Partial derivative for each 𝜃 parameter and gradient ascent algorithm; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p><strong>What about minimizing the cost function?</strong> We often hear that we need to minimize the cost or the loss function. It is also called an objective function because we are trying to either maximize or minimize some numeric value. In the context of a cost or loss function, the goal is converging to the global minimum. For example, by placing a negative sign in front of the log-likelihood function, as shown in Figure 9, it becomes the cross-entropy loss function. The goal is to minimize this negative function using the <a href="https://www.khanacademy.org/math/multivariable-calculus/applications-of-multivariable-derivatives/optimizing-multivariable-functions/a/what-is-gradient-descent#:~:text=Gradient%20descent%20is%20an%20algorithm,like%20we&#39;ve%20seen%20before."><strong>gradient descent algorithm</strong></a><strong> </strong>(second equation in Figure 10). This process is the same as maximizing the log-likelihood, except we minimize it by descending to the minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXnTOP78wtCp_odxrEVZrA.png" /><figcaption>Figure 9: Cross-entropy loss function or negative log-likelihood (NLL) function; Source Reading: <a href="https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020">Machine Learning: A Probabilistic Perspective by Kevin P. Murphy</a> — Chapter 8; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p>Once the partial derivative (Figure 10) is derived for each 𝜃 parameter, the form is the same as in Figure 8. The big difference is the subtraction term, where it is re-ordered with sigmoid predicted probability minus actual <em>y </em>(0 or 1). This term is then multiplied by the <em>x (i, j) </em>feature. The process is the same as the process described in the gradient ascent section above. Thus, we will end up with four partial derivatives for every instance in the training set. And using the<strong> </strong>gradient descent algorithm, we update the parameters until they converge to their optima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWZOtNOVqthnR0dayocOFw.png" /><figcaption>Figure 10: Partial derivative for each theta parameter and gradient descent algorithm; Source Reading: <a href="https://web.stanford.edu/~jurafsky/slp3/">Speech and Language Process by Dan Jurafsky and James H. Martin (3rd Edition Draft)</a> — Chapter 5; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><p>Thankfully, the cross-entropy loss function is convex and naturally has one global minimum. Eventually, with enough small steps in the direction of the gradient, which is the steepest descent, it will end up at the bottom of the hill.</p><h3>Code in Action</h3><p>Now that we have reviewed the math involved, it is only fitting to demonstrate the power of logistic regression and gradient algorithms using code. Let’s start with our data. We have the train and test sets from <a href="https://www.kaggle.com/c/titanic/data">Kaggle’s Titanic Challenge</a>. As mentioned earlier, I’m only using three features — age, pclass, and sex — to predict passenger survival.</p><p><strong>First, we need to scale the features</strong>, which will help with the convergence process. I’ll be using the standardization method to scale the numeric features. In standardization, we take the mean for each numeric feature and subtract the mean from each value. This term is then divided by the standard deviation of the feature. Next, we’ll add a column with all ones to represent x0. This is for the bias term.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ed6774b478fac9546ac5f0159b21dc/href">https://medium.com/media/b8ed6774b478fac9546ac5f0159b21dc/href</a></iframe><p>With the above code, we have prepared the train input dataset. We now know that log-odds is the output of the linear regression function, and this output is the input in the sigmoid function. The only missing pieces are the 𝜃 parameters. Because we’ll be using gradient ascent and descent to estimate these parameters, we <strong>pick four arbitrary values</strong> as our starting point. I’ll be using four zeroes as the initial values. We also need to define the sigmoid function in code because this will generate our probabilities.</p><pre># sigmoid function where z = log-odds<br>def sigmoid(z):<br>    predict_proba = 1 / (1 + np.exp(-z))<br>    return predict_proba</pre><p>We have all the pieces in place. <strong>Next, we’ll translate the log-likelihood function, cross-entropy loss function, and gradients into code.</strong> We also need to determine how many times we want to go through the training set. We need to define the number of epochs (designated as n_epoch in code below, which is a hyperparameter helping with the learning process). <strong>What is an epoch?</strong> In the context of gradient ascent/descent algorithm, an epoch is a single iteration, where it determines how many training instances will pass through the gradient algorithm to update the 𝜃 parameters (shown in Figures 8 and 10).</p><p>Therefore, we commonly come across <strong>three gradient ascent/descent algorithms</strong>: batch, stochastic, and mini-batch. For the Titanic exercise, I’ll be using the batch approach. This means, for every epoch, the entire training set will pass through the gradient algorithm to update the 𝜃 parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/326127032af2e1a1e4178594cacd6011/href">https://medium.com/media/326127032af2e1a1e4178594cacd6011/href</a></iframe><p>Here you have it! By <strong>maximizing the log-likelihood through gradient ascent algorithm</strong>, we have derived the best 𝜃 parameters for the Titanic training set to predict passenger survival.</p><ul><li>𝜃0: -0.89362715 (bias term)</li><li>𝜃1: -1.41685703 (pclass)</li><li>𝜃2: 1.24119596 (sex)</li><li>𝜃3: -0.60707722 (age)</li></ul><p>Let’s visualize the maximizing process. In Figure 11, we can see that we reached the maximum after the first epoch and continues to stay at this level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTGA9E3CUyv7BZjuOdXY3A.png" /><figcaption>Figure 11: Maximizing log-likelihood function per epoch iteration; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><pre>x_axis = [i for i in range(1, 11)]<br>plt.figure(figsize=(14,6))<br>plt.title(‘Maximizing Log-Likelihood’)<br>plt.xticks(x_axis)<br>plt.xlabel(‘epoch iteration’)<br>plt.ylabel(‘log-likelihood’)<br>plt.plot(x_axis, log_likelihood_vals, marker=’o’)<br>plt.tight_layout()</pre><p>We can also visualize the 𝜃 parameters converging for every epoch iteration. As we saw in Figure 11, log-likelihood reached the maximum after the first epoch; we should see the same for the parameters. In Figure 12, we see the parameters converging to their optimum levels after the first epoch, and the optimum levels are maintained as the code iterates through the remaining epochs. Iterating through the training set once was enough to reach the optimal 𝜃 parameters. Let’s examine what is going on during each epoch interval.</p><p>The plots on the right side in Figure 12 show 𝜃 parameter values quickly moving towards their optima. As it continues to iterate through the training instances in each epoch, the parameter values oscillate up and down (epoch intervals are denoted as black dashed vertical lines). At the end of each epoch, we end with the optimal parameter values and these values are maintained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXDEmunmvMaw4r_doCUj2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fikG8lv11Svgp_-864VLkg.png" /><figcaption>Figure 12: 𝜃 parameter convergence per epoch (left) and per instance (right); Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c8c7d4cb610cc6d4fe2b9594de60ee/href">https://medium.com/media/81c8c7d4cb610cc6d4fe2b9594de60ee/href</a></iframe><p>It’s time to make predictions using this model and generate an accuracy score to measure model performance. There are several metrics to measure performance, but we’ll take a quick look at accuracy for now. The code below generated an accuracy score of 79.8%.</p><pre>from sklearn.metrics import accuracy_score</pre><pre>def make_predictions(X, thetas):<br>    X = X.copy()<br>    predictions = []<br>    for x_row in X:<br>        log_odds = sum(thetas * x_row[:4])<br>        pred_proba = sigmoid(log_odds)<br>        <br>        # if probability &gt;= 0.5, predicted class is 1<br>        predictions.append(1 if pred_proba &gt;= 0.5 else 0)<br>    return predictions</pre><pre>y_train = X_train[:, -1]<br>y_predict = make_predictions(X_train[:, :4], thetas)<br>accuracy_score(y_train, y_predict)</pre><p><strong>What about cross-entropy loss function?</strong> The results from minimizing the cross-entropy loss function will be the same as above. There are only a few lines of code changes and then the code is ready to go (see ‘# changed’ in code below). Here’s the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6814429f744fae112f7f534a93594073/href">https://medium.com/media/6814429f744fae112f7f534a93594073/href</a></iframe><p>Let’s take a look at the cross-entropy loss function being minimized using gradient descent. We reached the minimum after the first epoch, as we observed with maximum log-likelihood. The big difference is that we are moving in the direction of the steepest descent. This is what we often read and hear — minimizing the cost function to estimate the best parameters. We are now equipped with all the components to build a binary logistic regression model from scratch. I hope this article helped you as much as it has helped me develop a deeper understanding of logistic regression and gradient algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRlT-38kRXy436Q7d_67SQ.png" /><figcaption>Figure 13: Minimizing cross-entropy loss function; Image by <a href="https://dolee.medium.com/">Author</a></figcaption></figure><pre>x_axis = [i for i in range(1, 11)]<br>plt.figure(figsize=(14,6))<br>plt.title(‘Minimizing Cross-Entropy Loss’)<br>plt.xticks(x_axis)<br>plt.xlabel(‘epoch iteration’)<br>plt.ylabel(‘cross-entropy loss’)<br>plt.plot(x_axis, ce_loss_vals, marker=’o’)<br>plt.tight_layout()</pre><h3>Final Thoughts</h3><p>In this article, my goal was to provide a solid introductory overview of the binary logistic regression model and two approaches in estimating the best 𝜃 parameters. As we saw in the Titanic example, the main obstacle was estimating the optimal 𝜃 parameters to fit the model and using the estimates to predict passenger survival. We examined the (maximum) log-likelihood function using the gradient ascent algorithm. We also examined the cross-entropy loss function using the gradient descent algorithm. Of course, you can apply other cost functions to this problem, but we covered enough ground to get a taste of what we are trying to achieve with gradient ascent/descent.</p><p><strong>Where do we go from here?</strong> There are several areas that we can explore in terms of improving the model. We can start with the learning rate. The <a href="https://en.wikipedia.org/wiki/Learning_rate">learning rate</a> is a hyperparameter and can be tuned. In many cases, a learning rate schedule is introduced to decrease the step size as the gradient ascent/descent algorithm progresses forward.</p><p>If the dataset is massive, the batch approach might not be ideal. Understanding the mechanics of <a href="https://machinelearningmastery.com/gentle-introduction-mini-batch-gradient-descent-configure-batch-size/">stochastic and mini-batch gradient descent</a> algorithms will be much more helpful. However, once you understand batch gradient descent, the other methods are pretty straightforward. There are also different <a href="https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html">feature scaling</a> techniques in the wild beyond the standardization method I used in this article.</p><p>If you encounter any issues or have feedback for me, feel free to leave a comment. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1e1a329f460" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understand-implement-logistic-regression-in-python-c1e1a329f460">Understand &amp; Implement Logistic Regression in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Window Functions: The Intuitive Guide]]></title>
            <link>https://medium.com/data-science/sql-window-functions-the-intuitive-guide-5b56d7f437cb?source=rss-607ad4750966------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b56d7f437cb</guid>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Do Lee]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 18:41:40 GMT</pubDate>
            <atom:updated>2021-06-29T08:35:20.171Z</atom:updated>
            <content:encoded><![CDATA[<h4>Intuitively learn different components of window functions using Postgres and implement them into your data workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IujGM1qaTQG3pM2s" /><figcaption>Photo by <a href="https://unsplash.com/@pablofierro?utm_source=medium&amp;utm_medium=referral">Pablo Fierro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>The main goal is to understand the fundamental concepts of window functions and apply them to your SQL workflow. Window functions are nothing more than FOPO (Function Over PartitionBy OrderBy). Here’s a quick outline of what will be covered in this article.</p><ul><li>The GROUP BY</li><li>The Window Function — 4 Major Components (The FOPO)</li><li>The func() OVER ()</li><li>The PARTITION BY</li><li>The ORDER BY</li><li>The PARTITION BY &amp; ORDER BY</li><li>Summary</li><li>Appendix</li></ul><h3>The GROUP BY</h3><p>If you have a good understanding of the GROUP BY clause, you already have a head start understanding window functions. In a nutshell, the GROUP BY clause condenses a table into fewer rows or outputs unique rows. When grouping by a column, the SQL query outputs a single row for every distinct value found under that column. In grouping multiple columns, the output will consist of unique combinations of the specified columns with or without some aggregate functions. Here’s an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQ_Tfx7aqHhUO8zGPAN-HA.png" /><figcaption>The 1 in GROUP BY 1 represents the position of the grouping column under the SELECT. Columns listed under the SELECT are like an array with starting index position 1.</figcaption></figure><p>In this product_orders table, every order_id is attached to all product items (product_name) purchased by a customer.</p><ul><li>First, the order_id is designated as the GROUP BY column.</li><li>Second, the amounts corresponding to the order_id are summed into one value (total_amount) using the SUM aggregate function.</li></ul><p>Now, let’s take a deeper look into the mechanics of window functions.</p><h3>The Window Function — 4 Major Components (The FOPO)</h3><ul><li>First, the function component determines the treatment of the data. For example, we can rank based on a column (e.g., DENSE_RANK) or create equal-sized bins (e.g., NTILE). Check out the available window functions in Postgres <a href="https://www.postgresql.org/docs/9.3/functions-window.html">here</a>. Aggregate functions (e.g., SUM, COUNT, AVG, etc.) can be used as window functions as well — listed <a href="https://www.postgresql.org/docs/9.3/functions-aggregate.html">here</a>.</li><li>Second, the OVER clause is the glue that holds everything together. The functions from above are invoked or enabled with the use of the OVER clause to create window functions.</li><li>Third, similar to GROUP BY, the PARTITION BY is like a subgroup-by clause. Rather than collapsing the dataset, the PARTITION BY creates subgroups/blocks/partitions based on the specified column or columns.</li><li>Lastly, the ORDER BY clause orders the data, again, based on the specified column or columns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8NGyKmTZoklpSuqJbbSIA.png" /></figure><p>Based on the level of treatment needed to transform the data not all components need to be used, except the OVER clause. (<strong>Remember:</strong> The OVER clause invokes the window functions and enables aggregate functions to become window functions.) Here are the use cases.</p><ul><li>func() OVER ()</li><li>func(&lt;column, integer value&gt;) OVER ()</li><li>func() OVER (PARTITION BY &lt;column(s)&gt;)</li><li>func(&lt;column, integer value&gt;) OVER (PARTITION BY &lt;column(s)&gt;)</li><li>func() OVER (PARTITION BY &lt;column(s)&gt; ORDER BY &lt;column(s)&gt;)</li><li>func(&lt;column, integer value&gt;) OVER (PARTITION BY &lt;column(s)&gt; ORDER BY &lt;column(s)&gt;)</li></ul><h3>The func() OVER ()</h3><p>The OVER () approach without defining a PARTITION BY and/or ORDER BY applies the function to the entire dataset. This approach pairs well with aggregate functions. The integrity of the table or dataset is maintained while a function is applied to calculate a value using all the rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*DQrgBo5YmH02O3OmygGVeA.png" /><figcaption>In the orders table, every row is a unique order_id (primary key). I added a few more orders to this table for demonstration purposes.</figcaption></figure><p>In this example, three aggregate functions are paired with the OVER clause to create three window functions represented by total_amount, total_count, and total_mean. The total_amount, for example, sums all the values under the amount column, and the new total appears in every row. The same logic applies to total_count and total_mean. This setup helps calculate % of total and creating ratios against a total quantity or a statistic like the mean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47844e495dcfbc6da132f28b367186e3/href">https://medium.com/media/47844e495dcfbc6da132f28b367186e3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrsZ83pepdvdtHu78uFwDA.png" /></figure><p>As a result, values from the window functions are useful in creating standardized metrics for easy comparison across the dataset. The first grey highlighted block shows the aggregate values in the provided example below, while the second block contains metrics describing the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45cd3e2cc70f561bf1731cb6b107c962/href">https://medium.com/media/45cd3e2cc70f561bf1731cb6b107c962/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auPkm-CUcPZ_m73jx8SFhQ.png" /></figure><h3>The PARTITION BY</h3><p>As I mentioned earlier, the PARTITION BY is similar to GROUP BY. The best way to think of PARTITION BY is subgrouping (a group within a group). Like the GROUP BY, start by defining the PARTITION BY column or columns. Once the subgroups are defined, the OVER clause will invoke or enable the function to execute its logic onto each subgroup. Unlike the GROUP BY, the PARTITION BY clause does not condense the table; instead, it maintains the table&#39;s integrity while adding the output as a column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bf9b2bca39028abe79bd0e29c3cb044/href">https://medium.com/media/9bf9b2bca39028abe79bd0e29c3cb044/href</a></iframe><p>For instance, using the product_orders table, the PARTITION BY column is the order_id. Moreover, the number of subgroups is defined by the unique number of order_id’s. In this case, that number is three.</p><ul><li>NTILE: The NTILE(3) equals the number of bins, and PARTITION BY determines the subgroups (or partitions), in which every subgroup will be divided into three bins.</li><li>FIRST_VALUE: The function outputs the first value or row in the defined subgroup.</li><li>COUNT: Counts the number of rows in each defined subgroup.</li><li>SUM: Sums the values (e.g., amount) in each subgroup.</li><li>AVG: Calculates the mean of each defined subgroup.</li></ul><p>In the output, the highlighted grey blocks below represent the defined subgroups by the PARTITION BY clause and the creation of new columns by the window functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOCx7qE6-nP3TA3P962HSA.png" /></figure><h3>The ORDER BY</h3><p>The ORDER BY clause is used when ranking or ordering the data. It can be a standalone clause within the window function or paired with the PARTITION BY clause. At times, just using the ORDER BY clause will be more appropriate, which allows the ranking or ordering of the entire dataset. Here’s an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc8e6c83a86eaeacedb61e4a501d43f5/href">https://medium.com/media/fc8e6c83a86eaeacedb61e4a501d43f5/href</a></iframe><p>Using the ORDER BY clause within the ranking functions generates an ordered view based on the values found in the num_product_items and amount column. The difference between ranking functions is shown in the orange highlighted area below. Just a reminder that the ORDER BY clause is set to order by ascending (ASC). For descending, it must be denoted with DESC (e.g., ORDER BY amount DESC).</p><ul><li>ROW_NUMBER(): The function ranks sequentially either by ascending or descending regardless of duplicate values in the column.</li><li>RANK(): The function ranks sequentially either by ascending or descending, but there will be gaps when there are duplicate values. For example, under num_product_items, there are two occurrences of number 1; thus, the function ranks both as 1 (under rank_by_items). Next, there are two occurrences of 2 under num_product_items, and the function ranks these as 3. The function skipped rank 2 because the second occurrence of 1 already captured the 2nd rank position. Furthermore, because the second occurrence of 3 has already taken the 4th rank position, the next rank starts with 5.</li><li>DENSE_RANK(): This function is like the RANK() function but does not skip or create gaps. Unlike ROW_NUMBER(), where every row is designated with a unique rank regardless of duplicate values, DENSE_RANK() will apply the same rank for duplicate values without the gaps.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgrZuz7ZlR96oIDumigkoA.png" /></figure><h3>The PARTITION BY &amp; ORDER BY</h3><p>After examining the mechanics of PARTITION BY and ORDER BY separately, pairing these two components is the next step. The PARTITION BY creates subgroups (or partitions) based on the chosen column or set of columns. The ORDER BY organizes the data in ascending or descending order. I’ll be illustrating the pairing of these components using the product_orders table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*ZlQojKUXPjnLLn8cG_VP1Q.png" /><figcaption>SELECT * FROM product_orders; This table consists of three order_ids with a list of purchased product items.</figcaption></figure><p>In this example, I’m using nine window functions to demonstrate PARTITION BY and ORDER BY pairing. At this stage, if you have a solid understanding of each component, this should be straightforward. The description of each window function for Postgres is available <a href="https://www.postgresql.org/docs/9.3/functions-window.html">here</a>.</p><p>In this SQL query, all the window functions are using order_id in the PARTITION BY clause. The number of unique order_id’s equals the number of subgroups, and the ORDER BY column orders the data for each subgroup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbe437006727d455bcdc3d332962ac71/href">https://medium.com/media/bbe437006727d455bcdc3d332962ac71/href</a></iframe><p>One item not discussed earlier is the use of the “RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING” clause in FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE() functions. This clause is needed to define the first and last row of the subgroup. There is nothing special about this clause, except it must be included to set the frame of the window function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*as-sPTNC1TPSGyaM3MWiKA.png" /></figure><h3>Summary</h3><p>The key takeaway is that window functions are an amalgamation of existing SQL concepts bundled together to create a different way to slice and dice the data. There are clear benefits of using window functions and allows you to quickly output transformed data versus taking the time to create your own custom functions.</p><p>The way that I like to think of window functions is FOPO (Function Over PartitionBy OrderBy).</p><ul><li>First, choose a function that is most applicable to your use case.</li><li>Second, remember that the OVER clause invokes the window function (e.g., DENSE_RANK(), LAG(), etc.) and enables the aggregate function to become a window function.</li><li>Third, the PARTITION BY clause defines the subgroups (or partitions) — a group within a group — in which the chosen function runs through each partition.</li><li>Lastly, the ORDER BY clause orders the data in each partition based on a column or set of columns.</li></ul><p>In the Appendix, I shared the SQL statements used to create my tables and the data. The best way to learn is to practice, so feel free to dive deeper on your own. You already have the basics under your belt, and next is just putting together the pieces based on your use case. Thanks for reading and have fun querying!</p><p><a href="https://www.postgresql.org/docs/9.3/functions-window.html">PostgreSQL: Documentation: 9.3: Window Functions</a></p><h3>Appendix</h3><p>If you already have Postgres installed on your computer, please run these CREATE TABLE and INSERT statements and run the SQL queries that I have shared earlier. For downloads, go to this <a href="https://www.postgresql.org/download/">page</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdbff931cfc4537cd564dc3b5ef7c203/href">https://medium.com/media/cdbff931cfc4537cd564dc3b5ef7c203/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b56d7f437cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sql-window-functions-the-intuitive-guide-5b56d7f437cb">SQL Window Functions: The Intuitive Guide</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kaggle Titanic Competition: Model Building & Tuning in Python]]></title>
            <link>https://medium.com/data-science/kaggle-titanic-competition-model-building-tuning-in-python-12f4f74436b5?source=rss-607ad4750966------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f4f74436b5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[titanic-dataset]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[gridsearchcv]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[Do Lee]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 05:55:17 GMT</pubDate>
            <atom:updated>2022-01-26T18:38:54.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>Best Fitting Model, Feature &amp; Permutation Importance, and Hyperparameter Tuning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g7iKKjLM46rnjqf1" /><figcaption>Photo by <a href="https://unsplash.com/@iampaulbiondi?utm_source=medium&amp;utm_medium=referral">Paul Biondi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background</h3><p>I conducted my initial exploratory analysis and feature engineering in SQL. In my previous article, I demonstrated how powerful SQL can be in exploring data in relational databases. For more context, it might be worthwhile checking it out before reading this article, although it’s not required. You can find the article <a href="https://medium.com/@dolee_12121/kaggle-titanic-competition-in-sql-78ae3cd551ce">here</a>!</p><p><a href="https://towardsdatascience.com/kaggle-titanic-competition-in-sql-78ae3cd551ce">Kaggle Titanic Competition in SQL</a></p><p>I‘ll be using the train/test datasets prepared earlier in the <em>“Kaggle Titanic Competition in SQL”</em> article to predict passenger survival.</p><h3>Overview</h3><ul><li>Import Libraries</li><li>Prepare Train and Test Data Frames</li><li>Correlation Coefficient Matrix</li><li>Create Helper Function: Output Model Stats</li><li>Multiple Fitted Models and Best Fit Model</li><li>Create Helper Function: Output RF Feature Importance Ranking</li><li>Feature Selection with Random Forest Feature Importance, Permutation Importance, and Hierarchical Clustering</li><li>RandomizedSearchCV: Random Forest Classifier</li><li>GridSearchCV: Random Forest Classifier</li><li>Conclusion: Latest Results &amp; Final Thoughts</li></ul><h3>Import Libraries</h3><pre>import numpy as np <br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.linear_model import Perceptron<br>from sklearn.linear_model import SGDClassifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.svm import SVC, LinearSVC<br>from sklearn.naive_bayes import GaussianNB</pre><pre>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.model_selection import RandomizedSearchCV, GridSearchCV<br>from sklearn.model_selection import cross_val_score<br>from sklearn.model_selection import cross_val_predict<br>from sklearn.metrics import confusion_matrix<br>from sklearn.metrics import precision_score, recall_score, roc_auc_score</pre><h3>Prepare Train &amp; Test Data Frames</h3><p>Using Pandas, I imported the CSV files as data frames. The resultset of train_df.info() should look familiar if you read my “<a href="https://medium.com/@dolee_12121/kaggle-titanic-competition-in-sql-78ae3cd551ce"><em>Kaggle Titanic Competition in SQL</em></a>” article. For model training, I started with 15 features, as shown below, excluding Survived and PassengerId.</p><pre>train_df = pd.read_csv(‘file/path/data-train.csv’)<br>test_df = pd.read_csv(‘file/path/data-test.csv’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*eoMgm1oJO_nbonZaqQqJaA.png" /></figure><h3>Correlation Coefficient Matrix</h3><p>As a first step, I created a pairwise correlation matrix using the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html">corr function</a> built into Pandas and Seaborn to visualize the data. It calculates the <em>Pearson</em> <em>correlation coefficients</em> (linear relationships) as the default method. I also used <em>Spearman</em> and <em>Kendall</em> methods, which are both available in pandas.DataFrame.corr.</p><p>All the results looked similar across the board. Relatively speaking, <a href="https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient"><em>Spearman’s</em> <em>rank-order correlation</em></a><em> </em>method, which measures monotonic relationships, might be the best here without diving deep into the concept of correlation and association for different types of features. One caveat is that <em>Spearman</em> will treat nominal features as ordinal features.</p><p>Just as a side note, at this point, all my features have been converted to numerical values composed of binary (dichotomous), ordinal (categorical and ordered), nominal (categorical and not ordered), and continuous features. I wanted to quickly see what features were correlated with each other and the magnitude beyond the obvious ones.</p><p>If I were to dive deeper into the specifics of this exercise, then we also need to talk about associations between categorical features versus correlation among binary and continuous features. In measuring the association between two nominal features, we would have to dive into <a href="https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V"><em>Cramer’s V</em></a> or <em>Pearson’s</em> <em>chi-square test</em>. However, in my opinion, this should be a good enough approach to get an initial baseline read. If I missed anything here, feel free to let me know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*hvx8_0qDa0Ddo9p6CcPl_A.png" /><figcaption>You can find it <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html">here</a>.</figcaption></figure><p>I generated the correlation coefficient heatmap and paid attention to the absolute values in the 0.8 to 1.0 correlation range. These correlation thresholds are arbitrary, and I’ll be looking at various thresholds to determine what works best later on.</p><pre>train_corr = train_df.drop(columns=[&quot;survived&quot;, &quot;passengerid&quot;]).corr(method=&#39;pearson&#39;)<br>plt.figure(figsize=(18, 12))<br>sns.set(font_scale=1.4)<br>sns.heatmap(train_corr, <br>            annot=True, <br>            linecolor=&#39;white&#39;, <br>            linewidth=0.5, <br>            cmap=&#39;magma&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXkHxxAY3DHZTmCvilxlDA.png" /><figcaption>Pearson</figcaption></figure><p>After diving a bit deeper into the numbers using 0.8 as my Pearson correlation threshold, I found these pairs (shown below; output from df_corr) to be highly correlated. Later on, I’ll leverage Spearman with other methods to select important features for my final model.</p><pre># Pearson’s correlation analysis using an arbitrary correlation threshold (absolute values)</pre><pre>corr_threshold = 0.8<br>train_corr_abs = train_corr.abs()</pre><pre>feature_1 = []<br>feature_2 = []<br>corr_coeff = []<br>for col in train_corr_abs:<br>    for idx, val in enumerate(train_corr_abs[col]):<br>        if ((val &gt;= corr_threshold) and (val &lt; 1)):<br>            feature_1.append(col)<br>            feature_2.append(train_corr_abs[col].index[idx])<br>            corr_coeff.append(val)</pre><pre>df_corr = pd.DataFrame({‘feature_1’: feature_1, <br>                        ‘feature_2’: feature_2, <br>                        ‘corr_coeff’: corr_coeff})<br>df_corr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*LbL5m96hezIDtGzmJvV06Q.png" /><figcaption>Results from df_corr; Output contains duplicates.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ZzNuq_9p6E4cwlABH_VhYw.png" /><figcaption>Duplicates are removed, and six highly correlated pairs remain.</figcaption></figure><p>Having identified highly correlated pairs, this analysis will help later when dealing with any regression or linear models. High multicollinearity results in features or coefficient estimates becoming sensitive to small changes in the model. This can also impact <a href="https://scikit-learn.org/stable/auto_examples/inspection/plot_permutation_importance_multicollinear.html">non-linear models</a>.</p><p>The bottom line is that multicollinear features can create an ineffective model, and understanding feature importance can be skewed. I’m not going to focus my energy on pairs with mild multicollinearity. For now, I’ll keep this on the back burner and address this issue directly when the time comes.</p><pre>train_corr = train_df.train_df.drop(columns=[&quot;survived&quot;,       &quot;passengerid&quot;]).corr(method=&#39;spearman&#39;)<br>plt.figure(figsize=(18, 12))<br>sns.set(font_scale=1.4)<br>sns.heatmap(train_corr, <br>            annot=True, <br>            linecolor=’white’, <br>            linewidths=0.5, <br>            cmap=’magma’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*jRkzSsDRc1xdvmBgy-PYVQ.png" /><figcaption>Spearman</figcaption></figure><pre>train_corr = train_df.drop(columns=[&quot;survived&quot;, &quot;passengerid&quot;]).corr(method=&#39;kendall&#39;)<br>plt.figure(figsize=(18, 12))<br>sns.set(font_scale=1.4)<br>sns.heatmap(train_corr, <br>            annot=True, <br>            linecolor=’white’, <br>            linewidths=0.5, <br>            cmap=’magma’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*obER_pO0E8HOSXfq0yObKg.png" /><figcaption>Kendall</figcaption></figure><h3>Create Helper Function: Output Model Stats</h3><p>To start, I trained nine different models by fitting X_train and y_train. To expedite my workflow, I created a function to output model performance and diagnostic metrics to quickly see the numbers and determine what model might work best. These metrics are listed in the function’s docstring.</p><p>Additionally, I defined a pipeline object (line 27 below) containing a scaler and an instance of an estimator. I do not scale the X_train and X_test in few cases when using random forest because it is not necessary to do so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44b6adb78da410d782bb9ce8c882a67/href">https://medium.com/media/d44b6adb78da410d782bb9ce8c882a67/href</a></iframe><h3>Multiple Fitted Models &amp; Best Fit Model</h3><p>The helper function has three parameters. First, it needs a dictionary with the model&#39;s name (string) as the key and model class instantiation as the value. Second, it needs the feature training dataset (X_train) and, lastly, the target class data (y_train). Let’s examine the results!</p><p>Immediately, random forest and decision tree stood out from the rest with an accuracy of 98.54%. I know decision tree tends to overfit, so I wasn’t too surprised. On the other hand, random forest is an ensemble of decision trees designed to minimize overfitting by taking a random subset of features and rows to create a forest of decision trees and voting on the prediction outcomes. This random process generates a better model with higher bias and lower variance.</p><p>At a closer look, the accuracy scores using cross-validation with Kfold of 10 generated more realistic scores of 84.07% for random forest and 81.3% for decision tree. Other models that also stood out were KNN, SVM, logistic regression, and linear SVC, with all respectable scores. A high standard deviation is indicative of a model that might not generalize well with new data, so I paid attention to this as well.</p><p>Let’s take a closer look at precision and recall. In this case, it made sense to maximize both precision and recall, and a high F1 score would be indicative of that. Although there is a precision-recall tradeoff, relatively high precision [TP/(TP+FP)] gives me the accuracy of positive predictions. In contrast, relatively high recall [TP/(TP+FN)] gives me % of actual positives correctly detected by the model. Recall is also known as True Positive Rate (TPR) and sensitivity. Also, I wanted a high AUC under the ROC curve. As a result, I narrowed down my list to four models — random forest, KNN, logistic regression, and linear SVC.</p><p>In the end, I decided on random forest, although other models had slightly better scores. The slight differences seemed negligible in my eyes. The goal is to leverage random forest’s impurity-based feature importance and permutation importance for the feature selection process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYaFUFft06nwW26e_aRuWg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54ccad2900a882cf39452bc1e4566eb7/href">https://medium.com/media/54ccad2900a882cf39452bc1e4566eb7/href</a></iframe><h3>Create Helper Function: Output RF Feature Importance Ranking</h3><p>To quickly output feature importance ranking using random forest, I created a helper function to do this. It outputs a Pandas data frame with feature names with their corresponding feature importance scores in ranked order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/441c2fe83880cf5edaf6c71483c1ee6f/href">https://medium.com/media/441c2fe83880cf5edaf6c71483c1ee6f/href</a></iframe><h3>Feature Selection with RF Feature Importance, Permutation Importance, &amp; Hierarchical Clustering</h3><h4><strong>Iteration 1</strong></h4><p>Going back to the correlation coefficient matrix, there were five pairs flagged as highly correlated or associated with one another. With all the features as defined by X_train and X_test as shown below, I examined the results of RF’s feature and permutation importance. I also used hierarchical clustering and Spearman’s correlation matrix to assist in feature selection.</p><pre>X_train = train_df.drop([“survived”, “passengerid”], axis=1)<br>y_train = train_df[“survived”]<br>X_test = test_df.drop([“passengerid”], axis=1)</pre><pre>rf_base = RandomForestClassifier(n_estimators=100, random_state=0)<br>rf_base.fit(X_train, y_train)</pre><pre>n = len(X_train.columns)<br>importance_scores = rf_base.feature_importances_<br>rf_feature_ranking(n, importance_scores)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*-XQAu7M8kI5LaAANBrF20Q.png" /><figcaption>Random Forest Feature Importance</figcaption></figure><p>RF’s feature importance is a solid start to gauge what features are important but does not always give a definitive view of importance and can be misleading. The underlying mechanism of RF’s feature importance is biased. It tends to overestimate the importance of certain features, such as continuous or high cardinality categorical features. In a nutshell, the decrease in impurity is averaged for each feature in a forest of decision trees, and then the features are ranked based on this averaged value. Here’s a good <a href="https://link.springer.com/article/10.1186/1471-2105-8-25">read</a> on this and <a href="https://explained.ai/rf-importance/">this</a> and <a href="https://stackoverflow.com/questions/15810339/how-are-feature-importances-in-randomforestclassifier-determined">this</a>!</p><p>Collinear features will be an issue as well. Therefore, utilizing only RF’s mean decrease in impurity-based feature importance won’t show you the whole picture and must be one of many tools to understand feature importance better.</p><p>My concern at this point is collinear features. As a result, I’m leveraging permutation importance and hierarchical clustering to determine what features are relevant. Conceptually, in permutation importance, it calculates a baseline accuracy for the features using a validation set. Next, it permutes all the values for a single column/feature and measures the change against the baseline accuracy using the test dataset. This would be repeated for every feature.</p><p>In my research, I came across an informative article on this particular topic on Scikit-Learn’s <a href="https://scikit-learn.org/stable/auto_examples/inspection/plot_permutation_importance_multicollinear.html">website</a>. I’m going to leverage the code found here and complete my feature selection process. Also, I’ll rely on <em>domain knowledge </em>and <em>guided trial-and-error</em> to see what combinations of features will have the best outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*aQK3NUxrECPHGlRVBhcKDw.png" /></figure><p>Permutation importance is relatively more reliable than feature importance, although the former is also influenced by collinear features and inflates the importance of impacted features. One agreeable recommendation that came out of the two initial views was that is_alone, is_mix_group, and is_one_family do not add much value to the model.</p><p>For hierarchical clustering, the y-axis on the dendrogram represents closeness or dissimilarity. As it gets closer to 0, the closer the distance between clustered features indicating correlation/association. In this iteration, I examined all clusters falling under 1.5 — an arbitrary threshold. The code chunk used here is also available on S<a href="https://scikit-learn.org/stable/auto_examples/inspection/plot_permutation_importance_multicollinear.html">cikit-Learn’s website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*CahpccWAjERcc0kuDjcRng.png" /><figcaption>The dendrogram on the left and Spearman’s correlation matrix on the right</figcaption></figure><p>Using the dendrogram, I took a closer look at smaller clusters with two features (e.g., pclass and cabin_level) and heuristically determined what features might need to be dropped. I decided to drop age because it&#39;s highly collinear with age_bucket, and it’s a continuous feature. In addition, I decided to drop sex and fare because their correlated features would contribute equally to the model. As a result, a total of 7 features were dropped in the next iteration — age, sex, fare, is_alone, is_mix_group, and is_one_family</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddab4b085aa038c515f7826a816efcc7/href">https://medium.com/media/ddab4b085aa038c515f7826a816efcc7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d0940676b243fb297b479add9a15582/href">https://medium.com/media/9d0940676b243fb297b479add9a15582/href</a></iframe><h4>Iteration 2</h4><p>Let’s take a look at the updated results. In this iteration, I worked with 9 features, which represent the new X_train and X_test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*FCf6NISilffV1xOzLkQb7Q.png" /><figcaption>X_train.info()</figcaption></figure><p>I used the <em>output_model_stats</em> function to compare the performance metrics against the original random forest metrics. The iteration 2 metrics are attached to the “rf_base — iteration 2” index. Overall the model performed slightly less effectively than the model with all the features. Most likely, the first random forest model was overfitting (relatively low bias and high variance) and should not be a source of concern at this stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*sEo9wm9um_K315go3AKnVQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f38429dd8123ebc8d6e3169e8fb84f14/href">https://medium.com/media/f38429dd8123ebc8d6e3169e8fb84f14/href</a></iframe><p>Based on the updated feature and permutation importance ranking, embarked was very close to zero in both. I decided to drop this feature in the next iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*SHy-XzcVpnVz7bxk32fwKw.png" /></figure><p>I decided to drop fare_bucket as well as age_bucket. In my mind, the average fare_per_passenger calculation, which was used to create the fare buckets, most likely did not have enough data to generalize well and fare outliers lingering in the training data.</p><p>Similar logical thinking fell onto age_bucket after observing how high it ranked versus pclass and is_woman_child using permutation importance. At the same time, fare_bucket and age_bucket correlated with one another. My intuition told me that keeping these features would most likely decrease bias and increase variance. Therefore, the model&#39;s effectiveness to generalize would be reduced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*jjBS9Ez89veHr9B7vmlHnw.png" /></figure><p>As the dendrogram illustrates, the first cluster from the left under 0.5 is composed of pclass and cabin_level. The distance between pclass and cabin_level is very close, and Spearman’s correlation matrix shows these being correlated. I was hesitant to drop either pclass or is_woman_child because both features showed a high correlation to passenger survival during my exploratory analysis.</p><p>Random forest’s <a href="https://blog.datadive.net/selecting-good-features-part-iii-random-forests/#:~:text=Random%20forest%20feature%20importance,impurity%20and%20mean%20decrease%20accuracy.">randomness</a> of creating root nodes and splitting to create internal and leaf nodes reduce the effects of collinear features but never completely. In my opinion, it does not hurt to use both collinear features in this scenario using random forest.</p><h4>Iteration 3</h4><p>The updated X_train and X_test datasets contain 5 features at this stage, which I have deduced to be most relevant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*RCVb2LEWXdqy6ECzSdXswA.png" /><figcaption>X_train.info()</figcaption></figure><p>Next, I outputted the performance metrics (“rb_base — Iteration 3”) and compared them with earlier results. The accuracy_cv_score was higher than the previous two iterations. Precision improved quite a bit, which meant more true positives (TP) were found within all positives (TP + FP) detected by the model. This was a good sign. Recall dropped slightly as expected, which meant the model’s ability to detect true positives (TP) among actual true positives (TP + FN) outstanding had fallen a bit. F1 score improved from iteration 2, and the AUC under the ROC curve moved up to a new high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*U15_auOfdCNzlgUDB-MulA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f05f4b80df06711bc1a13d417ceccda/href">https://medium.com/media/6f05f4b80df06711bc1a13d417ceccda/href</a></iframe><p>After taking a closer look at feature importance, permutation importance, and dendrogram accompanied by Spearman’s correlation matrix, I decided these features would generate my first Kaggle submission file. At this point, I was not concerned about one pair of correlated features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*7tCVT3pIf988POjGd8QjyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Uhp4DbHMux1bpswxp7Y5_A.png" /></figure><p>I outputted the predicted y_test (y_pred_base) using the trained model with X_test. I created my submission file and submitted it to Kaggle. I was able to score 80.382% accuracy with this submission. I think this is a pretty respectable score.</p><pre>rf_base = RandomForestClassifier(n_estimators=100, random_state=0)<br>rf_base.fit(X_train, y_train)<br>y_pred_base = rf_base.predict(X_test)</pre><pre>df_output = pd.concat([test_df[‘passengerid’], y_pred_df], axis=1, sort=False)<br>df_output = df_output.rename(columns={“passengerid”: “PassengerId”})<br>df_output.to_csv(‘gender_submission.csv’, index=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*23R6U2POKiiW7ZOEaN1xJg.png" /></figure><h3>RandomizedSearchCV: Random Forest Classifier</h3><p>A good explanation of RandomizedSearchCV is found on Scikit-Learn’s documentation <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html">page</a>. It’s good to know Python’s approach to OOP. The model class objects in Scikit-Learn contain parameters, attributes, and methods.</p><blockquote>“The parameters of the estimator used to apply these methods are optimized by cross-validated search over parameter settings.</blockquote><blockquote>In contrast to GridSearchCV, not all parameter values are tried out, but rather a fixed number of parameter settings is sampled from the specified distributions. The number of parameter settings that are tried is given by n_iter.</blockquote><blockquote>If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribution, sampling with replacement is used. It is highly recommended to use continuous distributions for continuous parameters.”</blockquote><p>I’m focusing on the 6 hyperparameters listed under the rs_grid variable. For a detailed overview of all parameters, the documentation <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">page</a> contains a plethora of information.</p><h4>Random Forest Hyperparameters</h4><ul><li><strong>n_estimators:<em> </em></strong>This represents a number of decision trees in the forest. The default value is set at n_estimators=100.</li><li><strong>criterion: </strong>This function measures the quality of the split. For example, age is a feature that can be a root node. Based on the split criteria, it splits into internal and leaf nodes until tree growth is stopped when the lowest gini impurity is reached for a branch (default is set to gini and the second option is entropy for information gain).</li><li><strong>max_features: </strong>The number of the random subset of features to consider when looking for the best split.</li><li><strong>max_depth:</strong> The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.</li><li><strong>min_samples_split:</strong> The minimum number of samples required to split an internal node.</li><li><strong>min_samples_leaf:</strong> The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches.</li></ul><h4>RandomizedSearchCV Parameters</h4><ul><li><strong>estimator:</strong> model class instantiation used to conduct a randomized search for the best parameters.</li><li><strong>param_distributions:</strong> Dictionary with parameters names (str) as keys and distributions or lists of parameters to try.</li><li><strong>n_iter:</strong> Number of parameter settings that are sampled.</li><li><strong>cv:</strong> Determines the cross-validation splitting strategy.</li><li><strong>verbose:</strong> Controls the verbosity; the higher the verbosity number, the longer the output/log messages.</li><li><strong>random_state:</strong> Pseudo-random number generator state used for random uniform sampling from lists of possible values instead of scipy.stats distributions.</li><li><strong>n_jobs:</strong> Number of jobs to run in parallel. None means 1 unless in a <a href="https://joblib.readthedocs.io/en/latest/parallel.html#joblib.parallel_backend">joblib.parallel_backend</a> context. -1 means using all processors.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/515a7297a242c24c65d094c737362f20/href">https://medium.com/media/515a7297a242c24c65d094c737362f20/href</a></iframe><p>The randomized search took about 5 minutes using all my processor power (n_jobs=-1). The param_distributions contain 8,232 combinations of settings (7*2*2*7*7*6). For my randomized search, I set cv to 5, which equals the number of stratified Kfolds. Therefore, if I started with GridSearchCV, a total of 41,160 parameter settings or fits would be tried. This would take a very long time to run. However, with RandomizedSearchCV, it samples n_iter=200 from total possible settings and thus lowering the number of tasks or fits to 1,000 in this case. Here are the best hyperparameter values from this randomized search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*tqdPEf3SXDg-DcAnS2BZog.png" /><figcaption>best_params_ attribute of RandomizedSearchCV</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*P6W5fbNNKP52KhCtV0v2TQ.png" /><figcaption>By setting verbose=3, you get a nice output of what’s going on.</figcaption></figure><p>Let’s compare the results from my previous runs. The accuracy_cv_score increased by approximately 1.1% and accuracy_cv_stddev went down to about 4%. The precision score improved as well (91.47%) while recall went down a bit. The overall F1 score improved. The AUC score stood steady at 89%. Using what I have learned thus far, the goal is to run a grid search on a smaller set of settings and measure <a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html#sphx-glr-auto-examples-model-selection-plot-randomized-search-py">incrementality</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*X8190AG0Wa1-HINHh_yh7g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d08b2dee2a663e27ab7438f768ed9cb9/href">https://medium.com/media/d08b2dee2a663e27ab7438f768ed9cb9/href</a></iframe><h3>GridSearchCV: Random Forest Classifier</h3><p>GridSearchCV is similar to RandomizedSearchCV, except it will conduct an exhaustive search based on the defined set of model hyperparameters (GridSearchCV’s param_grid). In other words, it will go through all of the 41,160 fits from above. However, I’m leveraging the learnings from earlier and reducing the list of values for each hyperparameter. For a detailed overview of GridSearchCV’s parameters, take a look at the documentation <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">page</a>.</p><blockquote>“The parameters of the estimator used to apply these methods are optimized by cross-validated grid-search over a parameter grid.”</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ff05ee7a96857dca8528a0acbcaaf29/href">https://medium.com/media/2ff05ee7a96857dca8528a0acbcaaf29/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*3iqjyshKdkDvet4Zxvh5ug.png" /><figcaption>best_params_ attribute from GridSearchCV</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*YEf8t-_fznKHR8K0tgMS2A.png" /><figcaption>verbose=3</figcaption></figure><p>Overall, there wasn’t a whole lot of improvement, except AUC went up slightly. Either way, this demonstrated that tuning the right set of hyperparameters and covering a wide range of settings can improve model predictions. Therefore, learning to leverage RandomizedSearchCV and GridSearchCV becomes an important part of the machine learning workflow. However, you also need to know how much time and energy you want to put into the tuning process because the gain can be minimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*D-BIlplXAga-lgu_OuZl_Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d84f4ad82ad8831bc1d0c842129bf8/href">https://medium.com/media/80d84f4ad82ad8831bc1d0c842129bf8/href</a></iframe><p>As the last step, I generated the updated submission file and submitted it to Kaggle. Even with hyperparameter tuning, my score stayed at 80.382% for this set of features and this set of optimized hyperparameters.</p><h3>Conclusion</h3><h4>Latest Results</h4><p>Through trial-and-error and expanding the hyperparameter settings, I reached the current standing score of 80.861%, which, according to Kaggle, falls within the top 6%. In my opinion, this is a pretty solid score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*zWPw44Fop1iCJim1vJt6dw.png" /></figure><h4>Final thoughts</h4><ul><li>This project reinforced the idea that feature engineering is powerful. Five out of the six features used to predict survival were engineered features, which captured information that the original features could not.</li><li>Additionally, having enough context (reading about Titanic) on the subject matter was helpful, which helped during the exploratory analysis stage.</li><li>Spending enough time to explore (slicing and dicing) the data helped build intuition, which helped with feature engineering, aggregating, and grouping the dataset.</li><li>As these pieces fell in place, techniques like grid search and randomized search helped improve the model incrementally.</li><li>Lastly, I believe we can’t easily dismiss the significance of domain knowledge and guided trial-and-error in machine learning. These can be created into inputs, and the models can help quantify their importance.</li></ul><p>Please feel free to share your comments, feedback, and/or questions. If you’re interested in exploratory analysis and feature engineering, check out my first article — “<a href="https://towardsdatascience.com/kaggle-titanic-competition-in-sql-78ae3cd551ce"><em>Kaggle Titanic Competition in SQL</em></a>.” Thanks for reading!</p><p><a href="https://towardsdatascience.com/kaggle-titanic-competition-in-sql-78ae3cd551ce">Kaggle Titanic Competition in SQL</a></p><h3>Resources</h3><p>I recommend these three books if you are looking for good reference books on machine learning, data analysis, and improving your Python programming skill.</p><ul><li><a href="https://amzn.to/2Nse7gx">Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems 2nd Edition</a></li><li><a href="https://amzn.to/2YE0X6J">Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython 2nd Edition</a></li><li><a href="https://amzn.to/2V9l8r2">Fluent Python: Clear, Concise, and Effective Programming 1st Edition</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f4f74436b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/kaggle-titanic-competition-model-building-tuning-in-python-12f4f74436b5">Kaggle Titanic Competition: Model Building &amp; Tuning in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kaggle Titanic Competition in SQL]]></title>
            <link>https://medium.com/data-science/kaggle-titanic-competition-in-sql-78ae3cd551ce?source=rss-607ad4750966------2</link>
            <guid isPermaLink="false">https://medium.com/p/78ae3cd551ce</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[in-depth-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[titanic-dataset]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Do Lee]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 20:10:33 GMT</pubDate>
            <atom:updated>2024-09-13T18:38:40.955Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploratory Data Analysis &amp; Feature Engineering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9GmZZts-5E_rmj6xgfrRuw.jpeg" /></figure><h3>Introduction</h3><p>There is nothing more powerful than learning something new or taking a skill to the next level by simply doing. In this article, I’ll use SQL (Postgres) to conduct my exploratory analysis and create a transformed feature training set for my machine learning model.</p><p>Although Python or R is the current de facto language for data science and machine learning, having a solid foundation in SQL, at times, will help you iterate faster and allow you to explore your data quickly. At the end of the day, most of the data we work with lives in a relational database. Having the ability to write SQL queries fluidly will allow you to tackle data with ease and quickly get you started on your analysis.</p><h3>Goal</h3><p>Although Python would be my preferred approach, I wanted to see if I could do all my exploratory analysis and feature engineering in SQL. I aim to show how powerful and complementary SQL can be to one’s workflow. Although one obvious limitation of SQL is the ability to visualize data natively, you can still get big gains by quickly writing queries and outputting results. Let’s get started!</p><h3>My Setup</h3><ul><li>macOS Mojave Version 10.14.6</li><li>Postgres (PostgreSQL) 12.2</li><li><a href="http://www.pgadmin.org/">pgAdmin 4.21</a> (SQL web querying tool)</li><li><a href="https://www.postgresql.org/docs/12/app-psql.html">psql</a> (Terminal access to databases and tables)</li></ul><p>In the follow-up article, I completed my supervised classification model with Python and shared my highest score achieved on Kaggle’s Public Leadership Board. <a href="https://medium.com/@dolee_12121/kaggle-titanic-competition-model-building-tuning-in-python-12f4f74436b5">Check it out here!</a></p><p><a href="https://towardsdatascience.com/kaggle-titanic-competition-model-building-tuning-in-python-12f4f74436b5">Kaggle Titanic Competition: Model Building &amp; Tuning in Python</a></p><h3>Exploration</h3><p>My research into the sinking of the Titanic revealed that women and children were prioritized over others in transporting passengers into lifeboats. This notion plays a big role in how the dataset is analyzed downstream.</p><p>Additionally, there are <a href="https://www.kaggle.com/c/titanic/discussion/177536">discussions</a> of whether to keep training and test datasets separate or combine them for feature engineering and selection. In most cases, the former will make sense to avoid data leakage.</p><p>The common practice is putting aside the test dataset, forgetting about it, and only using the training dataset to impute and engineer features. For this exercise, I have decided to combine the training and test data so I have more data to predict survival. This is a fixed universe, and we are not expecting new data to flow into the prediction pipeline.</p><p>To get started, I downloaded the train.csv and test.csv files from Kaggle and imported the files to two tables I created in the Postgres database. Next, I combined the two tables to generate my first working table (titanic_train_test_raw).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7c9b98036d8c161e4fdc7dbbbfe2757/href">https://medium.com/media/b7c9b98036d8c161e4fdc7dbbbfe2757/href</a></iframe><p>To insert records into my tables, I opened psql on my terminal by typing “<em>psql postgres.”</em> This is a PostgreSQL command-line tool. I ran the following two psql copy commands to insert the CSV files into my tables.</p><pre>\copy titanic_train_raw from ‘file/path/train.csv’ delimiter ‘,’ csv HEADER;</pre><pre>\copy titanic_test_raw from ‘file/path/test.csv’ delimiter ‘,’ csv HEADER;</pre><p>To better understand the data, I calculated the survival_rate for every feature in the training set. I’m not sharing the entire output here because I’ll share them piece by piece throughout the article. However, this allowed me to develop a mental image of what features might be worth digging deeper into and getting a feel for each feature&#39;s relative importance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8c05cbb785023475ab628800a1bfd2/href">https://medium.com/media/2c8c05cbb785023475ab628800a1bfd2/href</a></iframe><p><strong>1. Missing values</strong></p><p>Let’s look at missing values and see what potential features need estimating or dropping due to sparsity. The missing-value calculations are done with a combined train and test data. Because test data does not have the Survived target feature, the combined Survived column has 31.93% of its values missing. Also, Age, Cabin, Fare, and Embarked are missing 20.09%, 77.46%, 0.08%, and 0.15%, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9xJichNN7NlyAP2khbt3g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1deb83402a7a401aab47c89d929a8b4f/href">https://medium.com/media/1deb83402a7a401aab47c89d929a8b4f/href</a></iframe><p><strong>2. Overall survival</strong></p><p>Using the training dataset, I calculated the survived % versus not survived %. Out of the 891 passengers in the training data, only 38.38% survived. Also, this analysis allowed me to see that the target class is not too imbalanced — it’s approximately a 60%/40% split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGEMY2eRQh0094cFPmJN0A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a050b6414438db929558d835e0f083f/href">https://medium.com/media/5a050b6414438db929558d835e0f083f/href</a></iframe><p><strong>3. Survival by sex and age</strong></p><p>Female passengers had the highest probability of survival versus male passengers. By sex alone, training data tells us that the survival rate is approximately 74.2% for women and 18.89% for men.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*26VXJ5_8GN-8rfsJPmy26Q.png" /></figure><p>Using pure SQL, I created 10 bins (age_cohort) to group different ages. I’m not going for any precise division of age groups, and thus the number of bins is arbitrary but enough to see relevant patterns. And one of the most critical pieces of information emerges from this view. While the female survival rate remained high across all age cohorts, a male individual of nine years or younger had a survival rate of almost 60% (line 9 in Data Output). By sex alone, men’s survival was under 20%, but by slicing the data with age cohorts we see that a subgroup of men had a relatively higher survival rate — children.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*d7q9GhV-1ZVE3qr9V8cXTw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e05f6181e07041ccccf68ed97f9588eb/href">https://medium.com/media/e05f6181e07041ccccf68ed97f9588eb/href</a></iframe><p><strong>4. Survival by fare and average fare per passenger</strong></p><p>To quickly get a sense of fare correlating to survival, I used ntile window function to evenly bucket passengers into 6 bins and created statistics for closer examination. This is a quick and dirty binning method because the same fare amounts could fall into different bins as shown by fare_min and fare_max.</p><p>At a glance, survival_rate looks to tick up as fares become more expensive. At the same time, fare_mean and fare_stddev jump pretty dramatically from bin 5 to 6. The highest fare_max price is $512.3292, while the lowest fare_min is $0. There is some noise in the fare column. What continues to hold is that female survival is much higher than men’s. Based on the fare_grouping attribute, female survival is 2x — 9x higher than men’s (survival_ratio).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gr86bUsBIgsWnsCtWaZbog.png" /></figure><p>I soon discovered that the fare represents the ticket&#39;s total cost and not the fare per passenger. For example, ticket PC 17755, there are four passengers. The Cardeza is a wealthy family traveling in first class with their two employees, Miss Ward and Mr. Lesurer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ge-8Lwmcr2NxZGvr5QLlw.png" /></figure><p>To get a sense of how much per fare cost, I divided the fare amount by the total number of passengers on each ticket and grouped the averages by Pclass. When examining the ticket feature, I saw families, mixed groups, and individuals attached to individual tickets. As a result, rather than using [SibSp (siblings &amp; spouses) + ParCh (parents &amp; children) + 1 (PassengerId)], commonly used by other Kaggle folks to calculate the family_size feature, using the number of passengers on each ticket generated a smaller standard deviation and gave me confidence that this would provide a relatively more accurate average fare per passenger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*avVl5TTZM1I0mlueottBMA.png" /></figure><p>On average, the first-class fare per passenger came out to be about $32, second-class fare per passenger about $12, and third-class about $8. This averaging removed quite a bit of noise built into the original fare feature. And fare_mean looked to be highly correlated to Pclass. Thus, having both features, Pclass, and fare_per_passenger, might be redundant. Later on, we might want to drop one of these during the model build.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8873f887b369a3ef532572ee8ed74b/href">https://medium.com/media/8e8873f887b369a3ef532572ee8ed74b/href</a></iframe><p><strong>5. Survival based on Title from original Name feature</strong></p><p>There are 17 unique titles some with high survival rates; however, most suffer from infrequency. There are only two passengers in the training data with the title, Major, and one passenger with Sir. To make each grouping relevant and impactful for modeling, I rolled up infrequent titles into four — Mr, Mrs, Miss, and Master — and thus created a title_grouping feature. For example, Mlle, an abbreviation for Mademoiselle, rolled up into Miss.</p><p>The title Master is interesting because it has a relatively high survival rate, and there are quite a few of them in the training data. During this period, boys were given this title until they reached adult age. Now we have a way to identify boys using the title_grouping while all girls and women are rolled up into Mrs. or Miss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*ijy-dr7kh8P0ozUKemSg2g.png" /></figure><p>I calculated the survival rate by each title_grouping, and the numbers are very telling. By carving out the boys from the male group, men’s survival rate drops. In contrast, boys’ survival is nearly 60%. I’ll encode this feature into numeric values during the final training dataset prep work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*kqFLSjV4dAIj25dPybDpeA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db5926f012472d262c354f0173f9fb9f/href">https://medium.com/media/db5926f012472d262c354f0173f9fb9f/href</a></iframe><p><strong>6. Survival based on being a woman or a child</strong></p><p>I came across Chris Deotte’s <a href="https://www.kaggle.com/cdeotte/titanic-using-name-only-0-81818">article</a> about a feature he created called “woman-child-groups” based on grouping passengers with family names (surnames) and titles. Essentially, it focuses on group survival. With that in mind, I created a binary feature flagging if each passenger is a woman or a boy. The is_woman_child = 1 captures all women and children while is_woman_child = 0 captures all adult men. This flag might be redundant with title_grouping and potentially contribute to overfitting the model, but let’s see how this works out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*cKEhQxy075bD7a9movdxhA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47cbb4d1bddca0ff6ef0956603a4de37/href">https://medium.com/media/47cbb4d1bddca0ff6ef0956603a4de37/href</a></iframe><p><strong>7. Survival based on cabin level (a.k.a. deck)</strong></p><p>Some of the readings I did for this showed that the majority of the third-class passengers were located in cabin levels F and G. With that, it made sense to look at cabin levels more closely, although 77% of the values were missing. I hypothesized that lower cabin levels decreased a passenger’s chance of survival.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5CmcwyjxWYCvASVkQwaVA.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Titanic_cutaway_diagram.png">Cutaway diagram of RMS <em>Titanic</em>, midships</a></figcaption></figure><p>After doing some analysis, I observed a decrease in survival rate when passengers were in the lower class group and lower cabin levels. I created a logic to approximate each passenger’s cabin level using Pclass and Embarked, which I’ll dive deeper into in the feature engineering section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*XadEZJ6FU6cXR2D1wJOAlQ.png" /></figure><p>Embarked alone doesn’t quite tell you a story of survival as shown below, but I believe it can be used to create new features that will have relatively higher predictive power. Titanic initially stopped at Southhampton, England, and then moved on to Cherbourg, France. Finally, stopping at Queenstown, Ireland, before sailing off to New York City.</p><blockquote>On a quick side note, there are two passengers with missing Embarked values, but I looked up these passengers and they both boarded the ship at Southhampton (S), England.</blockquote><p>I assumed a correlation between the embarked location and the deck (cabin_level) the cabin was located. In other words, every boarding location was for a specific set of cabins, and there was some form of organization around which cabins would be filled first based on the boarding location. Thus, if you had a third-class ticket that started with F, which indicated the deck the cabin resided in, you most likely boarded the ship from Southhampton, England, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*fe-FFUfooR_pFgKXjCpusg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e66ccecd2f5694267876e05d4b253568/href">https://medium.com/media/e66ccecd2f5694267876e05d4b253568/href</a></iframe><h3>Feature Transformation and Engineering</h3><p>Now that I understand the original training features and better insights into passenger survival, it’s time to consolidate our findings and start putting together the optimized training dataset for model fitting.</p><p><strong>1. is_one_family / is_mix_group / is_alone</strong></p><p><strong>Assumption:</strong> I am assuming that the same ticket number defines passengers traveling together. Furthermore, I’m assuming that if an individual is the only passenger attached to a ticket, this passenger is a solo traveler while potentially having other family members or relatives traveling on different tickets. Therefore, I grouped passengers based on ticket number and surname extracted from the original Name feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*ZakTstcOifFtV-FI7-O2YA.png" /></figure><p>There is a trade-off with this assumption, but I’m assuming that this captures most of the group scenarios. And the main goal of partitioning groups in this manner is to generalize the ship’s population.</p><ul><li>If a given ticket has a single surname with multiple passengers, that is considered one family, where 1 is True, and 0 is False (is_one_family). This is primarily to flag families traveling together. Thus, if a passenger was part of a single ticket family, this flag is marked as 1.</li><li>If a given ticket has multiple surnames and multiple passengers, this is flagged as a mixed group (is_mix_group). For example, ticket number 1601 has 7 different surnames. There are a total of 67 tickets with two or more surnames attached. I’m only showing the top 12 tickets here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*1LGcpfZpZxn3CzwNAeRSdg.png" /></figure><ul><li>If a given ticket has a single surname and a single passenger, this is a passenger traveling alone (is_alone). Taking a closer look at the male population, adult male passengers traveling alone had the lowest survival rate (15.57%) compared to adult males with families (17.46%) and boys with families (57.5%).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*1hxa-yDsZ8cMd-InJSxs6Q.png" /></figure><p>At a glance, adult male passengers without families or part of a mixed group had the lowest chance of survival. We do see some interesting patterns in this output. Male passengers traveling with their families had the highest rate of survival. Most likely, these male passengers were boys. I’ll verify this below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*_w3_gVunfVW4dsikrwBtxg.png" /></figure><p>When I carved out the boys from the male population, the picture is much clearer. Boys survived at a higher rate than adult men.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*5SdwbxcMJtsPrKof5tbAwg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d72338fcc2b8950f61e776fa2f31a5/href">https://medium.com/media/05d72338fcc2b8950f61e776fa2f31a5/href</a></iframe><p><strong>2. family_size</strong></p><p>To determine each passenger&#39;s family size, it’s logical to add SibSp, ParCh, and the current passenger (+1). However, rather than defining this at the passenger level, it made more sense to determine the maximum family size based on ticket number and surname.</p><p>I’m sticking with the assumption that families traveled together and, in this case, on the same ticket. As a result, the sum of SibSp, ParCh, and current passenger, which represents the family size, is matched with a ticket number and surname. I created a mapping SQL subquery where if you had the same ticket number and surname, then the family size (SibSp + ParCh + 1) would be mapped to the passenger.</p><p>Once the logic was put together, I looked at the average survival rate by family size and Pclass. Relatively large families had a lower rate of survival. It can be loosely inferred that if you were part of a big family, you died. Also, you died if you were alone. Since there are only a handful of tickets with four or more passengers, it’s hard to generalize large groups&#39; survival. However, based on available data, it is worth seeing if the family size has some relative importance in predicting survival.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*LNtFUeyqj9OJcp6nLfvHXw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b703e569009d93c39333b4ccba22c013/href">https://medium.com/media/b703e569009d93c39333b4ccba22c013/href</a></iframe><p><strong>3. Build the first consolidated feature table: titanic_train_test_raw_v2</strong></p><p>I am now putting together my first consolidate table based on all my findings above. In this step, I’m incorporating new features and transforming existing features for better model consumption. Here is a list of all the additions and enhancements.</p><ul><li>Encoding Sex feature as female = 1 and male = 0</li><li>Extract family_name (surname) from Name feature</li><li>Adding title_grouping feature that I shared earlier in the post</li><li>Adding is_woman_child feature</li><li>Extracting the cabin levels (deck) from the Cabin feature</li><li>Encoding Embarked feature as S = 0, C = 1, and Q = 2</li><li>Adding family_size feature based on ticket number and family_name (surname)</li><li>Adding is_one_family, is_mix_group, and is_alone features</li><li>Adding fare_per_passenger feature by dividing fare by count of PassengerId’s found on each ticket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgPgwVUWwGpc5lFnQXR0XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*mg39GUjiJo3eGbvwHvo_vg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4828bbe9d15099265d23d81ada70f203/href">https://medium.com/media/4828bbe9d15099265d23d81ada70f203/href</a></iframe><p><strong>4. Build the second consolidated feature table: titanic_train_test_raw_v3</strong></p><p>Using some of the features created earlier, I created a second consolidated table (v3) to add more features and make additional changes. It’s better to build multiple tables in this fashion when using SQL because it helps to keep things organized and makes SQL more readable by having smaller chunks.</p><ul><li><strong>Age missing values:</strong> Fill in missing Age values (line 11 &amp; lines 44–52). I grouped the data by Pclass, Sex, and title_grouping to calculate each grouping&#39;s average age. I went with the mean rather than the median because both sets of numbers are similar. I also calculated the standard deviation of the mean to examine the variability.</li><li><strong>Age_bucket:</strong> Additionally, I created a feature called age_bucket (line 12). I decided to take the continuous Age variable and put them into 7 bins. Because the Age feature contains estimated averages, it might be better to convert this into a categorical feature to minimize the noise in the continuous feature.</li><li><strong>Fare_bucket &amp; fare missing values: </strong>I calculated the average fare per passenger per Pclass during my exploratory analysis, and it was clear that prices were tied to class. I filled the missing fare values with fare_per_passenger tied to each passenger’s Pclass. At the same time, I created 5 bins to created a categorical feature.</li><li><strong>Title_grouping: </strong>The four text string labels in this feature were converted to numeric values. (Master = 0, Mrs = 1, Miss = 2, and Mr = 3)</li><li><strong>Cabin_level &amp; cabin level missing values: </strong>My approach to filling out the missing cabin_level values is to count all passengers by Pclass, Embarked, and cabin_level where Cabin is not null. Next, I ranked in descending order the number of passengers attached to Pclass, Embarked, and cabin_level, and for each combination of Pclass + Embarked, I grabbed the cabin_level with the highest number of passengers attached to it.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2412174d7334e8b46fd67e5317137626/href">https://medium.com/media/2412174d7334e8b46fd67e5317137626/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*seQlRFHbO-j7G9ZLpt8ySQ.png" /></figure><p><em>If Pclass = 1 and Embarked = 0, then cabin_level = C.</em></p><p><em>If Pclass = 1 and Embarked = 1, then cabin_level = C.</em></p><p><em>If Pclass = 1 and Embarked = 2, then cabin_level = C.</em></p><p><em>If Pclass = 2 and Embarked = 0, then cabin_level = F.</em></p><p><em>If Pclass = 3 and Embarked = 0, then cabin_level = G.</em></p><p><em>And so on!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eb2311bd43a60c5981da5157b3cbd98/href">https://medium.com/media/2eb2311bd43a60c5981da5157b3cbd98/href</a></iframe><p><strong>5. Building “women-child-group” modified logic</strong></p><p>I went ahead and tried to re-create <a href="https://www.kaggle.com/cdeotte/titanic-using-name-only-0-81818">Chris Deotte’s feature</a> with some modifications in SQL. I’ll go over what I did and, in my follow-up article, I’ll be testing the feature for impact and importance.</p><ul><li>First, each passenger’s title is labeled as man, woman, or boy. Simultaneously, all men’s titles are labeled as ‘noGroup’ because the priority for survival is given to women and children.</li><li>Next, I calculated the surname frequency for each passenger. This frequency looks at the whole dataset and not at the ticket level. And any passengers with a surname frequency of one or less, if any are labeled as ‘noGroup.’ Thus, women and children in families are prioritized over women who are traveling alone.</li><li>At this stage, the probability of survival is calculated using the training data’s Survived target feature based on the updated surname feature. At this point, most surnames have changed to ‘noGroup,’ and thus, all passengers’ survival will be generalized using this updated surname feature.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adddb0c31d09209cc9b4413fcbe79bcc/href">https://medium.com/media/adddb0c31d09209cc9b4413fcbe79bcc/href</a></iframe><ul><li>Finally, using the title and surname_survival, I created a new binary flag, title_surname_survival. This logic was incorporated when the final training and test datasets were created. I created two tables to capture each — titanic_train_ml_features_v0 and titanic_test_ml_features_v0.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*zNur6amEv4ico4YH8iYVfw.png" /></figure><ul><li>ML Training Dataset: titanic_train_ml_features_v0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_FKB-9urAjWwY8ZR3hhUg.png" /></figure><ul><li>ML Test Dataset: titanic_test_ml_features_v0 (Identical to training dataset except Survived feature is missing.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLE_PNjFH1uXjeEmtNK6uw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a8787e56279a98c23ea8e2193911467/href">https://medium.com/media/6a8787e56279a98c23ea8e2193911467/href</a></iframe><h3>Summary</h3><p>There is quite a lot of information presented in this article. I conducted my exploratory analysis and feature engineering using purely SQL. I leveraged GROUP BY, window functions, aggregation functions, subqueries, WITH clause, HAVING clause, and other SQL techniques to slice and dice the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E89sfl8xzsopEJ5H" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The next step is to export the finalized training and test datasets for analysis using Python. In my follow-up article, I’ll use Python to test different ML models, understand feature importance, and tune the chosen model using RandomizedSearchCV and GridSearchCV. Finally, I‘ll submit my predictions to Kaggle and see how I rank among other entries!</p><h4>Here’s an overview of what I cover in the follow-up article:</h4><blockquote><a href="https://medium.com/@dolee_12121/kaggle-titanic-competition-model-building-tuning-in-python-12f4f74436b5">Title: “Kaggle Titanic Competition: Model Building &amp; Tuning in Python”</a></blockquote><ul><li>Import Libraries</li><li>Prepare Train and Test Data Frames</li><li>Correlation Coefficient Matrix</li><li>Create Helper Function: Output Model Stats</li><li>Multiple Fitted Models and Best Fit Model</li><li>Create Helper Function: Output RF Feature Importance Ranking</li><li>Feature Selection with Random Forest Feature Importance, Permutation Importance, and Hierarchical Clustering</li><li>RandomizedSearchCV: Random Forest Classifier</li><li>GridSearchCV: Random Forest Classifier</li><li>Conclusion: Latest Results &amp; Final Thoughts</li></ul><p>If you have any questions, comments, or feedback, please let me know. Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78ae3cd551ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/kaggle-titanic-competition-in-sql-78ae3cd551ce">Kaggle Titanic Competition in SQL</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>