<?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 Sawsan Yusuf on Medium]]></title>
        <description><![CDATA[Stories by Sawsan Yusuf on Medium]]></description>
        <link>https://medium.com/@sawsanyusuf?source=rss-694a29ec1850------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QlWTqLmR-xSR3z84mZvLjg.png</url>
            <title>Stories by Sawsan Yusuf on Medium</title>
            <link>https://medium.com/@sawsanyusuf?source=rss-694a29ec1850------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:14:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sawsanyusuf/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[Building an Interactive Dash Web Application for Visualizing Clustering Models on Credit-Fearful…]]></title>
            <link>https://medium.com/@sawsanyusuf/building-an-interactive-dash-web-application-for-visualizing-clustering-models-on-credit-fearful-d71a8794dafa?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71a8794dafa</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 14:25:15 GMT</pubDate>
            <atom:updated>2024-11-18T14:25:15.048Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Interactive Dash Web Application for Visualizing Clustering Models on Credit-Fearful Households</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xzlJ6hjoCrrzqZ5si_LBA.jpeg" /></figure><p>Welcome to Part 4 of Project 5! In the last part, we created a K-means model based on the high variance numerical features in our dataset. We then used Plotly Express to visualize those features with a bar chart and a scatter plot of the clusters. It was a fun exercise!</p><p>Today, we’ll build on that and create an interactive web application using <strong>Dash</strong>—a Python library for building web apps without needing HTML or JavaScript. It’s maintained by Plotly, so it will integrate seamlessly with the visualizations from the previous part.</p><p>Before we dive in, let’s go over today’s objectives. First, we’ll import and clean the dataset, as we’ve done in previous parts. Then, we’ll build the app layout, placing the necessary elements in the right spots.<br>After that, we’ll create interactive visualizations that respond to user input, such as:<br> - A variance bar chart with options to display trimmed or untrimmed variance.<br> - A slider to adjust the number of clusters in the KMeans model.<br> - A PCA scatter plot that updates based on the selected number of clusters.<br>Finally, we’ll run the app and explore the results.</p><p>This article will differ from previous ones. We’ll move away from the typical ML workflow and focus more on the web app development process. The steps are as follows:<br>1. Data Preparation: Import and wrangle the data (same as before).<br>2. App Development:<br> - Build the layout (organize elements on the page).<br> - Add the variance bar chart, KMeans slider, and PCA scatter plot.<br> <br>The four key components of our app will be:<br>1. App Layout (where to place elements).<br>2. Variance Bar Chart (with trimmed and untrimmed variance options).<br>3. K-Means Slider (to adjust cluster count and retrain the model).<br>4. PCA Scatter Plot (display clusters dynamically).</p><p>Key Concepts to Understand:<br>- Callbacks: Mechanisms that allow interactive elements to update automatically (e.g., clicking a button or moving a slider triggers an update).<br>- Decorators: Functions that add functionality to existing Python functions (like giving them &quot;superpowers&quot;).</p><p>Next, let’s go over the libraries we’ll use in today’s session. We’ll be using:<br>1. Pandas for data wrangling.<br>2. Plotly Express for visualizations.<br>3. Dash for building the web app:<br> - `dash`: Core library for the app.<br> - `dash_core_components (dcc)`: Interactive elements like sliders and radio buttons.<br> - `dash_html_components`: For HTML elements like headers and layouts.<br> - `jupyter_dash`: To run the Dash app inside a Jupyter notebook.<br>4. Scikit-learn for K-Means, PCA, and other ML tools.</p><pre>import pandas as pd<br>import plotly.express as px<br>from dash import Input, Output, dcc, html<br>from jupyter_dash import JupyterDash<br>from scipy.stats.mstats import trimmed_var<br>from sklearn.cluster import KMeans<br>from sklearn.decomposition import PCA<br>from sklearn.metrics import silhouette_score<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import StandardScaler<br><br>JupyterDash.infer_jupyter_proxy_config()</pre><h3>1. Prepare Data</h3><p>Now it’s time to prepare our data. For this, we’ll build a `Wrangle` function, but with a slight twist. Normally, we talked about the function before we implemented the code, but for this session, I’ve placed all the relevant details directly in the function’s docstring.</p><p><strong>What is a Docstring?</strong></p><p>A docstring is a multi-line string used to document a function. It provides instructions on how the function works, and it’s placed immediately below the function definition. This makes it easier for you or others to understand how the function works when revisiting the code later.</p><p>A good docstring usually has three parts:</p><p>1. Summary Line: A brief, one-sentence explanation of what the function does.<br>2. Detailed Information: Additional information, such as how to use the function or any important details.<br>3. Parameters: Describes the function’s arguments, including the data type and purpose of each.</p><p>In our case, the `Wrangle` function has one parameter: `file_path`, which should be a string that points to the location of a CSV file.</p><p>Now, let’s implement the function based on the provided details. First, we’ll add the `file_path` argument, then load the data using `pandas.read_csv()`. After that, we’ll create a mask to filter only those households with a net worth less than $2 million.</p><pre>def wrangle(filepath):<br><br>    &quot;&quot;&quot;Read SCF data file into ``DataFrame``.<br><br>    Returns only credit fearful households whose net worth is less than $2 million.<br><br>    Parameters<br>    ----------<br>    filepath : str<br>        Location of CSV file.<br>    &quot;&quot;&quot;<br>    #Load data<br>    df = pd.read_csv(filepath)<br>    #Creat a mask<br>    mask = (df[&quot;TURNFEAR&quot;]==1) &amp; (df[&quot;NETWORTH&quot;]&lt; 2e6)<br>    #Subset data<br>    df = df[mask]<br>    return df</pre><p>Now, if we execute this function and use the question mark (`?`) after `wrangle`, we can see the docstring with instructions on how to use the function.</p><pre>wrangle?</pre><pre>Signature: wrangle(filepath)<br>Docstring:<br>Read SCF data file into ``DataFrame``.<br><br>Returns only credit fearful households whose net worth is less than $2 million.<br><br>Parameters<br>----------<br>filepath : str<br>    Location of CSV file.<br>File:      /content/&lt;ipython-input-4-e070e2792e2f&gt;<br>Type:      function</pre><p>Next, let’s use the function to load our data. By passing in the file path, we get the expected result—4,418 rows, just as we did in the previous parts.</p><pre>df = wrangle(&quot;SCFP2019.csv&quot;)<br>print(df.shape)<br>df.head()</pre><pre>(4418, 351)<br><br>	YY1	Y1	WGT	        HHSEX	AGE	AGECL	EDUC	EDCL	MARRIED	KIDS    ...	NWCAT	INCCAT	ASSETCAT	NINCCAT	NINC2CAT	NWPCTLECAT	INCPCTLECAT	NINCPCTLECAT	INCQRTCAT	NINCQRTCAT<br>5	2	21	3790.476607	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>6	2	22	3798.868505	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        3	        2	        2<br>7	2	23	3799.468393	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>8	2	24	3788.076005	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>9	2	25	3793.066589	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br><br>5 rows × 351 column<br></pre><h3>2. Build Dashboard</h3><p>With the data prepared, it’s time to start building the application.</p><h4>2.1. Application Layout</h4><p>First, let’s talk about the final product so you know what we’re aiming for, and then we’ll build the application.</p><p><strong>The Final Product</strong></p><p>The final application consists of three dynamic elements:</p><p>1. Variance Bar Chart: Displays the top 5 highest variance features in the dataset. Users can toggle between &quot;trimmed&quot; and &quot;not trimmed&quot; versions using radio buttons, which dynamically updates the chart.</p><p>2. K-Means Slider: Allows users to adjust the number of clusters in a K-means model. Moving the slider retrains the model and updates metrics like inertia and silhouette scores.</p><p>3. PCA Scatter Plot: Visualizes the dataset in a 2D scatter plot, color-coded by the number of clusters selected via the K-Means slider.</p><p>These elements work together to provide an interactive, data-driven experience.</p><p><strong>Instantiation Application</strong></p><p>Let’s begin by instantiating the app. We’ll use the `jupyter_dash` package to do this, and follow a common convention by naming our app `app`. We also need to specify the location of our application code, which is done using the special Python variable `__name__`.</p><pre>app = JupyterDash(__name__)</pre><p><strong>Application Layout</strong></p><p>We’ll begin by adding a title for the entire application, followed by a subsection title for the bar chart. To do this, we’ll use the `html` module and its `div` object to create a container for the layout. Think of a `div` as a section of the webpage where we can organize our elements.</p><p>First, we’ll create a `div` to contain everything and then add a list of elements inside. For the application title, we&#39;ll use an `H1` tag (the largest header), and for the bar chart section, we’ll use an `H2` tag (a smaller header).</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;) <br>])</pre><h4>2.2. Variance Bar Chart</h4><p><strong>Bar Chart: Presentation Layer</strong></p><p>Next, we’ll begin building the bar chart. But before continuing with the development of our data application, let’s first discuss its architecture. Our application consists of two main parts: the <strong>presentation layer</strong>, which handles the visualizations and interactive elements, and the <strong>business layer</strong>, which performs calculations like variance analysis, model training, and PCA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*QfXS_TkInbH1I3Jz6m1QnA.jpeg" /></figure><p>In application design, these parts are referred to as <strong>layers</strong>. Let me illustrate:</p><p>- The presentation layer is what the user interacts with, displaying elements like charts and sliders.<br>- The business layer handles the backend tasks, such as data processing and computations.</p><p>For these layers to work together, they need to communicate. For example, when a user clicks a button or interacts with a chart, the business layer must perform the necessary calculations and return the result to the presentation layer.</p><p>Initially, these layers could communicate directly: a widget in the presentation layer might call a function in the business layer, which then returns results (e.g., a visualization). While this might work in the short term, it creates challenges for long-term maintenance. If one layer changes, it often requires updates to the other, creating a tight coupling between them.</p><p>To solve this, we introduce a <strong>service layer.</strong> This layer acts as a mediator, translating data between the presentation and business layers. It decouples the two layers, making it easier to maintain and update each independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*zaRnHOLPQJj3WBiy52-Nsw.jpeg" /></figure><p><strong>How This Works in Our Application?</strong></p><p>Let’s break this down with our application’s components:</p><p>1. Presentation Layer: This includes the chart we built a while ago. And now, we’ll add the bar chart (graph object) to the layout.<br>2. Business Layer: Here, we’ll create a function, `get_high_var_features`, that calculates variance. <br>3. Service Layer: This layer will facilitate communication between the presentation and business layers.</p><p>We’ll build out each layer incrementally, starting with adding the bar chart to the presentation layer.</p><p>We’ll use `dcc.Graph` from Dash’s core components module as a placeholder for our bar chart. To allow communication with the business and service layers, we need to give the graph an ID. We’ll call it `bar-chart`.</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(id=&quot;bar-chart&quot;)<br>])</pre><p><strong>Bar Chart: Business Layer</strong></p><p>Now it’s time to develop a function in the business layer that returns the five highest variance features from our dataset.</p><p>We need a function that returns the five highest variance features from the DataFrame `df` (defined earlier in the part). The function will takes two parameters:<br> - `trimmed` (Boolean, default `True`): Determines whether to calculate the trimmed variance or regular variance. If `True`, the function calculates the trimmed variance, removing the top and bottom 10% of the data.<br> - `return_feature_names` (Boolean, default `True`): If `True`, the function returns the feature names as a list; otherwise, it returns a pandas Series with the feature names as the index and the variance values as the values.</p><p>Because we only want the top 5 features, we use `tail(5)` to retrieve the last five values after sorting by variance.</p><pre><br>def get_high_var_features(trimmed=True, return_feat_names=True):<br><br>    &quot;&quot;&quot;Returns the five highest-variance features of ``df``.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    return_feat_names : bool, default=False<br>        If ``True``, returns feature names as a ``list``. If ``False``<br>        returns ``Series``, where index is feature names and values are<br>        variances.<br>    &quot;&quot;&quot;<br>    #Calculate variance<br>    if trimmed:<br>        top_five_features = (<br>            df.apply(trimmed_var).sort_values().tail(5)<br>            )<br>    else:<br>        top_five_features = df.var().sort_values().tail(5)<br><br> <br>    return top_five_features</pre><p>To test the function, we’ll pass `trimmed=True` and verify that it returns the expected high-variance features. For example, running:</p><pre>get_high_var_features(trimmed=True, return_feat_names=True)</pre><p>Should return a list of the top 5 features with trimmed variance, such as:</p><pre>	             0<br>DEBT	        3.089865e+09<br>NETWORTH	3.099929e+09<br>HOUSES	        4.978660e+09<br>NFIN	        8.456442e+09<br>ASSET	        1.175370e+10<br><br>dtype: float64</pre><p>Next, we’ll set `trimmed=False` and check the result again. This time, we should get features calculated using the regular variance method.</p><pre>get_high_var_features(trimmed=False, return_feat_names=True)</pre><pre>	            0<br>NHNFIN	       2.254163e+10<br>HOUSES	       2.388459e+10<br>NETWORTH       4.847029e+10<br>NFIN	       5.713939e+10<br>ASSET	       8.303967e+10<br><br>dtype: float64</pre><p>Now we’ll modify the function to handle the `return_feature_names` parameter. If it’s set to `True`, the function will return just the feature names. If set to `False`, the function will return the full pandas Series containing both the feature names and their variance values.</p><pre>def get_high_var_features(trimmed=True, return_feat_names=True):<br><br>    &quot;&quot;&quot;Returns the five highest-variance features of ``df``.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    return_feat_names : bool, default=False<br>        If ``True``, returns feature names as a ``list``. If ``False``<br>        returns ``Series``, where index is feature names and values are<br>        variances.<br>    &quot;&quot;&quot;<br>    #Calculate variance<br>    if trimmed:<br>        top_five_features = (<br>            df.apply(trimmed_var).sort_values().tail(5)<br>            )<br>    else:<br>        top_five_features = df.var().sort_values().tail(5)<br><br>    #Extract names<br>    if return_feat_names:<br>        top_five_features = top_five_features.index.tolist()<br><br>    return top_five_features</pre><p>Let’s test the function again, now with both parameters:</p><p>1. Trimmed variance, return feature names (default behavior):</p><pre>get_high_var_features(trimmed=True, return_feat_names=True)</pre><pre>[&#39;DEBT&#39;, &#39;NETWORTH&#39;, &#39;HOUSES&#39;, &#39;NFIN&#39;, &#39;ASSET&#39;]</pre><p>2. Regular variance, return feature names as False:</p><pre>get_high_var_features(trimmed=False, return_feat_names=True)</pre><pre>[&#39;NHNFIN&#39;, &#39;HOUSES&#39;, &#39;NETWORTH&#39;, &#39;NFIN&#39;, &#39;ASSET&#39;]</pre><p>These tests confirm that the function works as expected.</p><p><strong>Bar Chart: Service Layer</strong></p><p>Now we’ll move on to connecting the layers by implementing a service layer. This layer will handle the communication between the presentation and business layers, ensuring smooth interaction as we continue to build out the application.</p><p>To achieve that, we will build the `serve_bar_chart` function, which will generate a horizontal bar chart displaying the top five high-variance features. The function will accept a single parameter, `trimmed`, which determines whether the chart shows the trimmed variances or the regular variances.</p><p>We begin by adding the `trimmed` parameter to the function definition, setting its default value to `True`. This will allow us to generate the chart with trimmed variances by default.<br>Next, we retrieve the top 5 features with the highest variance using the `get_high_var_features` function from the business layer. We pass `trimmed` to the function, along with `return_feature_names=False` to ensure we get the values of the features (not just the names).<br>Finally, using Plotly Express, we create the bar chart with the `px.bar()` function. We pass the feature values as the x-axis data and the feature names as the y-axis data. We also set the chart’s orientation to horizontal.<br>To ensure clarity, we update the layout to add labels to the x-axis and y-axis.</p><pre>def serve_bar_chart(trimmed=True):<br><br>    &quot;&quot;&quot;Returns a horizontal bar chart of five highest-variance features.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br>    &quot;&quot;&quot;<br>    #Get features<br>    top_five_features = get_high_var_features(trimmed=trimmed, return_feat_names=False)<br><br>    #Build bar chart<br>    fig = px.bar(x=top_five_features, y= top_five_features.index, orientation=&quot;h&quot;)<br>    fig.update_layout(xaxis_title=&quot;Variance&quot;, yaxis_title=&quot;Feature&quot;)<br><br>    return fig</pre><p>To verify that the function works as expected, we run the function with the default `trimmed=True` and then with `trimmed=False`. This should produce two different bar charts—one for the trimmed variances and one for the full variances.</p><pre>serve_bar_chart(trimmed=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*Cd88Q7E0zgoqEH8pbPoUaA.png" /></figure><pre>serve_bar_chart(trimmed=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*UKuUokNSHROLQt2R_wQiGg.png" /></figure><p>The chart correctly updates to display the top 5 features with the appropriate variance values. For example, the feature &quot;NFIN&quot; has a significantly higher variance in the full chart compared to the trimmed chart, confirming that the function works as expected.</p><p><strong>Bar Chart: Add Chart To Presentation Layer</strong></p><p>Now we’ll integrate this bar chart into our web application to preview how it will look in the presentation layer.</p><p>First, we’ll navigate to the layout. In the graph object, we’ve already defined an ID, but there is also an argument for `figure`, where we can pass the chart we created. We’ll use the `serve_bar_chart` function and keep the default `trimmed` value.</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(figure=serve_bar_chart(), id=&quot;bar-chart&quot;)<br>])</pre><p><strong>Bar Chart: Add Radio Button</strong></p><p>After we’ve added the bar chart to the presentation layer, now it’s time to implement radio buttons for users to toggle between trimmed and non-trimmed variances.</p><p>To do this, we’ll update the app layout again. First, I’ll locate the layout section and add a radio button component below the bar chart. We’ll use Dash Core Components (DCC) and the `RadioItems` object for this.</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(id=&quot;bar-chart&quot;, figure=serve_bar_chart()),<br>        dcc.RadioItems(<br>            options= [<br>                {&quot;label&quot;: &quot;Trimmed&quot;, &quot;value&quot;:True},<br>                {&quot;label&quot;:&quot;Not Trimmed&quot;, &quot;value&quot;:False}<br>            ],<br>            value= True,<br>            id=&quot;trim-button&quot;<br>            )<br>])</pre><p>Here, we define:<br>- ID: `trim-button` to connect it with the service layer.<br>- Default Value: `True`, which means the default option will be &quot;Trimmed.&quot;<br>- Options: A list with two choices—`Trimmed` (value `True`) and `Not Trimmed` (value `False`).</p><p><strong>Bar Chart: Callback Decorator</strong></p><p>Now, we need to connect the presentation layer (where the bar chart and radio buttons are) to the service layer. This requires a callback to dynamically update the chart based on user input.</p><p>A <strong>callback</strong> allows us to dynamically update the UI when a user interacts with it. We start by adding the callback decorator `@app.callback`, followed by the output and input.</p><p>Here:<br>- Output specifies where the updated value should go. We’re sending the updated figure to the `bar-chart` component.<br>- Input specifies the source of the update. In this case, the input is the value of the `trim-button` radio button.<br>In our case, the callback function takes the input from the radio button and updates the chart accordingly. We use the `serve_bar_chart` function, passing the value of the radio button (`True` for trimmed, `False` for non-trimmed) as a parameter.</p><pre>@app.callback(<br>    Output (&quot;bar-chart&quot;, &quot;figure&quot;), Input (&quot;trim-button&quot;,&quot;value&quot;)<br>    )<br>def serve_bar_chart(trimmed=True):<br><br>    &quot;&quot;&quot;Returns a horizontal bar chart of five highest-variance features.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br>    &quot;&quot;&quot;<br>    #Get features<br>    top_five_features = get_high_var_features(trimmed=trimmed, return_feat_names=False)<br><br>    #Build bar chart<br>    fig = px.bar(x=top_five_features, y= top_five_features.index, orientation=&quot;h&quot;)<br>    fig.update_layout(xaxis_title=&quot;Variance&quot;, yaxis_title=&quot;Feature&quot;)<br><br>    return fig</pre><p>The bar chart is now fully connected to the service layer, and the user can toggle between trimmed and non-trimmed variance options.</p><h4>2.3. K-means Slider and Metrics</h4><p>Next, we’ll move on to implementing the slider component, the K-Means slider. This will allow users to adjust the number of clusters the model is training on and view the corresponding metrics.</p><p><strong>K-Means Slider: Add Text</strong></p><p>To begin, add some title text to the layout to help guide the user. First, I’ll insert a comma at the end of the radio items, then add an HTML `&lt;h2&gt;` element with the title “K-means Clustering.”</p><p>Next, I’ll add an `&lt;h3&gt;` header titled “Number of Clusters (k)” for the slider section.</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(id=&quot;bar-chart&quot;, figure=serve_bar_chart()),<br>        dcc.RadioItems(<br>            options= [<br>                {&quot;label&quot;: &quot;trimmed&quot;, &quot;value&quot;:True},<br>                {&quot;label&quot;:&quot;not trimmed&quot;, &quot;value&quot;:False}<br>            ],<br>            value= True,<br>            id=&quot;trim-button&quot;<br>            ),<br>        #K-means slider<br>        html.H2(&quot;K-Means Clustering&quot;),<br>        html.H3(&quot;Number of Clusters (k)&quot;)<br>])</pre><p><strong>K-Means Slider: Add Slider</strong></p><p>After making these changes, it’s time to implement the slider itself. To do this, in the K-means slider section, I’ll use Dash’s core components (DCC) to create the slider element. We’ll define several parameters for the slider: the minimum value (2), the maximum value (12), the step value (1), and the default value (2). Finally, we’ll assign an ID to the slider element, which we’ll use to connect it to the service layer. The ID will be &quot;k-slider.&quot;</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(id=&quot;bar-chart&quot;, figure=serve_bar_chart()),<br>        dcc.RadioItems(<br>            options= [<br>                {&quot;label&quot;: &quot;trimmed&quot;, &quot;value&quot;:True},<br>                {&quot;label&quot;:&quot;not trimmed&quot;, &quot;value&quot;:False}<br>            ],<br>            value= True,<br>            id=&quot;trim-button&quot;<br>            ),<br>        #K-means slider<br>        html.H2(&quot;K-Means Clustering&quot;),<br>        html.H3(&quot;Number of Clusters (k)&quot;),<br>        dcc.Slider(min=2, max=12, step=1, value=2, id=&quot;k-slider&quot;)<br>])</pre><p><strong>K-Means Slider: Add Text Placeholder</strong></p><p>With the presentation layer set up, the next tasks will focus on building the business and service layers for this element.</p><p>But before updating the metrics with our case slider, we need a placeholder for displaying the text. Let’s add this element to the layout before building our functions.</p><p>In the layout section, where we’ll add an HTML `div` element. Inside this, we’ll nest another `div` with an ID set to &quot;metrics&quot; for easy reference.</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(id=&quot;bar-chart&quot;, figure=serve_bar_chart()),<br>        dcc.RadioItems(<br>            options= [<br>                {&quot;label&quot;: &quot;trimmed&quot;, &quot;value&quot;:True},<br>                {&quot;label&quot;:&quot;not trimmed&quot;, &quot;value&quot;:False}<br>            ],<br>            value= True,<br>            id=&quot;trim-button&quot;<br>            ),<br>        #K-means slider<br>        html.H2(&quot;K-Means Clustering&quot;),<br>        html.H3(&quot;Number of Clusters (k)&quot;),<br>        dcc.Slider(min=2, max=12, step=1, value=2, id=&quot;k-slider&quot;),<br>        html.Div(id=&quot;metrics&quot;)<br>])</pre><p>Now, we can proceed to build the functionality that will populate this div for the user.</p><p><strong>K-Means Slider: Business Layer</strong></p><p>To continue building our slider element, we’ll move to the business layer to create a function called `get_model_metrics`. This function will take input, train a model, and either return the model itself or specific metrics, such as inertia and silhouette scores.</p><p>We’ll add the following parameters to the function:</p><p>- `trimmed`: Determines whether the model uses trimmed or regular variances (default: `True`).<br>- `K`: Specifies the number of clusters (default: `2`).<br>- `return_metrics`: Decides whether to return the model or metrics as a dictionary (default: `False`).</p><p>With these in place, the function will first retrieve high-variance features using the `get_high_var_features` function, keeping it adaptable based on the `trimmed` parameter. Next, we’ll create a feature matrix, `X`, by selecting the relevant features from our DataFrame.</p><p>Now, we build the model using a pipeline containing a `StandardScaler` and `KMeans` predictor. The number of clusters will be set to `K`, and for reproducibility, we set the random state to 42. After building, we fit the model to the data.</p><pre>def get_model_metrics(trimmed=True, k=2, return_metrics=False):<br><br>    &quot;&quot;&quot;Build ``KMeans`` model based on five highest-variance features in ``df``.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br><br>    return_metrics : bool, default=False<br>        If ``False`` returns ``KMeans`` model. If ``True`` returns ``dict``<br>        with inertia and silhouette score.<br><br>    &quot;&quot;&quot;<br>    #Get high var features<br>    features = get_high_var_features(trimmed=trimmed,return_feat_names=True)<br>    #Create features matrix<br>    X = df[features]<br>    #Build model<br>    model = make_pipeline(StandardScaler(), KMeans(n_clusters=k, random_state=42))<br>    model.fit(X)<br>    <br><br>    return model</pre><p>To add metric functionality, we introduce an `if` clause for `return_metrics`. If `True`, the function calculates inertia and silhouette score, rounds them for readability, and returns them in a dictionary. Note that we’re using two `return` commands, but only one will execute based on the value of `return_metrics`.</p><pre>def get_model_metrics(trimmed=True, k=2, return_metrics=False):<br><br>    &quot;&quot;&quot;Build ``KMeans`` model based on five highest-variance features in ``df``.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br><br>    return_metrics : bool, default=False<br>        If ``False`` returns ``KMeans`` model. If ``True`` returns ``dict``<br>        with inertia and silhouette score.<br><br>    &quot;&quot;&quot;<br>    #Get high var features<br>    features = get_high_var_features(trimmed=trimmed,return_feat_names=True)<br>    #Create features matrix<br>    X = df[features]<br>    #Build model<br>    model = make_pipeline(StandardScaler(), KMeans(n_clusters=k, random_state=42))<br>    model.fit(X)<br><br>    if return_metrics:<br>        #Calculate inertia<br>        i = model.named_steps[&quot;kmeans&quot;].inertia_<br>        #Calculate silhouette score<br>        ss = silhouette_score(X, model.named_steps[&quot;kmeans&quot;].labels_)<br>        #Put results in dictionary<br>        metrics = {<br>            &quot;inertia&quot;: round(i),<br>            &quot;silhouette score&quot;: round(ss, 3)<br>            }<br>        # retun dictionary to user<br>        return metrics<br><br>    return model</pre><p>With this setup, running the function with `return_metrics=True` provides the inertia and silhouette scores.</p><p>And with the business layer for our case slider completed, we now turn to the service layer.</p><p><strong>K-Means Slider: Service Layer</strong></p><p>This next step involves creating a function called `serve_metrics`, which will retrieve model metrics and format them into HTML elements for display.</p><p>We’ll begin by defining the function with two parameters: `trimmed`, set to `True` by default, and `K`, set to `2`. This function will receive inputs from the presentation layer, call the `get_model_metrics` function to retrieve metrics, and format these metrics into HTML elements to be displayed.</p><p>First, we retrieve the metrics by calling `get_model_metrics` and storing the result in a dictionary called `metrics`. We set the `trimmed` and `K` arguments to match our function parameters, and set `return_metrics=True` to obtain just the metrics.</p><p>Next, we structure these metrics as HTML text. We initialize a list called `text`, which will hold two HTML elements. Using the `html` module, we create `H3` tags for each metric, adding headers for &quot;Inertia&quot; and &quot;Silhouette Score&quot; with their respective values retrieved from the `metrics` dictionary.</p><p>After structuring the HTML, we return this `text` to whichever function calls `serve_metrics`.</p><pre>def serve_metrics(trimmed=True, k=2):<br><br>    &quot;&quot;&quot;Returns list of ``H3`` elements containing inertia and silhouette score<br>    for ``KMeans`` model.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br>    &quot;&quot;&quot;<br>    #Get metrics<br>    metrics = get_model_metrics(trimmed=trimmed, k=k, return_metrics=True)<br><br>    #Add metrics to html elements<br>    text = [<br>        html.H3(f&quot;Inertia:{metrics[&#39;inertia&#39;]}&quot;),<br>        html.H3(f&quot;Silhouette Score:{metrics[&#39;silhouette score&#39;]}&quot;)<br>    ]<br>    return text</pre><p><strong>K-Means Slider: Callback Decorator</strong></p><p>With the service layer function operational, our next step will involve adding a callback to link this to the presentation layer, completing the slider functionality.</p><p>This callback specifies that the output should be directed to the `metrics` element in our layout, particularly targeting the `children` attribute. For the inputs, we have two: one for the `trimmed` value (from the trim button) and one for the `K` value (from the slider).</p><pre>@app.callback(<br>    Output(&quot;metrics&quot;, &quot;children&quot;),<br>    Input(&quot;trim-button&quot;, &quot;value&quot;),<br>    Input(&quot;k-slider&quot;, &quot;value&quot;)<br>    )<br><br>def serve_metrics(trimmed=True, k=2):<br><br>    &quot;&quot;&quot;Returns list of ``H3`` elements containing inertia and silhouette score<br>    for ``KMeans`` model.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br>    &quot;&quot;&quot;<br>    #Get metrics<br>    metrics = get_model_metrics(trimmed=trimmed, k=k, return_metrics=True)<br><br>    #Add metrics to html elements<br>    text = [<br>        html.H3(f&quot;Inertia:{metrics[&#39;inertia&#39;]}&quot;),<br>        html.H3(f&quot;Silhouette Score:{metrics[&#39;silhouette score&#39;]}&quot;)<br>    ]<br>    return text</pre><p>With the K-means clustering slider now complete, the next step will involve creating the PCA scatter plot for enhanced visualization.</p><h4>2.4. PCA Scatter Plot</h4><p><strong>PCA Scatter Plot: Presentation Layer</strong></p><p>This begins by adding a placeholder graph for the scatter plot in the presentation layer.</p><p>To implement this, we’ll go to the layout section and add a new `dcc.Graph` element, assigning it an ID of &quot;PCA_scatter&quot; to serve as the placeholder for the scatter plot.</p><pre>app.layout = html.Div(<br>    [<br>        #Application title<br>        html.H1(&quot;Survey of Consumer Finances&quot;),<br>        # Bar chart<br>        html.H2(&quot;High Variance Features &quot;),<br>        # Bar chart graph<br>        dcc.Graph(id=&quot;bar-chart&quot;),<br>        dcc.RadioItems(<br>            options= [<br>                {&quot;label&quot;: &quot;trimmed&quot;, &quot;value&quot;:True},<br>                {&quot;label&quot;:&quot;not trimmed&quot;, &quot;value&quot;:False}<br>            ],<br>            value= True,<br>            id=&quot;trim-button&quot;<br>            ),<br>        #K-means slider<br>        html.H2(&quot;K-Means Clustering&quot;),<br>        html.H3(&quot;Number of Clusters (k)&quot;),<br>        dcc.Slider(min=2, max=12, step=1, value=2, id=&quot;k-slider&quot;),<br>        html.Div(id=&quot;metrics&quot;),<br>        # PCA scatter plot<br>        dcc.Graph(id=&quot;pca-scatter&quot;)<br><br>    ])</pre><p><strong>PCA Scatter Plot: Business Layer</strong></p><p>In the business layer, the key function is `get_pca_labels`, which generates a 2D representation of our data with the model’s labels. This function has two parameters—`trimmed` and `K`—allowing us to set default values for easy adjustments. We start by creating the feature matrix using the high-variance features of the data, applying the `get_high_var_features` function, which filters the features based on the `trimmed` parameter.</p><p>After constructing the feature matrix, we initialize a PCA transformer with two components, representing our data in a 2D space. The transformed data is then stored in a DataFrame with columns &quot;PC1&quot; and &quot;PC2.&quot;</p><p>Once the PCA transformation is complete, we generate cluster labels. Using the `get_model_metrics` function, we retrieve the clustering model and apply its labels to the new &quot;labels&quot; column in the DataFrame. To ensure consistent ordering, the DataFrame is sorted by the labels column, preparing it for dynamic updates in the scatter plot.</p><pre>def get_pca_labels(trimmed=True, k=2):<br><br>    &quot;&quot;&quot;<br>    ``KMeans`` labels.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br>    &quot;&quot;&quot;<br>    # Create features matrix<br>    features = get_high_var_features(trimmed=trimmed, return_feat_names=True)<br>    X = df[features]<br><br>    # Build transformer<br>    transformer = PCA(n_components=2, random_state=42)<br><br>    # Transform data<br>    X_t = transformer.fit_transform(X)<br>    X_pca = pd.DataFrame(X_t, columns = [&quot;PC1&quot;, &quot;PC2&quot;])<br><br>    # Add labels<br>    model = get_model_metrics(trimmed=trimmed, k=k, return_metrics=False)<br>    X_pca[&quot;labels&quot;] = model.named_steps[&quot;kmeans&quot;].labels_.astype(str)<br>    X_pca.sort_values(&quot;labels&quot;, inplace=True)<br><br>    return X_pca</pre><p><strong>PCA Scatter Plot: Service Layer</strong></p><p>The final step will be to build the service layer function to render the scatter plot dynamically.</p><p>So now we’ll create a service layer function called `serve_scatter_plot` to generate the scatter plot using data from the business layer.</p><p>This function will construct a PCA scatter plot to visualize clustering results. It takes two parameters, `trimmed` and `k`, allowing users to toggle between different datasets and specify the number of clusters.</p><p>To start, we initialize the plot with Plotly Express using `px.scatter`. The data source for this plot will be the DataFrame returned by `get_pca_labels`, which provides a 2D representation of the data. The x-axis and y-axis will be `PC1` and `PC2`, respectively, and the points will be colored based on cluster labels.</p><p>We’ll also add a title, &quot;PCA Representation of Clusters,&quot; and label the axes accordingly. Once configured, the function can be tested to ensure it generates a scatter plot as expected.</p><pre>def serve_scatter_plot(trimmed=True, k=2):<br><br>    &quot;&quot;&quot;Build 2D scatter plot of ``df`` with ``KMeans`` labels.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br>    &quot;&quot;&quot;<br>    fig = px.scatter(<br>        data_frame = get_pca_labels(trimmed=trimmed, k=k),<br>        x = &quot;PC1&quot;,<br>        y = &quot;PC2&quot;,<br>        color = &quot;labels&quot;,<br>        title = &quot;PCA Representation of Clusters&quot;<br>        )<br>    fig.update_layout(xaxis_title = &quot;PC1&quot;, yaxis_title=&quot;PC2&quot;)<br><br>    return fig</pre><p><strong>PCA Scatter Plot: Callback Decorator</strong></p><p>With this service layer function ready, the final step is to connect it to the presentation layer via a callback.</p><p>In our layout, we’ll add an `app.callback` decorator to set up outputs and inputs for seamless communication between the scatter plot element and UI controls. The output will target the PCA scatter element’s figure parameter, while the inputs will include the `trim_button` for toggling data trimming and the `K_slider` for selecting the number of clusters.</p><pre>@app.callback(<br>    Output(&quot;pca-scatter&quot;, &quot;figure&quot;),<br>    Input(&quot;trim-button&quot;, &quot;value&quot;),<br>    Input(&quot;k-slider&quot;, &quot;value&quot;)<br>    )<br><br>def serve_scatter_plot(trimmed=True, k=2):<br><br>    &quot;&quot;&quot;Build 2D scatter plot of ``df`` with ``KMeans`` labels.<br><br>    Parameters<br>    ----------<br>    trimmed : bool, default=True<br>        If ``True``, calculates trimmed variance, removing bottom and top 10%<br>        of observations.<br><br>    k : int, default=2<br>        Number of clusters.<br>    &quot;&quot;&quot;<br>    fig = px.scatter(<br>        data_frame = get_pca_labels(trimmed=trimmed, k=k),<br>        x = &quot;PC1&quot;,<br>        y = &quot;PC2&quot;,<br>        color = &quot;labels&quot;,<br>        title = &quot;PCA Representation of Clusters&quot;<br>        )<br>    fig.update_layout(xaxis_title = &quot;PC1&quot;, yaxis_title=&quot;PC2&quot;)<br><br>    return fig</pre><h4>2.5. Application Deployment</h4><p>Running this cell launches the application, enabling real-time interaction with the plot.</p><pre>app.run_server(host=&quot;0.0.0.0&quot;, mode=&quot;external&quot;)</pre><p>Adjusting the slider dynamically updates the clusters, and toggling the trim option reconfigures the displayed data.</p><h3>Conclusion</h3><p>Reflecting on what we accomplished in this project, we’ve covered a range of essential techniques. We started by importing data and explored docstrings for better documentation. We then structured the web application, assembling HTML and Dash components within a Jupyter Dash framework. Following a layered architecture, we organized the project into the presentation layer (user interface), the business layer (computational logic), and the service layer (middleware for communication between layers).</p><p>This project has provided a comprehensive understanding of unsupervised learning and clustering, culminating in an interactive dashboard that allows users to explore cluster variations and high-variance features. Completing this project is a significant achievement, and the skills gained here will be foundational as we move forward to Project 6.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71a8794dafa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Clustering of Credit-Fearful Households Using High-Variance Features in K-Means]]></title>
            <link>https://medium.com/@sawsanyusuf/advanced-clustering-of-credit-fearful-households-using-high-variance-features-in-k-means-093ab032bc73?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/093ab032bc73</guid>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 13:55:54 GMT</pubDate>
            <atom:updated>2024-11-04T13:55:54.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCmeh1xs5MpQuYVaRdyn3g.jpeg" /></figure><p>Welcome to Part Three of Project Five! In the last article, we created a K-Means clustering model using Survey of Consumer Finances data, focusing on credit-fearful households. While we made some interesting distinctions, we were limited to only two features, which helped us visualize the model’s mechanics.</p><p>Now that we’ve established this foundation, we’ll build a model with more features in this part. Our goal is to leverage high-variance features from our dataset, which contains 315 features, to enhance clustering accuracy.</p><p>For our objectives for Today, First, we’ll calculate the variance of each feature to identify those with the highest variability.</p><p>Next, we’ll develop an unsupervised model to cluster households, similar to our approach in Part Two but with added refinements. We’ll also analyze the mean characteristics of each cluster and visualize them using side-by-side bar charts. Since we’re working with multidimensional data, we’ll use <strong>Principal Component Analysis (PCA)</strong> to reduce dimensions and visualize clusters in two dimensions.</p><p>In this article, we’ll follow our usual machine-learning workflow. The Import phase will be similar to Part Two. Then, we’ll assess features and trimmed variance in the Exploring phase. Finally, we’ll split the data, focusing only on the feature matrix since this is unsupervised learning.</p><p>In the model-building phase, we’ll iterate on a K-means model, experimenting with different cluster numbers and applying <strong>StandardScaler</strong> to normalize features.<br>In the results communication phase, we’ll create visualizations, including side-by-side bar charts and PCA scatter plots.</p><p>The libraries we’ll use for today: <br>Pandas for data wrangling, Plotly Express for visualizations, SciPy for trimmed variance, K-Means, and PCA for modeling. <br>Silhouette Score and Make Pipeline to streamline multi-step models, and<br>StandardScaler to standardize our data.</p><pre>import pandas as pd<br>import plotly.express as px<br><br>from scipy.stats.mstats import trimmed_var<br>from sklearn.cluster import KMeans<br>from sklearn.decomposition import PCA<br>from sklearn.metrics import silhouette_score<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import StandardScaler<br></pre><p>Let’s dive into the data wrangling and get started!</p><h3>1. Prepare Data</h3><h4>1.1. Import</h4><p>Now it’s time to build our `wrangle` function. This function will differ slightly from the one we created in the last section, though the change is an important one. We&#39;re still focused on credit-fearful households, but this time, we&#39;ll only examine households with a net worth of less than 2 million.</p><p>Since we&#39;re interested in net worth, we’ll refer to the data dictionary to locate the specific feature called `NETWORTH`, which will be the focus of our analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRIJ5a1M6QdDdjgIInkCiA.jpeg" /></figure><p>With this in mind, our `wrangle` function will filter data for both credit-fearful households and those with a net worth under 2 million. First, we need to load the data file into memory.</p><p>Next, we&#39;ll create a mask with two criteria to filter the data. To ensure both criteria are met, we’ll enclose each condition in parentheses and combine them with the ampersand (`&amp;`), indicating that both conditions must be true for a row to be included in the filtered data. The first criterion will filter by `TURNFEAR`, and the second will focus on `NETWORTH`.</p><pre>def wrangle(filepath):<br>    #read file into DataFrame<br>    df = pd.read_csv(filepath)<br>    mask = (df[&quot;TURNFEAR&quot;] == 1) &amp; (df[&quot;NETWORTH&quot;] &lt; 2e6)<br>    df = df[mask]<br><br>    return df<br></pre><pre>df = wrangle(&quot;SCFP2019.csv&quot;)<br>print(df.shape)<br>df.head()<br></pre><pre>(4418, 351)<br><br>	YY1	Y1	WGT	        HHSEX	AGE	AGECL	EDUC	EDCL	MARRIED	KIDS	...	NWCAT	INCCAT	ASSETCAT	NINCCAT	NINC2CAT	NWPCTLECAT	INCPCTLECAT	NINCPCTLECAT	INCQRTCAT	NINCQRTCAT<br>5	2	21	3790.476607	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>6	2	22	3798.868505	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        3	        2	        2<br>7	2	23	3799.468393	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>8	2	24	3788.076005	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>9	2	25	3793.066589	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br><br>5 rows × 351 columns<br></pre><p>With these filters applied, we end up with a slightly smaller dataset: instead of 4,600 households, we now have around 4,400 that meet both conditions. Now that our data is ready, we’ll move on to the exploration phase.</p><h4>1.2. Explore</h4><p>As mentioned at the start, our goal is to build a clustering model that uses multiple features. So, how do we choose these features, and what criteria should we consider?</p><p>There are a few key factors to keep in mind for feature selection, especially when working with a clustering model. First, it’s essential to match your features to the model type. Generally, K-Means works best with numerical features. If you want to cluster categorical data, K-Modes may be more suitable, but we’ll focus on K-Means here and stick with numerical features only.</p><p>The second consideration is your stakeholders. Previously, we discussed how marketing goals can influence the number of clusters you choose. Similarly, stakeholder needs might also shape your feature selection. You may be limited to features that are easily interpretable or relevant to your team.</p><p>For instance, some features, like “net worth” (representing a household’s total net worth), are straightforward to understand. Compare this to a feature like “NH_MORT,” which represents the total mortgage value and home equity loan secured by the primary residence. Explaining “NH_MORT” might be more challenging for a non-technical audience, so you might prefer “net worth” over it.</p><p>If you don’t face these kinds of limitations, a good rule of thumb for K-Means models is to prioritize features with high variance. Higher variance can help form more distinct clusters, as spread-out data is easier to separate than tightly grouped values.</p><p>We haven’t covered variance in detail yet, so let’s explore the concept briefly, and then see how to apply it in Python. To begin, I’ll walk through the formula for variance. Let’s say we have a series ( X ), representing a variable like “debt.” Variance gives us a sense of how spread out the values in ( X ) are, calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*woeUuWFiS1bDZjfJGg4lOg.jpeg" /></figure><p>where ( N ) is the number of observations in our column.</p><p>Since we’re using Python, let’s look at how this works practically. Suppose we define ( X ) as the “debt” column in our DataFrame, `df`. To calculate the variance, we simply run:</p><pre>X = df[&quot;DEBT&quot;]<br>X.var()<br></pre><pre>18482520920.408085<br></pre><p>This command does exactly what the formula describes. For clarity, let’s manually calculate it to confirm we get the same result.</p><pre>sum((X - X.mean())**2)<br></pre><pre>18482520920.408085<br></pre><p>Now, to calculate variance across the entire dataset, we can apply the same method on a DataFrame:</p><pre>df.var()<br></pre><pre>	               0<br>YY1	        2.876461e+06<br>Y1	        2.876460e+08<br>WGT	        4.808436e+06<br>HHSEX	        2.192779e-01<br>AGE	        2.154642e+02<br>...	             ...<br>NWPCTLECAT	5.178676e+00<br>INCPCTLECAT	6.070208e+00<br>NINCPCTLECAT	6.136292e+00<br>INCQRTCAT	9.512230e-01<br>NINCQRTCAT	9.624869e-01<br><br>351 rows × 1 columns<br><br><br>dtype: float64<br></pre><p>This gives us a series of variance values, one for each column in the dataset. We’re only interested in the top 10 features with the highest variance. First, we sort the values in descending order, and then we select the top 10:</p><pre>top_ten_var = df.var().sort_values(ascending=False).head(10)<br>top_ten_var<br></pre><pre>	           0<br>PLOAN1	     1.140894e+10<br>ACTBUS	     1.251892e+10<br>BUS	     1.256643e+10<br>KGTOTAL	     1.346475e+10<br>DEBT	     1.848252e+10<br>NHNFIN	     2.254163e+10<br>HOUSES	     2.388459e+10<br>NETWORTH     4.847029e+10<br>NFIN	     5.713939e+10<br>ASSET	     8.303967e+10<br><br>dtype: float64<br></pre><p>And now, we have the top 10 features in our dataset with the highest variance, such as “assets,” “net worth,” and “debt.”</p><p>Seeing these variance values is helpful, but a bar chart will make the results much easier to interpret. For visualization, we’ll use Plotly Express instead of Seaborn or Matplotlib.</p><pre>fig = px.bar(<br>    x = top_ten_var,<br>    y = top_ten_var.index,<br>    title = &quot;SCF: High Variance Features&quot;<br>)<br><br>fig.update_layout(xaxis_title = &quot;Variance&quot;, yaxis_title = &quot;Feature&quot;)<br><br>fig.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*fptciGrScRS-8_66ne0P5A.png" /></figure><p>Looking at the bar chart, keep in mind that the variance values on the axis represent squared dollars, which is why they reach up to 80 billion. Here we see that &quot;assets&quot; stands out as the feature with the highest variance, followed by &quot;NFIN&quot; (likely related to financial net worth), and then other familiar metrics like &quot;net worth&quot; and &quot;debt.&quot;</p><p>This chart suggests something interesting: some features, especially wealth indicators like &quot;financial assets,&quot; may be influenced by a few ultra-wealthy individuals. High-wealth outliers—think of billionaires—could be skewing our data. Before proceeding, let’s examine the distribution of these features to check for potential outliers.</p><p>A histogram or box plot would work well for this purpose. Let’s create a box plot using Plotly Express.</p><p>We’ll start by looking at the distribution of &quot;NHNFIN,&quot; which represents non-home, non-financial assets. Examples of these assets include items like automobiles, commercial properties, businesses, or even collectible items like a rare Pokemon card collection.</p><pre>fig = px.box(<br>    data_frame = df,<br>    x = &quot;NHNFIN&quot;,<br>    title = &quot;Distribution of Non-home, Non-Financial Assets&quot;<br>    )<br>fig.update_layout(xaxis_title = &quot;Value [$]&quot;)<br><br>fig.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*knNM-vuDkYOThoeFVcX3fQ.png" /></figure><p>The box plot reveals a significant right skew. The main body of the box (representing 75% of our data) falls well below $1 million, while the whisker extends to capture about 95% of the data, still far below the $2 million mark on the chart. However, a few individuals with substantial non-home, non-financial assets are skewing the distribution to the right.</p><p>This skew impacts our variance calculation. The presence of just a few extreme values significantly increases variance, even though most of the data is clustered at much lower values. Ideally, we want to find features with variances that reflect a more balanced distribution, giving a clearer view of the typical patterns in the data.</p><p>To achieve this, instead of using standard variance, we’ll switch to trimmed variance, which reduces the impact of outliers.</p><p>In trimmed variance, we calculate the variance only on the middle portion of the data by excluding extreme values at both ends. For example, if we want to focus on the middle 80%, we remove the top 10% and the bottom 10% of data points before calculating variance.</p><p>Let’s demonstrate this with our &quot;debt&quot; feature. Normally, we’d use the `.var()` method in Pandas, but since Pandas doesn’t have a built-in trimmed variance function, we’ll use the `trimmed_var` function from the SciPy library.</p><pre>trimmed_var(df[&quot;DEBT&quot;])<br></pre><pre>3089864647.655702<br></pre><p>Applying this to our &quot;debt&quot; feature shows a significantly lower trimmed variance compared to the standard variance, confirming that we’ve minimized the impact of extreme outliers. However, to apply trimmed variance across multiple columns, we use Pandas’ `.apply()` method, which allows us to efficiently apply this function across all columns in the DataFrame. We also pass in our list of values and specify limits—here, `0.1` for both ends, which sets our middle 80% focus.</p><p>After calculating the trimmed variance for each feature, we can sort these values, just as we did with regular variance, and retrieve the top 10.</p><pre>top_ten_trim_var = df.apply(<br>            trimmed_var, limits=(0.1,0.1)).sort_values().tail(10)<br>top_ten_trim_var<br></pre><pre>	              0<br>WAGEINC	        5.550737e+08<br>HOMEEQ	        7.338377e+08<br>NH_MORT	        1.333125e+09<br>MRTHEL	        1.380468e+09<br>PLOAN1	        1.441968e+09<br>DEBT	        3.089865e+09<br>NETWORTH	3.099929e+09<br>HOUSES	        4.978660e+09<br>NFIN	        8.456442e+09<br>ASSET	        1.175370e+10<br><br>dtype: float64<br></pre><p>Interestingly, we see some familiar features, like &quot;assets,&quot; but also new ones, indicating that trimmed variance might reveal more relevant features for our model.</p><p>With our trimmed variances calculated, let’s create a horizontal bar chart to visually compare them.</p><pre>fig = px.bar(<br>    x = top_ten_trim_var,<br>    y = top_ten_trim_var.index,<br>    title = &quot;SCF: High Variance Features&quot;<br>    )<br><br>fig.update_layout(xaxis_title =&quot;Trimmed Variance&quot;, yaxis_title=&quot;Feature&quot;)<br><br>fig.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*-tyzEtLnl4BJM5XHoPUDUw.png" /></figure><p>A few changes stand out. Some features from our previous chart, like non-home non-financial assets, are no longer present, indicating that outlier trimming significantly altered the variance distribution. Notably, the variance values are much lower than before—down from 80 billion to around 12 billion—showing the strong impact of trimming.</p><p>The top five features, however, remain distinctly higher in variance compared to the others. These include “assets,” “non-financial assets” (which could include homes or businesses), “house value,” “net worth,” and “debt.” These features are not only high in variance but are also intuitively meaningful, making them ideal candidates for our model.</p><p>Based on this analysis, focusing on these five features should provide a strong foundation for building our model.</p><p>So now, we need to extract the names of these top 5 columns and store them in a list for our feature matrix.</p><p>Starting with our `top_10_trimmed_var` Series, let’s apply a few transformations to get the data in the format we need. First, we’ll select the bottom 5 entries (which represent the highest trimmed variances) by using `.tail(5)`.</p><p>Next, we only need the column names, not the variance values themselves. To achieve this, we’ll extract the index labels from the Series—these labels represent the feature names we’ll use for our feature matrix.</p><pre>high_var_cols = top_ten_trim_var.tail(5).index.to_list()<br>high_var_cols<br></pre><pre>[&#39;DEBT&#39;, &#39;NETWORTH&#39;, &#39;HOUSES&#39;, &#39;NFIN&#39;, &#39;ASSET&#39;]<br></pre><h4>1.3. Split</h4><p>With our top 5 high-variance features identified, we’re ready to create our feature matrix. The names of these high-variance columns are already stored in the variable `high_var_cal`.</p><pre>X = df[high_var_cols]<br>print(&quot;X shape:&quot;, X.shape)<br>X.head()<br></pre><pre>X shape: (4418, 5)<br><br>	DEBT	   NETWORTH	HOUSES	NFIN	 ASSET<br>5	12200.0	   -6710.0	0.0	3900.0	 5490.0<br>6	12600.0	   -4710.0	0.0	6300.0	 7890.0<br>7	15300.0	   -8115.0	0.0	5600.0	 7185.0<br>8	14100.0	   -2510.0	0.0	10000.0	 11590.0<br>9	15400.0	   -5715.0	0.0	8100.0	 9685.0<br></pre><p>Now, we&#39;re officially entering the fifth dimension, so let&#39;s begin building our model.</p><h3>2. Build Model</h3><h4>2.1. Iterate</h4><p>As mentioned earlier, this model will be similar to what we built in the previous part, as we’re still using a K-means clustering model. However, there’s a critical difference to keep in mind.</p><p>We’re now working in a multi-dimensional space, and as we discussed, the &quot;curse of dimensionality&quot; means that as data points move into higher dimensions, they become more spread out. This can make clustering challenging. Additionally, the five features we&#39;re using have very different scales—for example, &quot;assets&quot; might reach up to 12 billion, while &quot;debt&quot; is closer to 2 billion. These scale differences can impact our model’s performance.</p><p>To address both of these issues, we’ll use a technique called standardization, which will rescale our features to have a common scale. We can do this with scikit-learn, but let’s first build an intuition for standardization with some preliminary calculations using Pandas.</p><p>Our goal here is to create a DataFrame that displays the mean and standard deviation of each feature in our feature matrix. If we were working with a single feature, we could simply use `mean()`. For all columns in `X`, we want both means and standard deviations, so we&#39;ll perform multiple aggregations using Pandas’ `aggregate()` method. By specifying `mean` and `std` (for standard deviation), we get a DataFrame with these statistics for each feature—remember, standard deviation is the square root of variance.</p><pre>X_summary = X.aggregate([&quot;mean&quot;,&quot;std&quot;]).astype(int)<br>X_summary<br></pre><pre>	DEBT	NETWORTH	HOUSES	NFIN	ASSET<br>mean	72701	76387	        74530	117330	149089<br>std	135950	220159	        154546	239038	288166<br></pre><p>This DataFrame gives us a baseline for each feature’s mean and standard deviation before standardization. Keep these values in mind, as we’ll see changes after applying standard scaling with scikit-learn.</p><p>Now it’s time to standardize them so they all have a common mean and standard deviation—putting them on the same scale. To achieve this, we’ll use `StandardScaler` from scikit-learn, a type of transformer designed specifically for this task. But before diving into the implementation, let’s briefly discuss the math behind it to understand how it works.</p><p>To standardize a feature, let’s take one of our columns—for example, &quot;debt,&quot; which we’ll refer to as x.</p><pre>x = X[&quot;DEBT&quot;]<br>print(&quot;mean&quot;, round(x.mean()))<br>print(&quot;std&quot;, round(x.std()))<br></pre><pre>mean  72701<br>std   135950<br></pre><p>Standard scaling involves two steps:</p><p>1. Subtract the mean of x from each value in the column.<br>2. Divide the result by s, the standard deviation of x (where standard deviation is the square root of variance).</p><pre>x_scaled = (x - x.mean()) / x.std() <br></pre><p>After applying this transformation, the resulting values will have a mean of zero and a standard deviation of one.</p><pre>print(&quot;mean&quot;, round(x_scaled.mean()))<br>print(&quot;std&quot;, round(x_scaled.std()))<br><br></pre><pre>mean 0<br>std  1<br></pre><p>This transformation ensures that each feature contributes equally to the model, regardless of its original scale.</p><p>Now, let’s implement this using scikit-learn’s `StandardScaler`.</p><pre># Instantiate transformer<br>ss = StandardScaler()<br><br># Transform `X`<br>X_scaled_data = ss.fit_transform(X)<br><br># Put `X_scaled_data` into DataFrame<br>X_scaled = pd.DataFrame(X_scaled_data, columns=X.columns)<br><br>print(&quot;X_scaled shape:&quot;, X_scaled.shape)<br>X_scaled.head()<br></pre><pre>X_scaled shape: (4418, 5)<br><br>	DEBT	        NETWORTH	HOUSES	        NFIN	        ASSET<br>0	-0.445075	-0.377486	-0.48231	-0.474583	-0.498377<br>1	-0.442132	-0.368401	-0.48231	-0.464541	-0.490047<br>2	-0.422270	-0.383868	-0.48231	-0.467470	-0.492494<br>3	-0.431097	-0.358407	-0.48231	-0.449061	-0.477206<br>4	-0.421534	-0.372966	-0.48231	-0.457010	-0.483818<br></pre><p>And here we have our scaled data! Notice that these values look quite different from the original ones. To confirm our standardization, we can verify that the mean is now zero and the standard deviation is one for each feature.</p><pre>X_scaled_summary = X_scaled.aggregate([&quot;mean&quot;,&quot;std&quot;]).astype(int)<br>X_scaled_summary<br><br></pre><pre>	DEBT	NETWORTH	HOUSES	NFIN	ASSET<br>mean	0	0	        0	0	0<br>std	1	1	        1	1	1<br><br></pre><p>And there we go—five features with means of zero and standard deviations of one, just as we wanted.</p><p>One quick note: we won’t be using this `StandardScaler` alone. Instead, we’ll create a pipeline where the first step will be standard scaling and the second step will be our K-Means model. Pipelines keep everything organized and allow us to easily tune our model, including finding the optimal number of clusters.</p><p>We&#39;ll iterate through cluster counts from 2 to 12. First, we initialize lists to store inertia and silhouette scores. In each loop iteration, we build the model pipeline with a standard scaler followed by K-means, setting the number of clusters to K and fixing the random state for reproducibility.</p><p>After fitting the model, we retrieve the inertia score from the K-means step in the pipeline and append it to the inertia list. Similarly, we calculate the silhouette score by passing the data and cluster labels from the model into the silhouette score function, appending the result to the silhouette scores list.</p><pre>n_clusters = range(2,13)<br>inertia_errors = []<br>silhouette_scores = []<br><br># Add `for` loop to train model and calculate inertia, silhouette score.<br>for k in n_clusters:<br>    #Build model<br>    model = make_pipeline(<br>        StandardScaler(),<br>        KMeans(n_clusters=k, random_state=42, n_init=10)<br>        )<br>    #Train model<br>    model.fit(X)<br><br>    #Calculate inertia<br>    inertia_errors.append(model.named_steps[&#39;kmeans&#39;].inertia_)<br><br>    #Calculate silhouette score<br>    silhouette_scores.append(<br>        silhouette_score(X, model.named_steps[&#39;kmeans&#39;].labels_)<br>        )<br><br><br>print(&quot;Inertia:&quot;, inertia_errors[:3])<br>print()<br>print(&quot;Silhouette Scores:&quot;, silhouette_scores[:3])<br><br></pre><pre>Inertia: [11028.058082607145, 7190.526303575355, 5923.0831522361805]<br><br>Silhouette Scores: [0.7464502937083215, 0.7044601307791996, 0.6928096095443212]<br></pre><p>After training our model with different values of K, we’ll examine our metrics to identify the best cluster count, starting with inertia. Using Plotly Express, we’ll create an elbow plot, plotting the number of clusters on the X-axis and inertia values on the Y-axis.</p><pre>fig = px.line(<br>    x=n_clusters, y=inertia_errors, title=&quot;K-Mean Model: Inertia vs Number of Clusters&quot;<br>    )<br><br>fig.update_layout(xaxis_title=&quot;Number of Clusters&quot;, yaxis_title=&quot;Inertia&quot;)<br><br>fig.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*a8ABL52gQ1d4r5xKgWe8-g.png" /></figure><p>From this plot, we’ll look for an elbow point, estimating an optimal K around 4 or 5.</p><p>Next, let’s check the silhouette scores to confirm.</p><pre>fig = px.line(<br>    x=n_clusters, y=silhouette_scores, title=&quot;K-Means Model: Silhouette Score vs Number of Clusters&quot;<br>    )<br>fig.update_layout(xaxis_title=&quot;Number of Clusters&quot;, yaxis_title=&quot;Silhouette score&quot;)<br>fig.show()<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*t0Y_MF6Uuc9kXPn9ZZv5yw.png" /></figure><p>Looking at the plot, the best silhouette score appears around 3 or 4 clusters. Since the inertia suggested 4 or 5 and the silhouette score suggests 3 or 4, we’ll select 4 as the final number of clusters.</p><p>Now, let’s build our final model, similar to those from our loop. We’ll start with `make_pipeline`, using a standard scaler followed by K-means clustering with `n_clusters=4` and `random_state=42`. Then, we’ll fit the model to `X`.</p><pre>final_model = make_pipeline(<br>    StandardScaler(),<br>    KMeans(n_clusters=4, random_state=42, n_init=10)<br>)<br>final_model.fit(X)<br></pre><h3>3. Communication Results</h3><p>We’ve built our final model, and now it’s time to move on to the communication stage. First, we’ll create a side-by-side bar chart, but we need to complete a couple of steps before the visualization.</p><p>We need to extract the labels from our model and create a DataFrame with the centroids (mean values) for our clusters.</p><pre>labels = final_model.named_steps[&quot;kmeans&quot;].labels_<br>print(labels[:5])<br><br></pre><pre>[0 0 0 0 0]<br></pre><p>Next, we’ll use them to get the centroids for our clusters, specifically the mean values for debt, net worth, house value, non-financial assets, and total assets.</p><p>we’ll use the groupby() and mean() methods to calculate the mean values for each feature by cluster.</p><pre>xgb = X.groupby(labels).mean()<br>xgb<br></pre><pre>	DEBT	        NETWORTH	HOUSES	        NFIN	        ASSET<br>0	25665.964836	13034.856146	12545.074106	2.593056e+04	3.870082e+04<br>1	125225.084034	920962.294118	276268.907563	7.395056e+05	1.046187e+06<br>2	214142.237674	165474.424779	250706.068268	3.220454e+05	3.796167e+05<br>3	725213.134328	778260.298507	819776.119403	1.289561e+06	1.503473e+06<br></pre><p>Now that we’ve extracted our mean household finance numbers, let&#39;s create a side-by-side bar chart to spot differences among our four groups.</p><p>We’ll use Plotly Express to start with `px.bar()` and specify the `xgb` DataFrame. However, the output is a stacked bar chart, which makes comparisons difficult. To fix this, I’ll add the argument `bar_mode=’group’`.</p><pre>fig = px.bar(<br>    xgb,<br>    barmode=&quot;group&quot;,<br>    title=&quot;Mean Household Finances by Cluster&quot;<br>)<br>fig.update_layout(xaxis_title=&quot;Cluster&quot;, yaxis_title=&quot;Value [$]&quot;)<br>fig.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*EGE03b-Di0v7TUPlavLt8g.png" /></figure><p>Now, the chart looks good. Focusing on the relationship between home value (green) and total assets (orange), we notice that in cluster 0, about 50% of total assets are in home value. Comparing with cluster 3, we see similar proportions, while cluster 1 has a higher percentage in home value. Interestingly, cluster 2 shows a smaller proportion in home value, indicating wealth is distributed among various non-financial assets, resulting in higher net worths.</p><p>With the centroids and side-by-side bar chart completed, our next step is to create a scatter plot of our clusters. However, our model’s data has five features, meaning our clusters exist in a five-dimensional space, which we cannot visualize directly. Generally, scatter plots are best when they are two-dimensional.</p><p>To address this, we can use dimensionality reduction, specifically Principal Component Analysis (PCA). PCA reduces the information from five dimensions into two while preserving as much information as possible.</p><p>To illustrate how PCA works, let&#39;s consider an art task: draw a bicycle. Although a bicycle exists in three dimensions, you will create a two-dimensional representation, effectively performing dimensionality reduction with your mind.</p><p>After drawing, drawn from the side, which captures more information about the object compared to a front view that may be less clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7r09hrAATBHr25bLvrWsg.png" /></figure><p>This thought process mirrors PCA, where an algorithm reduces the dimensionality of a dataset while maintaining information. PCA is considered unsupervised learning because there’s no target; you, as the data scientist, specify how many dimensions you want, and PCA handles the rest.</p><p>PCA is commonly used in model building, particularly when dealing with a wide dataset with many features, which can hinder model performance. By transforming the data with PCA, you obtain a reduced feature matrix that can be used in predictors like random forests or clustering algorithms.</p><p>Now, let’s implement PCA. We’ll start by instantiating our PCA transformer with two components, as we want a two-dimensional plot, and set the random state to 42.</p><p>Next, we’ll transform our feature matrix, `X`, using `fit_transform()`, and verify the output. If successful, we’ll create a DataFrame from the transformed data, which now has two columns representing the x and y coordinates.</p><p>It’s important to note that while we reduce dimensions, we lose some specificity. Each of our five original dimensions had specific meanings, but the two principal components will not carry the same clarity. Therefore, we’ll label the columns as `PC1` and `PC2` for principal components.</p><pre># Instantiate transformer<br>pca = PCA(n_components=2, random_state=42)<br><br># Transform `X`<br>X_t = pca.fit_transform(X)<br><br># Put `X_t` into DataFrame<br>X_pca = pd.DataFrame(X_t, columns= [&quot;PC1&quot;,&quot;PC2&quot;])<br><br>print(&quot;X_pca shape:&quot;, X_pca.shape)<br>X_pca.head()<br><br></pre><pre>X_pca shape: (4418, 2)<br><br>	PC1	        PC2<br>0	-221525.424530	22052.273003<br>1	-217775.100722	22851.358068<br>2	-219519.642175	19023.646333<br>3	-212195.720367	22957.107039<br>4	-215540.507551	20259.749306<br></pre><p>Now that we’ve compressed our 5-dimensional data into 2 dimensions, it’s time to create a scatter plot. We’re in task 6320, and we’ll use Plotly Express for this.</p><p>First, let&#39;s initialize the scatter plot with `PX.scatter`. The first argument is the data frame from the previous task, followed by specifying the x and y coordinates, which will be `PC1` and `PC2`. Next, we&#39;ll set the color, corresponding to our labels, and the title as &quot;PCA Representation of Clusters.&quot;</p><pre>fig = px.scatter(<br>    data_frame=X_pca,<br>    x= &quot;PC1&quot;,<br>    y=&quot;PC2&quot;,<br>    color=labels.astype(str),<br>    title= &quot;PCA Representation of Clusters&quot;<br>)<br>fig.update_layout(xaxis_title=&quot;PC1&quot;, yaxis_title=&quot;PC2&quot;)<br><br>fig.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*LwJx7O4yjlZOCsQDRe4FaA.png" /></figure><p>Now, let&#39;s interpret the results. As we move from cluster 0 to cluster 3, we see an increase in assets. Cluster 0, positioned at the origin, represents households with the fewest assets, while clusters 2 and 3 contain households with significantly higher assets.</p><p>It&#39;s important to note that most households fall within the first two groups, indicating that only a small portion has millions in assets.</p><p>The distinction between clusters 2 and 3 primarily relates to home value. Cluster 2 consists of families with high net worth but lower home values, while cluster 3 represents those with both high assets and high home values.</p><h3>Conclusion</h3><p>In summary, we started with 351 features and calculated the variance to determine the best 5 features for our unsupervised model. We applied hyperparameter tuning to our K-Means estimator, concluding that 4 clusters provided the best fit. After analyzing the mean characteristics of each cluster, we reduced the dimensions from 5 to 2 using PCA and created our scatter plot.</p><p>Great job today! We covered a lot of concepts and math. In the next lesson, we’ll create an interactive web app to make this data accessible to everyone, regardless of their data science skills. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=093ab032bc73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Segmenting Households with K-Means: Unveiling Clusters in Credit-Fearful Data]]></title>
            <link>https://medium.com/@sawsanyusuf/segmenting-households-with-k-means-unveiling-clusters-in-credit-fearful-data-c9e8b6edfb3b?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9e8b6edfb3b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[kmeans-clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 14:16:57 GMT</pubDate>
            <atom:updated>2024-10-25T14:16:57.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-KD7tK2Ic7MQpfUUFs3DA.jpeg" /></figure><p>Welcome to part two of Project Five. In the previous lesson, we explored data from the Survey of Consumer Finances, focusing on households we’ve labeled as &quot;credit-fearful.&quot; These are households that were either denied credit or feared being turned down.</p><p>In this session, we’ll build an unsupervised machine learning model to segment these households into distinct groups, or &quot;clusters.&quot; Finally, we’ll analyze these clusters to uncover any meaningful insights. Let’s dive into the details.</p><p>Today, we&#39;ll construct a k-means clustering model, our tool for this session. Here&#39;s a breakdown of our goals: We’ll begin by subsetting the data to focus specifically on credit-fearful households. Next, we’ll briefly examine the relationship between household debt and home values. Then, we’ll build our k-means model to segment households into clusters. Lastly, we’ll analyze the average characteristics of each cluster.</p><p>As we work through this project, we’ll follow our usual machine-learning workflow with some key differences. Unlike previous projects where we used supervised learning for classification or regression, today we’ll focus on unsupervised learning for clustering. One major difference is that we don&#39;t have a target vector in unsupervised learning—only a feature matrix.</p><p>When building the model, instead of the multiple steps we used in supervised learning (baseline, iterate, evaluate), we’ll focus only on the iteration step, where we’ll choose the number of clusters and refine the model accordingly.</p><p>Once the model is built, we’ll communicate the results by:<br>1. Extracting the cluster centroids—essentially, the center points of each cluster.<br>2. Creating side-by-side bar charts to compare the characteristics of the different clusters easily.</p><p>Key terms to keep in mind as we progress include clusters (groups of data points, i.e., households), centroids (the center of a cluster), inertia, and silhouette score (metrics used to evaluate the quality of the clusters).</p><p>We’ll be using familiar libraries such as Matplotlib for visualization, Pandas for data manipulation, and Seaborn for additional visualization. Our new addition today is the k-means clustering algorithm, along with metrics like inertia and silhouette score to evaluate the model’s performance.</p><p>Additionally, we’ll use custom widgets—the Cluster Widget and the Survey of Consumer Finances (SCF) Cluster Widget—to visualize how the k-means algorithm works.</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import seaborn as sns<br>from sklearn.cluster import KMeans<br>from sklearn.metrics import silhouette_score</pre><p>With that overview, let’s get started!</p><h3>1. Prepare Data</h3><h4>1.1. Import</h4><p>Now it&#39;s time to build our wrangle function. We aim to create a function that accepts a file path from the user, loads the corresponding file into a DataFrame, and filters it to focus solely on credit-fearful households—those where the `TURNFEAR` column equals 1.</p><p>Here’s how we can accomplish that. Let’s start by defining the wrangle function and utilizing a bit of Pandas. First, we’ll create a DataFrame (I&#39;ll call it `df`) using the `read_csv()` method, passing in the `filepath` argument provided by the user. This will load the CSV file into our DataFrame.</p><p>Next, we’ll create a mask to filter the dataset to only include credit-fearful households. We can do this by referencing the `TURNFEAR` column and applying a condition where its value equals 1. Finally, we’ll apply the mask to subset the DataFrame and return the filtered result.</p><pre>def wrangle(filepath):<br>    df=pd.read_csv(filepath)<br>    mask=df[&quot;TURNFEAR&quot;] == 1<br>    df = df[mask]<br>    <br>    return df</pre><p>Now, you can use this `wrangle` function to load the compressed CSV file we’re using for this project and filter it into a DataFrame for further analysis.</p><pre>df = wrangle(&quot;SCFP2019.csv&quot;)<br>print(df.shape)<br>df.head()</pre><pre>       YY1 Y1 WGT         HHSEX AGE AGECL EDUC EDCL MARRIED KIDS ... NWCAT INCCAT ASSETCAT        NINCCAT NINC2CAT NWPCTLECAT INCPCTLECAT NINCPCTLECAT INCQRTCAT NINCQRTCAT<br>5       2  21 3790.476607 1     50   3      8    2    1        3 ... 1       2        1              2       1         1         4           4              2         2<br>6       2  22 3798.868505 1     50   3      8    2    1        3 ... 1       2        1              2       1         1         4           3              2         2<br>7       2  23 3799.468393 1     50   3      8    2    1        3 ... 1       2        1              2       1         1         4           4              2         2<br>8       2  24 3788.076005 1     50   3      8    2    1        3 ... 1       2        1              2       1         1         4           4              2         2<br>9       2  25 3793.066589 1     50   3      8    2    1        3 ... 1       2        1              2       1         1         4           4              2         2<br><br>5 rows × 351 columns</pre><h4>1.2. Explore</h4><p>After loading our data into a DataFrame using the wrangle function, it’s time to do some exploration. Specifically, I want to examine the relationship between home value and household debt for credit-fearful households.</p><p>To visualize this, we&#39;ll create a scatterplot with household debt on the x-axis and home value on the y-axis. This will help us determine whether there’s a relationship between these two variables and whether we can visually identify any clusters among the data points. We&#39;ll use Seaborn to build this scatterplot.</p><pre># Plot &quot;HOUSES&quot; vs &quot;DEBT&quot;<br>sns.scatterplot(x= df[&quot;DEBT&quot;], y=df[&quot;HOUSES&quot;])<br>plt.xlabel(&quot;Household Debt [$1M]&quot;)<br>plt.ylabel(&quot;Home Value [$1M]&quot;)<br>plt.title(&quot;Credit-Fearfull: Home Value vs. Household Debt&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*PScK21CpXQHBiVieZnCf6A.png" /></figure><p>Once we generate the plot, it looks great overall. However, one issue stands out—the x and y-axis labels are difficult to interpret. For example, the x-axis shows floating point numbers like 0.25 or 0.5, but the scale is in the tens of millions, making it unclear. The label &quot;0.25&quot; represents 2.5 million, but the formatting isn&#39;t intuitive.</p><p>To fix this, we’ll perform a simple data transformation to make the plot more readable. Specifically, we’ll scale both debt and home value by dividing them by one million. This will allow us to display values in millions, making the chart more legible. Instead of manually writing out &quot;1,000,000,&quot; we can simplify the code by using scientific notation (`1e6`), which represents 10^6.</p><pre># Plot &quot;HOUSES&quot; vs &quot;DEBT&quot;<br>sns.scatterplot(x= df[&quot;DEBT&quot;] / 1e6, y=df[&quot;HOUSES&quot;]/ 1e6)<br>plt.xlabel(&quot;Household Debt [$1M]&quot;)<br>plt.ylabel(&quot;Home Value [$1M]&quot;)<br>plt.title(&quot;Credit-Fearfull: Home Value vs. Household Debt&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*EJGCaPNZA2-I9SOS2lZyLw.png" /></figure><p>By applying this transformation and rerunning the plot, we now have clearer labels, such as 2.5 million, which are easier to interpret. This makes the data much more understandable at a glance.</p><p>Interestingly, even without a clustering algorithm, we can already start to identify potential groups. One group appears to have very high home values and large amounts of debt, both in the tens of millions. Another group seems to have lower home values and smaller debt loads. There’s also a group in between, though it’s unclear if this is a single group or multiple smaller clusters.</p><p>Visually, it’s clear that natural clusters are forming in the data. When we move to the model-building phase, we’ll compare our visual impressions to the results from the k-means clustering algorithm. But before that, our next step is to split the data into a feature matrix.</p><h4>1.3. Split</h4><p>We’ve explored the relationship between household debt and home value for our credit-fearful families, and now it’s time to create our feature matrix by splitting the data.</p><p>Remember, with unsupervised learning, we don’t have a target variable (little y). We’re only working with the feature matrix (big X). So in this step, we’ll just be focusing on creating that feature matrix.</p><pre># Create the feature matrix X<br>X = df[[&quot;DEBT&quot;, &quot;HOUSES&quot;]]<br>print(X.shape)<br>X.head()</pre><pre>(4623, 2)<br><br>	DEBT	  HOUSES<br>5	12200.0	   0.0<br>6	12600.0	   0.0<br>7	15300.0	   0.0<br>8	14100.0	   0.0<br>9	15400.0	   0.0</pre><p>Our new DataFrame, big X, still contains the same number of observations—4,623 rows. However, instead of the original 300+ features, we’ve now reduced it to just two: debt and home value. This means we’re finished with data preparation.</p><p>Next, we’ll move on to building the model, where we’ll discuss unsupervised learning in more detail and dive into how the k-means algorithm works.</p><h3>2. Build Model</h3><h4>2.1. Iterate</h4><p>Now that we’ve prepared our data, let’s discuss the model we’ll be using and how it fits into the broader field of machine learning.</p><p>At the start of this article, I mentioned that clustering is a form of unsupervised learning. So, what&#39;s the difference between unsupervised and supervised learning? In our previous projects, we focused on supervised learning, but this project will center on unsupervised learning.</p><p>In supervised learning, the data used to train the model has two parts: a feature matrix (often called &quot;X&quot;) and a target vector (referred to as &quot;y&quot;). The target is what the model is trained to predict. However, in unsupervised learning, we still have a feature matrix, but there’s no target vector. For instance, in this project, there are no predefined groups that these credit-fearful households belong to. So, unlike our earlier classification models (e.g., in Project Four), where we knew each company was either bankrupt or not bankrupt (a clear target), we can’t do the same here. Without predefined labels, we can’t use classification techniques.</p><p>Instead, we turn to clustering. In clustering, we build a model that groups the households in our dataset based on their proximity to one another. It&#39;s similar to what we did in our data exploration phase when we manually circled data points that were close together. Points that are near each other will end up in the same cluster, while those far apart will be placed in different clusters. The goal is that the differences between these clusters will help us make meaningful distinctions between the households.</p><p>The algorithm we’ll use for clustering is called <strong>K-means</strong>. The &quot;k&quot; refers to the number of clusters we ask the algorithm to create. Think of this as a hyperparameter—something we need to decide before training the model. In supervised learning, the number of groups (or classes) is usually predefined, like in Project Four, where companies were classified as either bankrupt or not bankrupt. Here, we have to determine the number of clusters ourselves.</p><p>We’ll explore strategies for selecting the number of clusters later, but for now, let’s focus on how the k-means algorithm works. We’ll start with a general example using a cluster widget to walk through the different steps.</p><p>In this example, let’s assume we want to create three clusters. Keep in mind that this is just a toy example, so the x-axis and y-axis don’t represent any specific features. This is just a way to visualize the process.</p><p>In <strong>Step 0</strong>, we initialize the algorithm by placing three centroids (one for each cluster) randomly in the space. A centroid is simply the center point of a cluster. At this point, the centroids aren’t close to any data points because their positions are randomly chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r85krD_PHVSYm6haj_k6Rg.jpeg" /></figure><p>In <strong>Step 1</strong>, each data point is assigned to the nearest centroid, forming initial clusters. As I move the slider from Step 0 to Step 1, you’ll see the data points get color-coded based on the cluster they belong to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSTzoDx3zjTTbXM_FeEjbQ.jpeg" /></figure><p>In <strong>Step 2</strong>, the centroids are recalculated by finding the average location of all the points in each cluster. This is where the &quot;means&quot; in K-means comes into play. If I move the slider from Step 1 to Step 2, you’ll see the centroids shift to their new positions based on the mean of their assigned points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttCoS7HSxBlankN0kUkV6g.jpeg" /></figure><p>From there, we repeat this process: assigning data points to the nearest centroid and recalculating the centroids. Moving from Step 2 to Step 3, you&#39;ll notice slight changes in cluster assignments, followed by another recalculation of centroids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDti1o2TRhz79dleo2mUxA.jpeg" /></figure><p>We continue this process until the centroids stabilize and no longer move significantly from iteration to iteration.</p><p>By the final step, you&#39;ll see that the algorithm has divided the data into three clusters, each with its corresponding centroid. At this point, the centroids have stopped moving, and the algorithm concludes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yl93N5py0mgwGRhho-YCqA.jpeg" /></figure><p>This is how the K-means algorithm works in practice. It’s important to remember that clustering is a type of unsupervised learning, and unlike supervised learning, there&#39;s no target variable guiding the process.</p><p>Now that we’ve gone through this general example, let’s move on to apply this algorithm to our dataset, the <strong>Survey of Consumer Finances (SCF)</strong> data we’ve been working on within this project, instead of toy data.</p><p>This tool is called the SCF Cluster Widget, and I’ve passed in three parameters: `x` for debt along the x-axis, `y` for home value along the y-axis, and the number of clusters, which is set to three. We’re telling the algorithm to group the data into three clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrsWrM-shprr3xJwwKP9-g.jpeg" /></figure><p>The result looks similar to the previous widget but with some key differences. Notice that there are two scatter plots displayed. While they both represent the same data—home value versus debt—the scales on the x and y axes are different. On the left plot, the scale is in millions of dollars, while the plot on the right shows a <strong>log transformation</strong>. The log transformation helps spread out data points that were previously grouped in the lower-left corner of the left plot, giving us a clearer view of the distribution of the data.</p><p>Now that we’re familiar with the layout, let’s walk through the clustering process again. We start at <strong>Step 0</strong>, where the centroids are randomly assigned. You can see the initial centroid positions on both plots.</p><p>Next, we move to <strong>Step 1</strong>, where each data point is assigned to the nearest centroid. As I transition from Step 0 to Step 1, you’ll notice the data points change color, indicating that they’ve been assigned to a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qyuX8iKSMKjKn2FVTYDzA.jpeg" /></figure><p>In <strong>Step 2</strong>, the algorithm recalculates the centroids based on the mean of all data points in each cluster. If I move the slider to Step 2, you’ll see the centroids shift—sometimes by a significant amount—indicating the new average positions for each cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ws6BwsRsBCojdFlLvOGpwg.jpeg" /></figure><p>After that, the process repeats: the data points are reassigned to clusters based on the updated centroids, and the centroids are recalculated again. We continue this cycle of reassigning points and adjusting centroids until the clusters stabilize. I’ll skip ahead to Step 8, where the centroids have stopped moving significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrbGS0qzb7-ogNymkk5ohw.jpeg" /></figure><p>At this point, we have three distinct clusters with their respective centroids. What&#39;s interesting here is that these clusters closely resemble the ones we initially identified through visual exploration earlier in this article. However, in this case, we didn&#39;t manually identify the clusters—the K-means algorithm did it for us. This is a good confirmation that the algorithm is working well on this dataset.</p><p>Now that we have a solid understanding of how the K-means algorithm works and how it groups the data, it’s time to apply our Scikit-learn skills and build the K-means model.</p><p>First, we need to instantiate the K-means model. We already imported the `KMeans` class at the beginning of the article, so let&#39;s get started. There are two key arguments we need to pass in.</p><p>The first is the number of clusters. Since this is unsupervised learning, we have to specify how many clusters we want the algorithm to create. For now, we’ll set this to three, allowing us to observe how the algorithm performs.</p><p>The second argument is the random state. Remember, the centroids are initialized randomly in Step 0, so to ensure that our results are reproducible, we’ll set the random state to 42.</p><pre>model = KMeans(n_clusters=3, random_state=42, n_init=10)</pre><p>Now, let’s train the model. Since this is unsupervised learning, we only have the feature matrix (big X) and no target vector (no little y).</p><pre>model.fit(X)</pre><p>Now that we’ve trained our model, the next step is to extract the cluster labels. These labels represent the specific cluster each data point has been assigned to by the model.</p><p>To extract these labels, we&#39;ll start with the model we just created. In Scikit-learn, we access the labels using the attribute `labels_` (note the underscore at the end). This underscore indicates that this attribute is only available after the model has been trained.</p><pre>labels = model.labels_<br>labels[:10]</pre><p>Let’s take a look at the first 10 labels. For example, our model has assigned these observations to Cluster 0. As we scroll through more observations, it seems that many of them are also assigned to Cluster 0, indicating some consistency in this initial output.</p><pre>array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)</pre><p>Now that we have the labels, the next step is to combine them with the scatter plot we created earlier. By color-coding the data points according to their assigned clusters, we can visually explore how well the model has segmented our data.</p><p>Before we dive in, let&#39;s quickly review the previous scatter plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*EJGCaPNZA2-I9SOS2lZyLw.png" /></figure><p>It looks nice, but we&#39;re missing color to distinguish between the clusters. So, let&#39;s fix that and also tidy up the code for better readability. I&#39;ll separate the `x` and `y` values onto different lines, making the code cleaner.</p><p>Next, we’ll add a few key arguments. First, I’ll use the `hue` argument to color-code the scatter plot based on the cluster labels. In this case, we’ve already defined the labels, so I’ll pass them in. Then, for aesthetic purposes, I’ll specify a color palette—I like to use the `deep` palette.</p><pre># Plot &quot;HOUSES&quot; vs &quot;DEBT&quot; with hue=label<br>sns.scatterplot(<br>    x=df[&quot;DEBT&quot;]/1e6,<br>    y=df[&quot;HOUSES&quot;]/1e6,<br>    hue=labels,<br>    palette=&quot;deep&quot;<br>    )<br>plt.xlabel(&quot;Household Debt [$1M]&quot;)<br>plt.ylabel(&quot;Home Value [$1M]&quot;)<br>plt.title(&quot;Credit-Fearfull: Home Value vs. Household Debt&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Ye03ibYtZXwDKWj1HEDvDw.png" /></figure><p>Now, we can see a clear, color-coded scatter plot with our three clusters, showing which data points belong to each cluster based on their color. It looks great! The final touch is to add the centroids—those stars representing the center points of each cluster.</p><p>Let&#39;s extract those centroids from our model and add them to the plot. The process is similar to how we pulled out the labels earlier. To do this, we&#39;ll access the centroids from the model using `model.cluster_centers_`.</p><pre>centroids = model.cluster_centers_<br>centroids</pre><pre>array([[91017.57766674, 116150.29328698],<br>       [18384100.   ,         34484000.],<br>       [5065800.     ,11666666.66666667]])</pre><p>The output is an array with three rows and two columns. Each row represents the x and y coordinates of one centroid. So, for example, the first row contains the coordinates of the first centroid, the second row for the second centroid, and so on.</p><p>Now that we have the centroids, we can plot them on our scatter plot as stars to visually represent the center of each cluster.</p><p>To do this, we’ll combine Seaborn, which we&#39;ll use to plot the data points, with Matplotlib, which we’ll use to plot the centroids. Below the Seaborn plot, I’ll use `plt.scatter` from Matplotlib. Since we&#39;re working with the centroids array, we need to specify the x and y coordinates.</p><p>For the x-coordinates, we’ll take the first column of the centroids array (index 0). So, we&#39;ll specify `centroids[:, 0]`—the colon grabs all the rows, and the `0` gives us the first column.</p><p>Next, we’ll do the same for the y-coordinates using `centroids[:, 1]` to get the second column.</p><pre># Plot &quot;HOUSES&quot; vs &quot;DEBT&quot;, add centroids<br>sns.scatterplot(<br>    x=df[&quot;DEBT&quot;]/1e6,<br>    y=df[&quot;HOUSES&quot;]/1e6,<br>    hue=labels,<br>    palette=&quot;deep&quot;<br>    )<br><br>plt.scatter(<br>    x=centroids[:,0],<br>    y=centroids[:,1]<br>    )<br><br>plt.xlabel(&quot;Household Debt [$1M]&quot;)<br>plt.ylabel(&quot;Home Value [$1M]&quot;)<br>plt.title(&quot;Credit-Fearfull: Home Value vs. Household Debt&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*hXmVvnGuTq4VpeZt23Dkiw.png" /></figure><p>However, when I initially ran this, the centroids didn’t align with the data points because they were on different scales. To fix this, we’ll adjust the centroids by dividing the values by a million, just like we did with the data points earlier, to make sure everything is on the same scale.</p><p>I also want to make a few visual adjustments for clarity. First, I&#39;ll change the color of the centroids to gray, so they don&#39;t overpower the data points. Then, I&#39;ll add a `marker` argument to plot them as stars (using an asterisk), and finally, I&#39;ll adjust the size (`s`) to 150 so they stand out but don’t dominate the plot.</p><pre># Plot &quot;HOUSES&quot; vs &quot;DEBT&quot;, add centroids<br>sns.scatterplot(<br>    x=df[&quot;DEBT&quot;]/1e6,<br>    y=df[&quot;HOUSES&quot;]/1e6,<br>    hue=labels,<br>    palette=&quot;deep&quot;<br>    )<br><br>plt.scatter(<br>    x=centroids[:,0]/1e6,<br>    y=centroids[:,1]/1e6,<br>    color=&quot;gray&quot;,<br>    marker=&quot;*&quot;,<br>    s=150<br>    )<br><br>plt.xlabel(&quot;Household Debt [$1M]&quot;)<br>plt.ylabel(&quot;Home Value [$1M]&quot;)<br>plt.title(&quot;Credit-Fearfull: Home Value vs. Household Debt&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*JF6s_EZYIjln8t4IR_oIAg.png" /></figure><p>Now, we have a scatter plot of home value vs. household debt, with three distinct clusters colored blue, orange, and green. The centroids for each cluster are marked as gray stars, making it clear where the cluster centers are.</p><p>This looks great! But remember, as data scientists, even though the plot visually looks good, we still need to evaluate the quality of these clusters numerically.</p><p>In supervised learning problems, we’ve used metrics that assess how well the model’s predictions match the target. For classification tasks, we’ve used metrics like accuracy, precision, and recall, as seen in Project 4. For regression, we evaluate the model’s predictions based on how close they are to the target values, using metrics like Mean Absolute Error, as we did in Projects 1 and 2.</p><p>However, in unsupervised learning, such as clustering, we don’t have target labels. This means we can’t evaluate the model in terms of being “right” or “wrong,” as we do in classification, nor can we compare predictions to a true value as we do in regression. The good news is that k-means does use distances to form clusters, specifically the distance between data points and their respective centroids. So, we can use this distance to measure how well the clusters fit the data.</p><p>The first distance-based metric we’ll discuss is <strong>inertia</strong>, which measures how cohesive the clusters are. It’s also known as the <strong>within-cluster sum of squares</strong> (WCSS). This metric provides insight into the compactness of the clusters.</p><p>Let’s break it down with an example. Imagine two clusters: one where data points are close to their centroid, and another where points are farther away. The closer the points are to their centroid, the lower the inertia, and the more compact the cluster. Conversely, when points are scattered far from the centroid, inertia will be higher.</p><p>To calculate inertia, we take the distance between each data point and its assigned centroid, square that distance, and then sum the squared distances for all points in the cluster. This gives us the inertia for a single cluster. The total inertia is the sum of the inertia values for all clusters.</p><p>For example, if we compare the orange cluster and the blue cluster in figure down, where the blue cluster’s points are farther from its centroid, the blue cluster will have a higher inertia than the orange cluster. Inertia values closer to zero indicate better cohesion within the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-L3TciRatllWkYjOn_Y6w.jpeg" /></figure><p>Now, let’s formalize this with a bit of math. Let’s define:<br>- n: the number of data points in a cluster (in our orange cluster, n = 8).<br>- xᵢ: the data points in the cluster.<br>- z: the centroid of the cluster.</p><p>The inertia for a cluster is calculated as the sum of squared distances between each data point and the centroid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jo-sJ9ciQdiyqxQympxMPg.jpeg" /></figure><p>This gives the inertia for a single cluster. But we typically work with multiple clusters. So, to generalize for k clusters, we sum the inertia values for each cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPh3oaDsD5xUUJDS4JALOA.jpeg" /></figure><p>Where <strong>zⱼ</strong> is the centroid of the <strong>j</strong>-th cluster, and <strong>nⱼ</strong> is the number of points in that cluster.</p><p>Now that we understand inertia conceptually, let&#39;s see how to calculate it using Scikit-learn. We can easily extract the inertia of the k-means model by accessing the `inertia_` attribute after training:</p><pre>inertia = model.inertia_<br>print(&quot;Inertia (3 clusters):&quot;, inertia)</pre><pre>Inertia (3 clusters): 939554010797059.4</pre><p>This value represents the sum of the within-cluster sum of squares for our three clusters. As with many distance-based metrics in data science, lower inertia is better, indicating more compact clusters. The best possible inertia is zero, meaning all points are perfectly clustered around their centroids. However, inertia can vary significantly depending on the scale of the data. For example, if your data includes large values—like home prices in millions of dollars—squaring these distances can lead to very large inertia values.</p><p>It’s also important to remember that inertia is measured in the same units as your data. In our case, inertia is measured in dollars. So, while smaller inertia is better, we still need additional context to fully evaluate the clustering performance, just as we use R-squared alongside mean absolute error in regression.</p><p>Now that we understand inertia, let’s explore another distance-based metric for evaluating our clustering model: the <strong>silhouette score</strong>.</p><p>The key difference between inertia and silhouette score is that while inertia measures the internal consistency of clusters (how close the points within each cluster are to the centroid), the silhouette score assesses how well-separated the clusters are from each other. In other words, inertia focuses on cohesion within clusters, whereas the silhouette score looks at the distance between clusters.</p><p>Let’s break this down further.</p><p>Imagine two sets of clusters. On the right, we have well-formed clusters: the points are close to their respective centroids and far from the centroids of other clusters. On the left, we have poorly defined clusters: the points are far from their centroid and closer to the centroid of another cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Me2Le5niD22XcD316cWlQ.jpeg" /></figure><p>The silhouette score helps us quantify how “good” or “bad” these clusters are.</p><p>To calculate the silhouette score, we need two key numbers:<br>1. A: The average distance between a data point and the centroid of its assigned cluster. For example, in the orange cluster on the right, we calculate the average distance between the data points and their centroid. Let’s assume A = 1 in this case.<br> <br>2. B: The average distance between that same data point and the centroid of the nearest neighboring cluster. This means we look at the distances from the orange centroid to the data points in the nearest cluster (denoted in green). Let’s assume B = 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1H46nKtkLQfsxj3rWjPlg.jpeg" /></figure><p>Once we have these two values, we calculate the silhouette score using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O-oMNrYh8lzkCAcpklwuQ.jpeg" /></figure><p>In our example, that would be 0.9. A silhouette score of 0.9 is close to the best possible score of 1, indicating that the clusters are well-separated and the model is performing well.</p><p>Now let’s contrast this with the poorly formed clusters on the right. Here, A (the average distance between points and their centroid) is much larger—let’s say A = 10—while B (the distance to the nearest cluster’s centroid) is smaller, say B = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8s4VQsx5VAT1IEdk5BUiA.jpeg" /></figure><p>Plugging these values into the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5Aswmbih1LaJJ4lQSSHuQ.jpeg" /></figure><p>A silhouette score of -0.9 is close to the worst possible score of -1, indicating that the clustering is poor, with points assigned to the wrong clusters.</p><p>In summary, the silhouette score ranges from 1 (best), indicating that points are well-clustered and far from other clusters. 0, indicating overlapping or ambiguous clusters. -1 (worst), indicating that points are likely assigned to the wrong clusters.</p><p>Now that we have a solid understanding of the silhouette score, let’s calculate it for our k-means model in practice. Since we imported `silhouette_score` from the Scikit-learn metrics module earlier, we can simply call it by passing two arguments: the data (e.g., X) and the cluster labels. We can either use the variable labels that we defined earlier, or we can retrieve the labels directly from the model using the `model.labels_`.</p><pre>ss = silhouette_score(X, model.labels_)<br>print(&quot;Silhouette Score (3 clusters):&quot;, ss)</pre><pre>Silhouette Score (3 clusters): 0.9768842462944348</pre><p>The silhouette score for our model with three clusters is close to 1, suggesting that the clustering is indeed quite good.</p><p>But here’s an important question: we know the model performs well with three clusters, but could it perform even better with five, six, or even ten clusters? How do we determine the optimal number of clusters for a given problem?</p><p>This is a hyperparameter we can tune, and it would be interesting to explore the relationship between the number of clusters and the two metrics, inertia, and silhouette score, to see if we can further fine-tune our model.</p><p>To do this, we’ll create a loop to test a range of cluster numbers. Specifically, we’ll try clustering from 2 to 12 clusters, calculating the inertia and silhouette scores for each model, and then appending those values to lists. By examining these metrics across different numbers of clusters, we can better understand how both inertia and silhouette scores change as we vary the number of clusters.</p><p>Let’s start by defining the range of clusters. We’ll use Python’s `range()` function, starting from 2 up to and including 12. Since Python’s syntax is inclusive-exclusive, we’ll specify the upper limit as 13 to ensure 12 is included. Then, we’ll initialize two empty lists: one for storing inertia values and another for storing silhouette scores.</p><p>Next, we’ll set up a loop to do the following steps for each number of clusters:<br>1. Build the k-means model, passing in the number of clusters (`k`) and a fixed `random_state` (in this case, 42).<br>2. Train the model.<br>3. Calculate the inertia score and append it to our `inertia_scores` list.<br>4. Calculate the silhouette score and append it to our `silhouette_scores` list.</p><pre>n_clusters = range(2,13)<br>inertia_errors = []<br>silhouette_scores = []<br><br># Add `for` loop to train model and calculate inertia, silhouette score.<br>for k in n_clusters:<br>    #build model<br>    model = KMeans(n_clusters=k , random_state=42, n_init=10)<br>    #train model<br>    model.fit(X)<br>    #inertia<br>    inertia_errors.append(model.inertia_)<br>    #silhouette<br>    silhouette_scores.append(silhouette_score(X,model.labels_))<br><br>print(&quot;Inertia:&quot;, inertia_errors)<br>print()<br>print(&quot;Silhouette Scores:&quot;, silhouette_scores)</pre><pre>Inertia: [3018038313336857.5, 939554010797059.4, 546098841715646.25, <br>          309313172681861.4, 235250007188435.38, 182185545995311.7, <br>          150727950872604.22, 114321995931021.89, 100488983856739.94, <br>          86227397125225.02, 73193859398329.2]<br><br>Silhouette Scores: [0.9855099957519555, 0.9768842462944348, <br>                    0.9490311483406091, 0.839669623678179, 0.7526801280714244, <br>                    0.7277940458463407, 0.7256332651512161, 0.7335125606476427, <br>                    0.7313509140373811, 0.6950363232867054, 0.6964839563551604]</pre><p>Now, we have a series of inertia and silhouette scores for different values of `k`. The next step is to visualize these results. Let’s plot both metrics to explore how the number of clusters affects the model’s performance.</p><p>Let’s start by examining the relationship between k and inertia. Specifically, we want to understand how inertia changes as we vary k. The best way to visualize this relationship is through a line plot, where the x-axis will represent the number of clusters and the y-axis will represent the inertia values, which we can refer to as &quot;inertia errors.&quot;</p><pre># Plot `inertia_errors` by `n_clusters`<br>plt.plot(n_clusters, inertia_errors)<br>plt.xlabel(&quot;Number of Clusters&quot;)<br>plt.ylabel(&quot;Inertia&quot;)<br>plt.title(&quot;K-Means Model: Inertia vs. Number of Clusters&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ne9tOIMdhSNcsqAETSpVFg.png" /></figure><p>As we analyze the plot, remember that for inertia, smaller values are better, with the ideal value being 0. Observing the plot, we can see that as k increases, inertia decreases. In theory, we could continue increasing the number of clusters indefinitely, even up to 4,623 clusters, one for each data point. In that scenario, our inertia would indeed be zero. However, having so many clusters, especially with one data point per cluster, would not yield meaningful insights—it wouldn’t make sense to have such granular groupings.</p><p>Therefore, aiming for an absolute inertia of zero is not practical. The key is to identify the optimal number of clusters. When considering inertia, we should look for the point on the curve where it starts to level off, indicating diminishing returns. This type of plot is known as an elbow plot, and what we’re searching for is the &quot;elbow&quot; point where the inertia curve flattens out. In this case, it appears that the sweet spot lies around 4 or 5 clusters.</p><p>However, it’s important to note that there isn’t a definitive answer to how many clusters we should create. This contrasts with supervised learning, where performance metrics provide clear, objective guidance for model evaluation. In unsupervised learning, the decision regarding the number of clusters k can be more subjective and influenced by various factors, some of which may not even relate to performance metrics.</p><p>For instance, consider a scenario where you’re working for a credit card company aiming to develop targeted email campaigns for different groups of credit-fearful households. If the marketing department states that they only have the budget for three campaigns, then regardless of performance metrics, k must be set to 3.</p><p>This distinction between supervised and unsupervised learning is crucial to communicate to stakeholders during data analysis projects, as it highlights the subjective nature of clustering decisions. Now that we’ve explored inertia and identified our sweet spot, let’s shift our focus to silhouette score to gain further insights and help solidify our decision.</p><p>We’ll follow a similar approach to what we did with inertia: we’ll create a plot with the number of clusters on the x-axis and silhouette scores on the y-axis.</p><pre># Plot `silhouette_scores` vs `n_clusters`<br>plt.plot(n_clusters, silhouette_scores)<br>plt.xlabel(&quot;Number of Clusters&quot;)<br>plt.ylabel(&quot;Silhouette score&quot;)<br>plt.title(&quot;K-Means Model: Silhouette Score vs. Number of Clusters&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*OR1C2Do_ZOqP-DeRMwNnWQ.png" /></figure><p>As a reminder, along the x-axis, moving from left to right indicates an increasing number of clusters, just like in our inertia plot. However, there’s a key difference to note: while lower inertia values are better (with 0 being the ideal), silhouette scores work differently. The best silhouette score is 1, while the worst is -1; thus, higher values are preferable. So, we are aiming for a score closer to 1, not zero.</p><p>Another important distinction is that this plot is not a smooth elbow plot as we saw with inertia; instead, it appears much more jagged, which is typical for silhouette score plots. However, if we’re comparing our two options of 4 and 5 clusters, the difference is clear. The silhouette score for 4 is significantly higher than that for 5.</p><p>This indicates that between the two choices, 4 clusters is the better option. Now that we have identified the optimal number of clusters for our model and fine-tuned this hyperparameter, we’re ready to create the final model.</p><p>We’ll use the same approach we applied when creating our initial model, maintaining that same spirit and enthusiasm. The code will be nearly identical; we’ll set the number of clusters to 4 and the random state to 42.</p><pre>final_model = KMeans(n_clusters=4, random_state=42, n_init=10)<br>final_model.fit(X)<br></pre><h3>3. Communication Results</h3><p>Now that we’ve developed our final model, it’s time to communicate our results. To do this, I want to create one last scatter plot, this time incorporating the labels from our final model.</p><p>We’ll proceed with the same approach we&#39;ve used throughout the article.</p><pre>sns.scatterplot(<br>    x=df[&quot;DEBT&quot;]/ 1e6 ,<br>    y=df[&quot;HOUSES&quot;]/ 1e6,<br>    hue= final_model.labels_,<br>    palette= &quot;deep&quot;<br>)<br>plt.xlabel(&quot;Household Debt [$1M]&quot;)<br>plt.ylabel(&quot;Home Value [$1M]&quot;)<br>plt.title(&quot;Credit-Fearful: Home Value vs. Household Debt&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Lytfjsi4VTL4VkwMC4noOw.png" /></figure><p>We can clearly see the relationship between home value and household debt, as well as the four distinct clusters identified by our model. This visualization effectively highlights our findings.</p><p>Next, I’d like to create a side-by-side bar chart to provide additional insights.</p><p>In this part, I want to calculate the mean values for debt and home value for each of our four clusters. These values will be used to create the chart.</p><p>To start, we’ll use our dataset, which is referred to as X, and employ the `group_by()` method. We want to group by the labels generated by our final model, so I&#39;ll use `final_model.labels`. Since this yields a generator object, we need to compute the mean values.</p><pre>xgb = X.groupby(final_model.labels_).mean()<br>xgb</pre><pre>	   DEBT	            HOUSES<br>0	8.488629e+04	1.031872e+05<br>1	1.838410e+07	3.448400e+07<br>2	2.420929e+06	4.551429e+06<br>3	5.472800e+06	1.407400e+07</pre><p>As we examine the resulting DataFrame, we can see that the index labels represent the four clusters our model has created: clusters 0, 1, 2, and 3. The DataFrame also provides the mean values for both debt and home value for each of these clusters. This gives us a clear understanding of the average debt and home values for the data points within each cluster.</p><p>Additionally, I want to highlight that I will extract the cluster centers from our final model. Notice that even though these values may be presented differently, they are the same as the mean values calculated for all the data points in each cluster. The advantage of presenting them in this DataFrame format is that it will simplify the visualization process.</p><p>Now that we’ve prepared our data, it’s time to create a side-by-side bar chart to identify any interesting differences among the four clusters generated by our k-means model. I’ll use Pandas for this visualization since we have already created a DataFrame called `xgb`.</p><pre>(xgb/1e6).plot(kind=&quot;bar&quot;)<br>plt.xlabel(&quot;Cluster&quot;)<br>plt.ylabel(&quot;Value [$1 million]&quot;)<br>plt.title(&quot;Mean Home Value &amp; Household Debt by Cluster&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*6aHRzF_SqMJWzZqxh8tzzg.png" /></figure><p>On the x-axis, we have the four clusters (0, 1, 2, and 3), and the y-axis represents values in millions of dollars. Each cluster displays two bars: the blue bar represents household debt, while the orange bar represents home value.</p><p>With this visualization in hand, we can interpret the data. One interesting observation is the mean home values across the clusters. For cluster 0, the mean home value is the lowest, falling into the low to mid-range category. In contrast, clusters 2 and 3 represent families with medium to high home values, while cluster 2 stands out with ultra-wealthy households owning very expensive properties.</p><p>Another key insight is the proportion of debt to home value, which we can assess by comparing the heights of the blue and orange bars. To illustrate this further, let&#39;s calculate the ratio of debt to home value. I’ll take the debt column from `xgb` and divide it by the home value column.</p><pre>xgb[&quot;DEBT&quot;]/ xgb[&quot;HOUSES&quot;]</pre><pre>	    0<br>0	0.822643<br>1	0.533120<br>2	0.531905<br>3	0.388859<br><br>dtype: float64</pre><p>After calculating this ratio, we can visualize it as a bar chart.</p><pre>proportion = xgb[&quot;DEBT&quot;] / xgb[&quot;HOUSES&quot;]<br><br># Plot the proportion<br>proportion.plot(<br>    kind=&quot;bar&quot;,<br>    xlabel=&quot;Cluster&quot;,<br>    ylabel=&quot;Proportion, Debt/Home&quot;,<br>    title=&quot;Proportion of Debt to Home Value&quot;<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*1ZomgGZvmb8OtkZDsmfbDg.png" /></figure><p>For example, in cluster 0, the debt-to-home-value ratio is above 0.8, suggesting that a significant portion of the households’ debt comes from mortgages. In contrast, cluster 3 shows a debt-to-home-value ratio below 0.5, indicating that these households have substantial equity in their homes. Interestingly, despite the high home values in cluster 1, the debt-to-home-value proportions are similar to those in cluster 2.</p><p>What does this imply? If I were working at a financial services institution, I might tailor products to these different groups. For example, I could offer households in cluster 0 refinancing options to lower their monthly mortgage payments. In contrast, for cluster 3, a home equity line of credit might be appealing to tap into their home equity for renovations. As for cluster 1, given their significant wealth, they might benefit from premium financial advisory services.</p><p>Now that we’ve reached the end of this section, let’s summarize our findings.</p><h3>Conclusion</h3><p>In this k-means clustering analysis, we began by focusing on credit-fearful households—those denied credit or fearing denial—and examined the relationship between debt and home value. We built an unsupervised K-means model, which helped us segment these households into distinct groups. By evaluating metrics like inertia and silhouette score, we determined that the optimal number of clusters was four.</p><p>We then created visualizations, including a scatter plot to show the different groups and a side-by-side bar chart to analyze the mean characteristics of each cluster regarding debt and home value. This provided us with valuable insights into the distinctions between these groups.</p><p>Moving forward, we’ll build on this foundation. In this session, we focused on just two features: debt and home value. However, we have 315 different features at our disposal. In the next part, we’ll explore moving from a two-dimensional space to a multi-dimensional one, which promises to be an exciting journey into the multiverse.</p><p>Take care, and I’ll see you in part 3!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9e8b6edfb3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Credit-Fearful Households: Demographics and Financial Insights from the Survey of…]]></title>
            <link>https://medium.com/@sawsanyusuf/exploring-credit-fearful-households-demographics-and-financial-insights-from-the-survey-of-8a9129898ed4?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9129898ed4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 09:40:27 GMT</pubDate>
            <atom:updated>2024-10-18T09:40:27.683Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Credit-Fearful Households: Demographics and Financial Insights from the Survey of Consumer Finances</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwAXtY457ZNGi7MVM3SROA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sumup?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">SumUp</a> on <a href="https://unsplash.com/photos/a-person-putting-a-credit-card-into-a-machine-fW0TfeMWsi0?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Welcome to Project Five in our series: <em>Customer Segmentation in the U.S</em>. In this project, we’ll be analyzing data from the Survey of Consumer Finances, sponsored by the Federal Reserve. This survey captures financial, demographic, and opinion data from American households. Our goal is to develop a model that categorizes households based on their financial status.</p><p>This categorization process is known by different names depending on the field. In data science, <em>clustering is</em> a form of unsupervised learning. In marketing, it’s referred to as <em>customer segmentation</em>, often used to identify target groups for personalized campaigns. In sociology, it’s called <em>social stratification</em>, where populations are divided into social classes to study societal structure.</p><p>Given the size and complexity of the dataset, this article will focus on exploring it. We’ll examine key characteristics such as age, race, income, assets, and education. Specifically, we’ll concentrate on households labeled as <em>credit-fearful </em>—those who either have been rejected for credit or fear rejection. Our first step is to subset the data to isolate credit-fearful households. Then, we’ll explore demographic factors like age, race, education, income, and assets. Finally, we’ll create side-by-side bar charts to compare credit-fearful and non-credit-fearful households.</p><p>Throughout this process, we’ll leverage <em>method chaining </em>—a technique in which multiple transformations are applied to a pandas DataFrame or Series through a sequence of methods, such as `.rename()` and `.split()`. This will streamline our more complex data transformations.</p><p>For this first part, we’ll use Matplotlib and Seaborn for visualizations, and Pandas for data wrangling.</p><pre># Import libraries<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import seaborn as sns<br></pre><h3>1. Prepare Data</h3><h4>1.1. Import</h4><p>After importing all the necessary libraries, it’s time to load our data file into a data frame using Pandas and the `read_csv()` method.</p><p>First, let’s examine the shape of the data frame, which consists of nearly 30,000 rows and 351 features.</p><pre>df = pd.read_csv(&quot;SCFP2019.csv&quot;)<br>print(&quot;df shape:&quot;, df.shape)<br></pre><pre>df shape: (28885, 351)<br></pre><p>We’ll also preview the first five rows to get an initial overview of the data.</p><pre>df.head()<br></pre><pre>	YY1	Y1	WGT	        HHSEX	AGE	AGECL	EDUC	EDCL	MARRIED	KIDS	...	NWCAT	INCCAT	ASSETCAT	NINCCAT	NINC2CAT	NWPCTLECAT	INCPCTLECAT	NINCPCTLECAT	INCQRTCAT	NINCQRTCAT<br>0	1	11	6119.779308	2	75	6	12	4	2	0	...	5	3	6	        3	2	        10	        6	        6	        3	        3<br>1	1	12	4712.374912	2	75	6	12	4	2	0	...	5	3	6	        3	1	        10	        5	        5	        2	        2<br>2	1	13	5145.224455	2	75	6	12	4	2	0	...	5	3	6	        3	1	        10	        5	        5	        2	        2<br>3	1	14	5297.663412	2	75	6	12	4	2	0	...	5	2	6	        2	1	        10	        4	        4	        2	        2<br>4	1	15	4761.812371	2	75	6	12	4	2	0	...	5	3	6	        3	1	        10	        5	        5	        2	        2<br><br>5 rows × 351 columns<br></pre><p>It seems that most of the values are numerical, but we’ll dive deeper into the data later.</p><p>Since we’re working with a large number of features, it’s crucial to keep track of them. If you need more details about any specific feature, you can refer to the <a href="https://sda.berkeley.edu/sdaweb/docs/scfcomb2019/DOC/hcbk0001.htm#AGECL">data dictionary</a>. The documentation, hosted by the University of California, Berkeley, provides comprehensive information about each feature.</p><p>With that said, let&#39;s begin exploring the data.</p><h4>1.2. Explore</h4><p>Before we begin exploring the data, we want to subset our data frame based on the `TURNFEAR` feature, which will be our focus.</p><p>According to the data dictionary, `TURNFEAR` contains numerical values: 0 and 1. These values represent &quot;No&quot; (0) and &quot;Yes&quot; (1), indicating whether a household has been turned down for credit or fears being turned down. Essentially, a value of 1 indicates credit fearfulness. To focus on credit-fearful families, we&#39;ll filter the data for rows where `TURNFEAR` equals 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWYEBPZ_SPE_tYeMEcdyvQ.jpeg" /></figure><p>Another thing to note is the total number of respondents in the original dataset—over a million, close to 1.25 million people. This is much larger than the roughly 28,000 observations in our dataset. The reason for this difference is that we&#39;re working with a public extract of the full data. So, if you notice discrepancies between the documentation and our data frame, it&#39;s because we&#39;re only looking at a smaller subset.</p><p>With that in mind, let&#39;s create a mask to filter our data frame for households marked as credit-fearful (`TURNFEAR == 1`). We&#39;ll assign this subset to a variable called `df_fear`. Now, let&#39;s take a look at the first five rows.</p><pre>mask = df[&quot;TURNFEAR&quot;] == 1<br>df_fear = df[mask]<br>df_fear.head()<br></pre><pre>	YY1	Y1	WGT	        HHSEX	AGE	AGECL	EDUC	EDCL	MARRIED	KIDS	...	NWCAT	INCCAT	ASSETCAT        NINCCAT	NINC2CAT	NWPCTLECAT	INCPCTLECAT	NINCPCTLECAT	INCQRTCAT	NINCQRTCAT<br>5	2	21	3790.476607	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>6	2	22	3798.868505	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        3	        2	        2<br>7	2	23	3799.468393	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>8	2	24	3788.076005	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br>9	2	25	3793.066589	1	50	3	8	2	1	3	...	1	2	1	        2	1	        1	        4	        4	        2	        2<br><br>5 rows × 351 columns<br></pre><p>Notice that the index labels don’t start at zero; they start at five. This is because the first few rows (non-credit-fearful households) have been removed. So, the data now starts at what was originally the sixth row (since Python uses zero-based indexing).</p><p>To confirm our filter worked correctly, we can check the shape of `df_fear`, which shows 4,620 rows.</p><pre>print(&quot;df_fear shape:&quot;, df_fear.shape)<br></pre><pre>df_fear shape: (4623, 351)<br></pre><p>This matches our expectations based on the mask, meaning we’ve successfully subset the data.</p><p>Next, let’s begin exploring the age characteristics of our group.</p><h4>Age</h4><p>We’ll start by examining the `AGECL` column to understand what it represents.</p><pre>df[&#39;AGECL&#39;].head()<br></pre><pre>	AGECL<br>0	2<br>1	6<br>2	5<br>3	6<br>4	6<br><br>dtype: int64<br></pre><p>Looking at this column, we can see it’s filled with integer values. Not only can we observe the numbers directly, but the data type also confirms it’s an integer column. This is useful information. To explore further, we’ll use the `unique()` method to see how many unique values are present.</p><pre>df[&#39;AGECL&#39;].unique()<br></pre><pre>array([6, 3, 1, 5, 4, 2])<br></pre><p>While there are many possible integers, this column only contains six distinct values: 1, 2, 3, 4, 5, and 6.</p><p>Now that we know the unique values, what do they represent? I checked the data documentation and found that these numbers correspond to age groups. Specifically:<br>- 1 represents individuals younger than 35,<br>- 6 represents individuals older than 75,<br>- and 2 through 5 represent different age groups in between.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLJzJx-koJUP632yaS8Spg.jpeg" /></figure><p>Although this column contains numeric values, it’s actually categorical data representing different age ranges. Now that we understand the meaning behind the values, let’s create a plot to visualize the distribution of the six age groups.</p><p>However, it would be much clearer if we used the actual labels for these age groups rather than the integer codes. So before we create the visualization, we&#39;ll do a bit of data cleaning.</p><p>We have a dictionary that maps the integers in the `AGECL` column to their corresponding age group labels. The keys in the dictionary are the integer values currently in the column, and the values are the string labels that represent the actual age groups. Our goal is to replace the integers with these descriptive labels.</p><p>To achieve this, we&#39;ll use the `replace()` method, which allows us to pass in a dictionary where the keys are the current values and the values are what we want to replace them with. We&#39;ll apply this using our age group dictionary.</p><pre>agecl_dict = {<br>    1: &quot;Under 35&quot;,<br>    2: &quot;35-44&quot;,<br>    3: &quot;45-54&quot;,<br>    4: &quot;55-64&quot;,<br>    5: &quot;65-74&quot;,<br>    6: &quot;75 or Older&quot;,<br>}<br><br>age_cl = df_fear[&quot;AGECL&quot;].replace(agecl_dict)<br>age_cl.head()<br></pre><pre>5    45-54<br>6    45-54<br>7    45-54<br>8    45-54<br>9    45-54<br>Name: AGECL, dtype: object<br></pre><p>Now, with the cleaned data and proper labels in place, we can create a more meaningful visualization of the age distribution in this column, a bar chart.</p><p>After we prepared our `age_cl` series, which contains the actual labels for the age groups. The next step is to determine how large each of these six groups is. To do this, we’ll use the `value_counts()` method, which is ideal for grouping and counting values.</p><pre>age_cl_value_counts = age_cl.value_counts()<br>age_cl_value_counts<br></pre><pre>	       count<br>AGECL	<br>Under 35	1307<br>35-44	        1093<br>45-54	         932<br>55-64	         745<br>65-74	         401<br>75 or Older	 145<br><br>dtype: int64<br></pre><p>This gives us a series showing the size of each group. As expected, the largest group is the under-35 age group. While this information is helpful, a visual representation would be more insightful, so let&#39;s create a bar chart using Pandas.</p><pre>age_cl_value_counts.plot(<br>    kind=&#39;bar&#39;,<br>    xlabel=&quot;Age Groups&quot;,<br>    ylabel=&quot;Frequency (counts)&quot;,<br>    title=&quot;Credit Fearful: Age Groups &quot;<br>);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*54P32s3wXrNsDiyfl8zedw.png" /></figure><p>Now that we have the chart, let’s interpret it. Along the X-axis, we have the six age groups in the correct order, and the Y-axis shows the count for each group. As we saw earlier, the under-35 group is the largest in our credit-fearful population. But what does this tell us?</p><p>It suggests that, in our credit-fearful group, the majority are under 35. However, that might not fully capture the situation. Let’s think about this a bit more.</p><p>The age groups in this column are binned, meaning we’ve divided all households into six broad categories. So, this bar chart reflects those predefined bins. It’s almost like a histogram with six categories, but we might gain a more nuanced understanding of the age profile in this subpopulation if we look at the raw ages rather than these broad groups. Creating a histogram from the raw ages could give us deeper insights.</p><pre>df_fear[&quot;AGE&quot;].hist(bins=10)<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Frequancy (count)&quot;)<br>plt.title(&quot;Credit Fearful: Age Distribution&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*3cHEfq6Hxy3Tvu-gW8P9Og.png" /></figure><p>This histogram is much more revealing, and I love how it gives us a clearer picture compared to just looking at the `AGECL` categories.</p><p>On the X-axis, we now have the raw ages. Initially, it seemed like almost everyone in our credit-fearful group was under 35, but the histogram tells a different story. We can see that the majority of individuals are actually between 30 and 40, not strictly under 35 as we first thought.</p><p>Looking more broadly, the bulk of this subpopulation falls between the ages of 25 and 60. So, while we originally assumed this group was mostly very young, the histogram shows that it spans a much wider range—more in line with what we might expect from a generational distribution.</p><p>Now that we have a better understanding of the age profile, let’s move on and explore the topic of race.</p><h4>Race</h4><p>Before we start coding, I want to review the data dictionary and highlight a few important points.</p><p>First, it’s essential to note that race, as sociologists often explain, is a social construct. The way race is categorized in our dataset reflects how race is conceptualized in the United States. In the `RACE` column, we see four distinct integers: 1, 2, 3, and 5. Each represents a racial or ethnic group—White non-Hispanic, Black/African American, Hispanic, and Other, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ohNrdvYyLpbHpYK-8ClMw.jpeg" /></figure><p>One thing that stands out is the absence of the number 4. It would seem reasonable, given how race is often categorized in the U.S., to expect 4 to represent Asian or Pacific Islander, but that group is not included in this dataset. I’m not sure why this extract of the data excludes that group, but it’s an important blind spot to keep in mind.</p><p>As data scientists, we need to remember that this dataset isn’t a fully accurate reflection of the entire U.S. population. There are limitations and omissions, and while we work with the data we have, it&#39;s essential to recognize these gaps.</p><p>With that context, let’s move forward and start building our plot.</p><p>We’ve already created a dictionary where the keys are integers from the `RACE` column, and the values are the corresponding category labels. The next step is to replace the integers in the race column with those labels, similar to what we did for the `AGECL` column.</p><pre>race_dict = {<br>    1: &quot;White/Non-Hispanic&quot;,<br>    2: &quot;Black/African-American&quot;,<br>    3: &quot;Hispanic&quot;,<br>    5: &quot;Other&quot;,<br>}<br>race = df_fear[&quot;RACE&quot;].replace(race_dict)<br></pre><p>After replacing the integers, we’ll count the occurrences of each race group. This time, however, we’ll normalize the values to show percentages, so we can see the proportional representation of each group in this subpopulation. Then, we’ll create the visualization.</p><pre>race_value_counts = race.value_counts(normalize=True)<br><br>race_value_counts.plot(kind=&quot;barh&quot;)<br>plt.xlim((0, 1))<br>plt.xlabel(&quot;Frequency (%)&quot;)<br>plt.ylabel(&quot;Race&quot;)<br>plt.title(&quot;Credit Fearful: Racial Groups&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*PSk0YsE36jZdXIGOa-4F2w.png" /></figure><p>From the plot, we can see that the largest group in our credit-fearful subpopulation is White non-Hispanic, making up over 50% of the group. Black/African American accounts for around 25%, and Hispanic is close to 20%.</p><p>At first glance, you might conclude that White non-Hispanic individuals are more likely to be fearful of being rejected for credit or are more frequently rejected. However, as always, the truth is more complex.</p><p>To gain a fuller understanding, we need to compare this subgroup with the entire population in our dataset. This will help us put the bar chart into context and reveal any subtleties that might alter our initial interpretation.</p><p>For this step, we’ll be using nearly the same code as before, but instead of focusing on the `df_fear` data frame (which contains only credit-fearful individuals), we’ll work with the entire dataset (`df`). Let’s see what insights we can uncover from the full data.</p><pre>race = df[&quot;RACE&quot;].replace(race_dict)<br>race_value_counts = race.value_counts(normalize=True)<br>race_value_counts.plot(kind=&quot;barh&quot;)<br>plt.xlim((0, 1))<br>plt.xlabel(&quot;Frequency (%)&quot;)<br>plt.ylabel(&quot;Race&quot;)<br>plt.title(&quot;SCF Respondents: Racial Groups&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*vuS-HbZcBMk9eoXletKBtw.png" /></figure><p>One of the first things that stands out is that White non-Hispanic respondents make up over 70% of the total population in the dataset. However, when we look at the credit-fearful subgroup, less than 60% of the respondents fall into this category. So, even though White non-Hispanics represent the largest group in both populations, they are proportionally less affected by credit fear or rejection compared to other groups.</p><p>Now, if we turn our attention to the Black/African American and Hispanic groups, an interesting pattern emerges. In the entire population, both of these groups represent well under 20%. But in the credit-fearful group, each makes up 20% or more. This indicates that these racial and ethnic groups are disproportionately affected by credit fear or outright rejection compared to the total population.</p><p>This analysis shows that our initial observation from the credit-fearful subgroup alone wasn’t quite accurate. Only by examining the data in the broader context of the entire dataset can we see the true picture.</p><p>This serves as an important reminder: always examine data from multiple perspectives to avoid drawing misleading conclusions.</p><p>Before wrapping up the discussion on race, it&#39;s crucial to point out that if you’re working for a private company, particularly one involved in customer segmentation or targeting, it is illegal and unethical in the United States to make decisions about extending credit based on race. This would not only violate anti-discrimination laws but also be fundamentally wrong. While race can be a relevant category in sociological studies, using it to inform business decisions in this manner is unacceptable.</p><h4>Income</h4><p>After exploring age and race, let’s now shift our focus to income. Just like we did with race, it’s important to compare both our subpopulation—the credit fearful—with those who are not. We’ll examine income, but through the lens of these two groups: credit fearful and not credit fearful.</p><p>Before diving into the analysis, let’s consult the data dictionary. The column we’ll be using is `INCCAT`, which represents income percentile groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*wU1FMwMLO_C3vginDZw6kw.png" /></figure><p>A couple of key details stand out here. First, while the column contains integers (ranging from 1 to 6), it is actually categorical, with each integer corresponding to a specific income percentile range. So, we’ll need to replace the integer values with their appropriate labels.</p><p>Second, it&#39;s important to note the way these percentile ranges are distributed. The first four categories cover 20% ranges each: 0–20%, 20–40%, 40–60%, and 60–80%. However, the last two categories—80–90% and 90–100%—are smaller, covering only 10% each. This uneven binning will be important to keep in mind when we visualize the data. As always, reviewing the documentation pays off.</p><p>Next, we’ll create a side-by-side bar chart to visualize the income distribution for both groups: credit fearful and not credit fearful. To achieve this, we need to prepare a DataFrame with the following columns:<br>1. `TURNFEAR`: This will indicate whether the household belongs to the credit fearful (1) or not (0).<br>2. `Income Category`: Instead of the integer values, we’ll use the actual percentile range labels.<br>3. `Normalized Frequency`: This will show the percentage of households in each income group for both subpopulations.</p><p>Now, let’s build this DataFrame by transforming the `INCCAT` column, which requires several steps, including method chaining.</p><p>We’ll start by replacing the integers in `INCCAT` with their corresponding percentile ranges using a dictionary. Then, we’ll group the data by `TURNFEAR` to distinguish between the credit fearful and non-credit fearful households. After that, we’ll calculate the normalized frequencies for each income group using the `value_counts` method with `normalize=True`.</p><p>A couple of things to note here: First, the output is a series, but we want a DataFrame. Second, the series has two indices: one for `TURNFEAR` (0 or 1) and one for the income category. Instead of these indices, we want these values to be columns in the DataFrame, so we’ll need to address that.</p><p>To proceed, we’ll rename the series to `Frequency`. Then, we’ll convert the series to a DataFrame using `to_frame`. Finally, we’ll reset the index so that `TURNFEAR` and `Income Category` become columns.</p><pre>inccat_dict = {<br>    1: &quot;0-20&quot;,<br>    2: &quot;21-39.9&quot;,<br>    3: &quot;40-59.9&quot;,<br>    4: &quot;60-79.9&quot;,<br>    5: &quot;80-89.9&quot;,<br>    6: &quot;90-100&quot;,<br>}<br><br>df_inccat = (<br>     df[&quot;INCCAT&quot;]<br>     .replace(inccat_dict)<br>     .groupby(df[&quot;TURNFEAR&quot;])<br>     .value_counts(normalize=True)<br>     .rename(&quot;Frequency&quot;)<br>     .to_frame()<br>     .reset_index()<br>)<br><br>df_inccat<br></pre><pre>	TURNFEAR INCCAT	        Frequency<br>0	0	 90-100         0.297296<br>1	0	 60-79.9        0.174841<br>2	0	 40-59.9	0.143146<br>3	0	 0-20	        0.140343<br>4	0	 21-39.9	0.135933<br>5	0	 80-89.9	0.108441<br>6	1	 0-20	        0.288125<br>7	1	 21-39.9	0.256327<br>8	1	 40-59.9	0.228856<br>9	1	 60-79.9	0.132598<br>10	1	 90-100	        0.048886<br>11	1	 80-89.9	0.045209<br></pre><p>Now we have exactly what we need: a DataFrame with three columns—`TURNFEAR`, `Income Category`, and `Frequency`—showing the normalized income distribution for both groups.</p><p>The final step is to visualize the data, and for that, we’ll use Seaborn to create a clear, side-by-side bar chart comparing the income distribution between credit fearful and non-credit fearful households.</p><pre>sns.barplot(data=df_inccat, x= &quot;INCCAT&quot;, y=&quot;Frequency&quot;, hue=&quot;TURNFEAR&quot;, order=inccat_dict.values())<br>plt.xlabel(&quot;Income Category&quot;)<br>plt.ylabel(&quot;Frequency (%)&quot;)<br>plt.title(&quot;Income Distribution: Credit Fearful vs. Non-fearful&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*_GmNuIUTWfyiRjdRUSBDnA.png" /></figure><p>What insights can we draw from this? This visualization is quite revealing. First, we see that the categories are in the correct order. What immediately stands out is that at the lower end of the income distribution, the orange bars (representing credit fearful households) are much more prominent. In contrast, at the higher end, especially in the 90–100 percentile range, we see that those households are far more credit-less.</p><p>So, what have we learned so far? We know that the credit-fearful group is largely in their 30s to early 40s, though when we broaden the scope, it includes households primarily between 25 and 60. We also know that, while white non-Hispanics are the largest racial group in this subpopulation, people of color (Black and Hispanic households) are proportionally more represented.</p><p>Lastly, we can see that households on the lower end of the income spectrum are more heavily represented in the credit-fearful group.</p><p>Great—now we have a clearer picture of who the credit-fearful households are. There&#39;s just one more factor we need to examine: assets.</p><h4>Assets</h4><p>Now, let’s examine the assets held by both credit-fearful and non-credit-fearful households. But before diving into the data, let’s clarify what we mean by &quot;assets.&quot; Essentially, an asset is anything of value that you own. For most Americans, the largest assets tend to be their homes and cars. However, there are many other types of assets.</p><p>For example, you can have financial assets like stocks or bonds. You might also own non-financial assets beyond your home and car, such as part of a business or even the entire business itself. Additionally, assets can include personal collections, like a stamp collection or even something like a collection of Pokémon cards or World Cup memorabilia. While these may not hold significant monetary value, they can carry sentimental value.</p><p>Given that home ownership represents a large portion of many Americans&#39; total assets, I want to examine the relationship between assets and home values for both the general population and the credit-fearful group. Let’s begin by looking at the general population.</p><pre>asset_house_corr = df[&quot;ASSET&quot;].corr(df[&quot;HOUSES&quot;])<br>print(&quot;SCF: Asset Houses Correlation:&quot;, asset_house_corr)<br></pre><pre>SCF: Asset Houses Correlation: 0.5198273544779252<br></pre><p>For the general population, we can observe a moderate positive correlation between assets and home value. In other words, as someone&#39;s assets increase, so does the value of their home. This relationship makes sense and is expected. Keep this in mind as we now shift our focus to the credit-fearful group.</p><p>How does the correlation compare to our credit fearful subpopulation? Is the relationship the same, or does it differ? Let’s find out.</p><pre>asset_house_corr = df_fear[&quot;ASSET&quot;].corr(df_fear[&quot;HOUSES&quot;])<br>print(&quot;Credit Fearful: Asset Houses Correlation:&quot;, asset_house_corr)<br></pre><pre>Credit Fearful: Asset Houses Correlation: 0.5832879735979154<br></pre><p>What we observe is that there’s also a moderate positive correlation for the credit fearful group, but it’s slightly stronger than for the general population. This suggests that, for credit-fearful households, their homes make up a larger proportion of their total assets.</p><p>This makes sense—those on the lower end of the economic spectrum tend to have fewer diverse assets. In contrast, wealthier individuals might own stocks, businesses, luxury cars, and more, so their assets are more spread out. But for those in the middle and lower economic brackets, a significant portion of their wealth is tied to their homes.</p><p>With that in mind, let’s continue exploring by focusing on a few other variables to see how they relate to one another. We’ll build on this discussion of assets.</p><p>Now, So far, we’ve been working with a large dataset—nearly 28,000 rows and over 300 features. Now, it’s time to narrow our focus and start looking at the specific features we’ll be using in the upcoming parts. At the same time, I want to continue exploring the differences between the overall population and the credit-fearful group, particularly in terms of assets, home value, income, and debt.</p><p>To do this, we’ll first subset the data, taking only the five key columns: total assets, home value, income, total debt, and education. Let’s go through that step by step.</p><p>However, instead of just looking at the raw data, I want to create a correlation matrix to understand how these variables are related. This will allow us to see the correlation coefficients between all the selected features.</p><pre>cols = [&quot;ASSET&quot;, &quot;HOUSES&quot;, &quot;INCOME&quot;, &quot;DEBT&quot;, &quot;EDUC&quot;]<br>corr = df[cols].corr()<br>corr.style.background_gradient(axis=None)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iN-sIaEw9_hmDNX0hdZ-UA.jpeg" /></figure><p>Now, we have a clear correlation matrix, and there are a few key points to highlight. First, as we’ve seen before, there’s a strong correlation between home value and total assets, but what stands out even more is the relationship between income and assets—this is our strongest correlation. As income increases, so do assets. Let’s keep both of these relationships in mind as we now shift our focus to the credit-fearful subpopulation.</p><pre>corr = df_fear[cols].corr()<br>corr.style.background_gradient(axis=None)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRKEtJ3xID98OyWF_z0f8g.jpeg" /></figure><p>In this new table, there are several key differences worth discussing. The first thing to note is that the highest correlation here is between debt and home value. What does that suggest? To me, it indicates that for families in the credit-fearful group, the majority of their debt is tied to their homes—specifically, their mortgages. This is an important distinction to keep in mind.</p><p>Now, let’s take a look at income. There’s still a correlation between income and assets, but it’s even stronger in this group. This suggests that the wealth of families in the credit fearful group is more closely tied to income from wages, rather than investments or business ownership. This aligns with our overall understanding of this subpopulation.</p><h4>Education</h4><p>We’ve developed a solid understanding of our total population, the credit-fearful group, and the key differences between credit-fearful and non-credit-fearful households. We’ve explored age, race, income, and assets, and now the final area to examine is education.</p><p>Before diving into the data, there&#39;s something important to note about the education column. While the values are numeric, they actually correspond to specific educational categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*DIOpXh8d4wHAPRfi72Z4aA.png" /></figure><p>For instance, a value of -1 represents &quot;less than first grade,&quot; while a value of 14 indicates a doctorate or professional degree. These are quite long labels, and if we were to include them in a bar chart, they’d be difficult to read. So, for simplicity, we’ll stick with the integer values.</p><p>Next, we’ll create a new data frame called `df_educ`, specifically for education. It will resemble the income category data frame we built earlier. Let&#39;s begin constructing it using the method of chaining.</p><pre>df_educ = (<br>     df[&quot;EDUC&quot;]<br>    .groupby(df[&quot;TURNFEAR&quot;])<br>    .value_counts(normalize=True)<br>    .rename(&quot;Frequency&quot;)<br>    .to_frame()<br>    .reset_index()<br><br>)<br>df_educ.head()<br></pre><pre>	TURNFEAR	EDUC	Frequency<br>0	0	        12	0.257481<br>1	0	        8	0.192029<br>2	0	        13	0.149823<br>3	0	        9	0.129833<br>4	0	        14	0.096117<br></pre><p>Once we have the data frame that shows the distribution of education levels for both credit-fearful and non-credit-fearful households, let’s visualize these differences with another side-by-side bar chart using Seaborn.</p><pre>sns.barplot(<br>    x=&quot;EDUC&quot;,<br>    y=&quot;Frequency&quot;,<br>    hue=&quot;TURNFEAR&quot;,<br>    data=df_educ)<br>plt.xlabel(&quot;Education Level&quot;)<br>plt.ylabel(&quot;Frequency (%)&quot;)<br>plt.title(&quot;Educational Attainment: Credit Fearful vs. Non-fearful&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*pCo-nPvlxwtzs_HR8ErnqA.png" /></figure><p>The resulting chart is clear and reveals some interesting insights. Looking at the orange bars, which represent the credit-fearful group, we can see that the most represented categories are 8 and 9—where 8 corresponds to a high school diploma, and 9 indicates some university education without graduating. These are the largest groups among credit-fearful households.</p><p>In fact, for all categories below 12 (which represents a university degree), credit-fearful households are more strongly represented compared to non-credit-fearful households. This indicates that credit-fearful households tend to be concentrated at the lower end of the educational spectrum. On the other hand, the blue bars, representing non-credit fearful households, are most prominent in categories 12, 13, and 14, where 12 corresponds to a university degree.</p><p>This tells us that credit-fearful households generally have lower levels of educational attainment compared to non-credit-fearful households.</p><h4>Debt</h4><p>The last thing I want to explore is debt, specifically how it compares to other variables like assets and home value, both for our total population and the credit fearful subgroup.</p><p>First, we’ll create a scatter plot of assets versus debt, starting with the total population. We’ll use Pandas to plot this data.</p><pre>df.plot.scatter(x=&quot;DEBT&quot;, y=&quot;ASSET&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*cf5seQTCXkMxOuGT1nRQnA.png" /></figure><p>Now, let’s break down the plot. The first thing to note is the scale. Along the x-axis, we see values in the range of (1 * 10^8), meaning each unit represents 100 million dollars. So, 2.5 on the x-axis translates to 250 million dollars. Similarly, the y-axis is in billions, denoted as (1 * 10^9). So, when you see a value of 2, it means 2 billion dollars in debt.</p><p>What stands out in this plot? On the one hand, there is a small group of outliers carrying enormous amounts of debt—hundreds of millions of dollars. However, it seems reasonable since their assets are in the billions.</p><p>Another key observation is that there doesn’t seem to be a strong correlation between the amount of debt and the amount of assets households have. We also notice a significant spread in the total population, with asset values ranging from very low amounts (including near-zero values) up to billions of dollars.</p><p>Now, let’s do the same plot for our credit fearful subpopulation.</p><pre>df_fear.plot.scatter(x=&quot;DEBT&quot;, y=&quot;ASSET&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*TJKBV6EdbnB5wDiNmtor1Q.png" /></figure><p>First, note the differences in scale compared to the previous plot. On the x-axis, we’re now only reaching values up to (1 * 10^7), so we’re dealing with tens of millions of dollars, not hundreds. Similarly, on the y-axis, we’re now looking at hundreds of millions of dollars, with a value of 5 representing 500 million dollars.</p><p>What’s interesting here is the emergence of distinct clusters or groups. For instance, we see a group of households with relatively low debt but significant assets. On the other end, we have a group with high debt but fewer assets. Beyond these two main groups, we can spot smaller variations: one group has more debt than assets, while another has more assets than debt. And finally, there’s a group with both low debt and low assets, falling somewhere in between.</p><p>This highlights an important finding: while we’ve been examining the credit-fearful population as a whole, there are clear subgroups within this population. We’ll definitely explore these divisions further in the next lesson.</p><p>Before we wrap up, let’s create one more set of scatter plots. Instead of assets versus debt, we’ll shift our focus to home value, comparing home values against debt.</p><p>Let’s start with creating a scatter plot comparing housing value to debt for our entire population. Again, we’ll use Pandas to generate the scatter plot.</p><pre>df.plot.scatter(x=&quot;DEBT&quot;, y=&quot;HOUSES&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*CyWJ3Ta550dleNnzNLwS1g.png" /></figure><p>Earlier, we saw that the correlation between these two variables was around 0.51, indicating a moderate positive correlation. This suggests that, generally, as debt increases, so does the value of the home—likely because much of the debt is tied to mortgages.</p><p>We can also start to see distinct clusters here. For example, we have families with a high amount of debt but relatively low home values. On the opposite end, there are families with highly valuable homes and lower levels of debt. These clusters provide an interesting glimpse into the range of financial situations across households.</p><p>Now, let’s create a scatter plot to examine housing value for our credit-favored families.</p><pre>df_fear.plot.scatter(x=&quot;DEBT&quot;, y=&quot;HOUSES&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*4PT8I9naoHEWuUb1dNBZAQ.png" /></figure><p>What stands out here? First, we can see that the correlation is noticeably stronger compared to the overall population. The correlation coefficient was higher, and it’s almost forming a straight line—it looks even stronger than 0.58, though it might just feel that way visually.</p><p>Additionally, we can clearly identify distinct groups. For instance, we have one cluster on the left, another over the right, and perhaps a few more scattered throughout. These clusters suggest that if we were to target different groups based on their home value and debt, there are clearly defined segments we could focus on.</p><p>This is valuable information that we’ll build upon in the next part when we create our first clustering model.</p><h3>Conclusion</h3><p>We’ve reached the end of this session, and we’ve accomplished quite a bit. Let’s recap what we’ve done. First, we took a compressed CSV file, loaded it into a DataFrame, and found ourselves with a huge dataset—over 28,000 observations and more than 300 features. To get a better understanding of the data, we focused on households that had been denied credit or feared being denied credit in the past.</p><p>We then explored the demographic characteristics of this subgroup, examining factors like age, race, education, income, assets, and debt. Using side-by-side bar charts, we uncovered that both education and income levels were generally lower for the credit-fearful group compared to the general population.</p><p>We also looked at correlations among several key variables, particularly noting the differences in home values and debt levels between the two groups. Finally, through scatter plots, we began to see distinct segments within the credit fearful population, revealing different patterns based on debt and assets.</p><p>All of this sets the stage for our next step. In the following part, we’ll take this information and build our first clustering model. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9129898ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Model Accuracy: Gradient Boosting for Bankruptcy Prediction in Python]]></title>
            <link>https://medium.com/@sawsanyusuf/boosting-model-accuracy-gradient-boosting-for-bankruptcy-prediction-in-python-404bbdf09aaf?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/404bbdf09aaf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 14:43:08 GMT</pubDate>
            <atom:updated>2024-10-10T14:43:08.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AS1S11P4fVG48g1-" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Greetings everyone to part 4 of Project 4. In the previous part, we covered various topics such as using ensemble models like random forests, hyperparameter tuning with grid search, confusion matrix evaluation, and the trade-off between false negatives and false positives. We have also learned to save and load models using Pickle and created a function to generate predictions.</p><p>As we advance, we plan to build on these areas. Our goals include improving our bankruptcy model using gradient boosting and evaluating it using precision and recall metrics. We also aim to develop an interactive dashboard better to understand the trade-off between false positives and false negatives.</p><p>The process will involve preparing the data as before, building the baseline model, discussing gradient boosting for model iteration, tuning the model using grid search, evaluating the model using precision and recall, and creating the interactive dashboard. Furthermore, we will save our model as a file and build a predictor module.</p><p>We will be working with new libraries including ipywidgets, importing them with the alias &#39;widgets&#39;, and the interact module. Additionally, we will be using the gradient boosting classifier from Scikit-learn, as well as the classification report and confusion matrix function for metrics.</p><pre>import json<br>import pickle<br><br>import ipywidgets as widgets<br>import pandas as pd<br>from imblearn.over_sampling import RandomOverSampler<br>from ipywidgets import interact<br>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.impute import SimpleImputer<br>from sklearn.metrics import (<br>    ConfusionMatrixDisplay,<br>    classification_report,<br>    confusion_matrix,<br>)<br>from sklearn.model_selection import GridSearchCV, train_test_split<br>from sklearn.pipeline import make_pipeline</pre><p>With these plans in place, we are ready to dive right in.</p><h3>1. Prepare</h3><h4>1.1. Import</h4><pre>def wrangle(filename):<br>    with open (filename, &quot;r&quot;) as f:<br>             data = json.load(f)<br>    <br>    df = pd.DataFrame().from_dict(data[&quot;data&quot;]).set_index(&quot;id&quot;)<br>    <br>    return df</pre><pre>df = wrangle(&quot;taiwan-bankruptcy-data.json&quot;)<br>print(df.shape)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yWrDn_bKXSnePSuzGha2w.png" /></figure><h4>1.3 Split</h4><pre># Create our feature matrix X and target vector y. <br>target = &quot;bankrupt&quot;<br>X = df.drop(columns = target)<br>y = df[target]<br><br># Divide our data (X and y) into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, <br>                test_size=0.2, random_state=42)</pre><h4>1.4 Resample</h4><pre>over_sampler = RandomOverSampler(random_state= 42)<br>X_train_over, y_train_over = over_sampler.fit_resample(X_train, y_train)<br></pre><h3>2. Build Model</h3><h4>2.1. Baseline</h4><pre># Calculate the baseline accuracy score for our model.<br>acc_baseline = y_train.value_counts(normalize=True).max()<br>print(&quot;Baseline Accuracy:&quot;, round(acc_baseline, 4))</pre><pre>Baseline Accuracy: 0.9619</pre><h4>2.2. Iterate</h4><p>After preparing our data and setting the baseline, it’s time to build our classifier. We’ll be using <strong>gradient boosting</strong>, but before we dive into the code, let’s take a moment to understand what gradient boosting is. In the previous section, we discussed <strong>random forests</strong>, which are based on a technique called <strong>bagging</strong>, where multiple models are trained in parallel on different subsets of data. In contrast, <strong>boosting</strong> trains multiple models sequentially using the entire dataset.</p><p>Keep this distinction in mind as I explain how boosting works.</p><p>A quick note: In this project, we&#39;re solving a classification problem—predicting whether a company will go bankrupt or not. However, to simplify the explanation, I’ll describe how gradient boosting works for a regression problem, similar to when we predicted apartment prices in a previous project. This will help clarify the steps.</p><p>Let’s break it down step by step:<br>We start by fitting a <strong>decision tree</strong> to the training data, where our feature matrix is X and our target vector is y. This initial decision tree is called a <strong>weak learner</strong>, meaning it’s not particularly accurate. In Scikit-learn, the default maximum depth for such trees is quite shallow (e.g., max_depth=3), so the model won’t perform very well on its own.</p><p>Once this tree is fitted, we calculate the <strong>residuals</strong>, which are the differences between the true target values y, and the predictions from our first tree, y hat. These residuals will be labeled as R_1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*O0m_2JrLTlEMnPXCNGHkRA.png" /></figure><p>Next, we fit a second decision tree, but this time, instead of using y as the target, we use the residuals from the first tree (R_1). Essentially, this second tree’s job is to correct the mistakes made by the first tree by predicting the residuals. After training this tree, we calculate another set of residuals by taking the difference between the original residuals and the predictions of the second tree, (R_2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*219FTOvKpZ32oPePLR5WCQ.png" /></figure><p>We repeat this process with a third tree. Now, the target is (R_2), and the residuals are calculated again as (R_3). Each new tree is learning to correct the errors made by the previous trees, gradually improving the overall model’s predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Q3T3EF0O2pEKr6GLBOmmMA.png" /></figure><p>This process continues for several iterations (usually 100 by default in Scikit-learn). Each new tree in the sequence learns from the residuals of the previous ones. The final model is an <strong>ensemble</strong> of these weak learners, but because they are chained together, they collectively become much stronger, producing more accurate predictions.</p><p>The key takeaway is that in <strong>boosting</strong>, we fit multiple models in <strong>sequence</strong> using the full dataset, with each model trying to correct the errors of the previous one. This contrasts with <strong>bagging</strong>, where models are trained in <strong>parallel</strong> on subsets of the data.</p><p>Now, let’s move on to implementing this. We’ll still be using a pipeline and a simple imputer, but instead of a random forest classifier, we’ll swap in a <strong>gradient-boosting classifier</strong>.</p><pre>clf = make_pipeline(<br>          SimpleImputer(), <br>          GradientBoostingClassifier())</pre><p>Next, it’s time to define the hyperparameter grid for our grid search. As we’ve discussed before, the grid is set up as a dictionary, where the keys are the hyperparameters, and the values are the ranges we want to explore.</p><p>The first hyperparameter we’ll test is the <strong>imputation strategy</strong>, which has two options: `mean` and `median`. This will help us determine the best strategy for handling missing values.</p><p>Next, we need to focus on the key hyperparameters for our <strong>gradient-boosting classifier</strong>. There are two that we’ll specifically target:</p><p>1. Number of estimators – This controls how many trees are included in the model. A higher number of trees generally increases the model’s performance, but it can also increase training time. We’ll experiment with three values: 20, 25, and 30.</p><p>2. Max depth – This parameter controls the depth of each tree. In gradient boosting, we typically want to keep the trees shallow to avoid overfitting and ensure that each tree focuses on improving the residuals of the previous one. We’ll explore depths of 2, 3, and 4.</p><pre>params = {<br>    &quot;simpleimputer__strategy&quot;:[&quot;mean&quot;,&quot;median&quot;],<br>    &quot;gradientboostingclassifier__n_estimators&quot;:range(20, 31, 5),<br>    &quot;gradientboostingclassifier__max_depth&quot;:range(2,5)<br>}<br>params</pre><pre>{&#39;simpleimputer__strategy&#39;: [&#39;mean&#39;, &#39;median&#39;],<br> &#39;gradientboostingclassifier__n_estimators&#39;: range(20, 31, 5),<br> &#39;gradientboostingclassifier__max_depth&#39;: range(2, 5)}</pre><p>Although the <strong>learning rate</strong> is another important hyperparameter that affects how fast the model learns (i.e., whether improvements are made gradually over many trees or more aggressively with fewer trees), we won’t include it in this search for now.</p><p>With this setup, we can now proceed with the grid search to find the best combination of parameters.</p><p>This process will be very similar to what we did before with our random forest classifier.</p><p>We’ll initiate the grid search CV and set CLF as our classifier, which contains the gradient boosting tree. We’ll set our parameter grid equal to the parameters of the dictionary we created earlier. The cross-validation will be set to five, and we will also set the verbosity to one. Additionally, we want to set n_jobs to be equal to -1.</p><pre>model = GridSearchCV(<br>    clf,<br>    param_grid=params,<br>    cv=5,<br>    n_jobs=-1,<br>    verbose=1<br>)</pre><p>Our model is now ready to be fitted.</p><pre>model.fit(X_train_over, y_train_over)</pre><p>After our grid search has finished, we can examine the cross-validation results.</p><p>First, let’s retrieve the data from the model. Since `cv_results()` returns a dictionary, we’ll convert it into a DataFrame for easier analysis.</p><pre>results = pd.DataFrame(model.cv_results_)<br>results.sort_values(&quot;rank_test_score&quot;).head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1sGwqtP7QARoManZ3CN5g.png" /></figure><p>There are a few key points to note. First, you might notice that the index labels aren’t in numerical order. We didn’t discuss this earlier, but the reason is that the results are ranked by the best-performing models, specifically by the test score rank. For instance, our best model achieved a mean test score of 0.91, which isn’t quite as strong as the performance we saw with our random forest models in the previous part. That’s something to keep in mind.</p><p>Another interesting observation is the <strong>fit times</strong>. You’ll notice that the mean fit times for this model are significantly longer compared to our random forest model. This tells us two things right away: first, this model takes more time to train, and second, the performance is slightly worse.</p><p>However, this doesn’t necessarily mean that the gradient-boosting model is bad. It just indicates that, within the limited hyperparameter space we explored, we didn’t find the optimal settings. It’s also possible that gradient boosting isn’t the best choice for this particular problem. This is exactly why we test multiple models with various configurations—to ensure we explore different approaches.</p><p>With that said, let’s extract the best hyperparameters from the model.</p><pre>model.best_params_</pre><pre>{&#39;gradientboostingclassifier__max_depth&#39;: 4,<br> &#39;gradientboostingclassifier__n_estimators&#39;: 30,<br> &#39;simpleimputer__strategy&#39;: &#39;median&#39;}</pre><p>Our best-performing hyperparameters were a max depth of 4 and 30 estimators. Both of these values are at the upper end of our search range, which suggests that, with more time and computational power, it might be worth exploring even larger values to potentially improve performance further.</p><p>Additionally, the median imputation strategy was the most effective, both in terms of computational time and overall performance metrics. This is a valuable insight for refining future models.</p><p>With the hyperparameter tuning complete, we’re now ready to move on to the evaluation phase.</p><h4>2.3. Evaluate</h4><p>First, we’ll examine the training and test accuracy.</p><pre>acc_train = model.score(X_train_over, y_train_over)<br>acc_test = model.score(X_test, y_test)<br><br>print(&quot;Training Accuracy:&quot;, round(acc_train, 4))<br>print(&quot;Validation Accuracy:&quot;, round(acc_test, 4))</pre><pre>Training Accuracy: 0.9622<br>Validation Accuracy: 0.9279</pre><p>Next, let’s review the confusion matrix.</p><pre>ConfusionMatrixDisplay.from_estimator(model, X_test, y_test);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*GKr_ZoQhDAfEV9jKjcYV_Q.png" /></figure><p>After completing our model evaluation by calculating the accuracy score and examining the confusion matrix, we now have a clear understanding of the true positives, false positives, false negatives, and true negatives. However, accuracy alone doesn’t tell the whole story, so it’s time to shift our attention to additional evaluation metrics: <strong>precision</strong> and <strong>recall.</strong></p><p>Typically, I would provide a conceptual overview before jumping into the code, but for this section, we’ll reverse that approach—starting with the code and then discussing the concepts.</p><p>First, we will generate a <strong>classification report</strong>. To do this, I’ll import the `classification_report` function from Scikit-learn’s metrics module. This function requires the true labels (`y_test` in our case) and the model’s predictions based on `X_test`.</p><pre>print(classification_report(y_test, model.predict(X_test)))</pre><pre>              precision    recall  f1-score   support<br><br>       False       0.99      0.93      0.96      1948<br>        True       0.21      0.73      0.33        48<br><br>    accuracy                           0.93      1996<br>   macro avg       0.60      0.83      0.64      1996<br>weighted avg       0.97      0.93      0.95      1996</pre><p>Before diving into the report’s details, there are a few key points worth highlighting. If you glance at the final column, labeled <strong>support</strong>, you’ll notice it represents the number of observations used to calculate each metric. For example, under accuracy, we see a score of 93, calculated using 1,996 observations. Moving up, we observe 1,948 for the negative class (non-bankrupt companies) and 48 for the positive class (bankrupt companies). This is what <strong>support</strong> refers to—the count of samples in each class.</p><p>Next, let’s focus on <strong>precision</strong> and <strong>recall</strong>, which are the two most important metrics we’ll examine in this case. Additionally, you might notice the <strong>f1-score</strong> metric, but for now, we’ll set that aside and concentrate on precision and recall.</p><p>A crucial point to understand is that precision and recall are calculated from the perspective of the positive class, which in this case refers to companies that go bankrupt. It’s important to be mindful of this distinction because it affects how we interpret the results. Precision measures the accuracy of the positive predictions, while recall measures how well the model identifies all actual positives.</p><p>When working with classification reports, always be clear about which class is designated as the positive class so you can interpret the precision and recall correctly.</p><p>If you&#39;re interested in further exploring other metrics within the classification report, additional research is recommended. However, for now, let&#39;s focus on unpacking the meaning and significance of precision and recall.</p><p>Let’s begin by discussing <strong>Recall</strong>. Recall measures how well our model identifies observations that belong to the positive class. A simple way to remember this is: “<strong>High recall means you “want to catch them all”</strong>—just like Pokémon.</p><p>As with other performance metrics like accuracy score, recall ranges from 0 to 1. A score of 1 means perfect recall, where the model identifies every positive case correctly, and a score of 0 means it missed all of them. In most cases, the score falls somewhere in between.</p><p>But what does recall mean in the context of our project? It tells us the fraction of actual bankrupt companies in our test set that the model successfully predicted as bankrupt. A recall of 1 means the model correctly identified all bankrupt companies, while a score of 0 means it didn’t identify any. Now that we&#39;ve covered the basics, let’s look at the actual numbers.</p><p>This confusion matrix contains the same values as the one we created earlier, but I’ve added a few enhancements. First, you’ll notice that I’ve included the formula for recall, so you can see exactly how it’s calculated. Second, I’ve adjusted the matrix&#39;s coloring to better illustrate the relationships between the confusion matrix and the formulas for precision, recall, and accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*oXY3xIgkc-agZlcgHqldAQ.png" /></figure><p>For example, we can clearly see how <strong>true positives</strong> contribute to recall, and how <strong>false negatives</strong> factor into the calculation. Additionally, I’ve added a threshold slider at the top, which I’ll explain in a moment.</p><p>Let’s first refresh our memory about how prediction works. In any tree-based model, or even with logistic regression, you can generate not only predictions but also prediction probabilities. Here’s how that works:</p><p>If I run `model.predict(X_test)` on the first five rows, we get a list of binary predictions:</p><pre>model.predict(X_test)</pre><pre>array([&#39;False&#39;, &#39;False&#39;, &#39;False&#39;, ..., &#39;False&#39;, &#39;False&#39;, &#39;False&#39;], <br>                      dtype=object)</pre><p>However, instead of just binary outcomes, we can also use `model.predict_proba(X_test)` to see the probabilities behind those predictions.</p><p>For instance, if a prediction probability exceeds 0.5, the model predicts True (bankrupt). If it’s below 0.5, the model predicts False (not bankrupt). By default, the threshold is set at 0.5, meaning that if the probability is higher than 0.5, the company is predicted to go bankrupt.</p><pre>model.predict_proba(X_test)</pre><pre>array([[0.60675641, 0.39324359],<br>       [0.94807928, 0.05192072],<br>       [0.607377  , 0.392623  ],<br>       ...,<br>       [0.72899007, 0.27100993],<br>       [0.83928259, 0.16071741],<br>       [0.78940826, 0.21059174]])</pre><p>But what if we adjust this threshold? For example, try moving the slider to lower the threshold and observe how the recall score changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*z6bEePfJSoEjv_vM_JMSmw.png" /></figure><p>As the threshold decreases, <strong>recall increases</strong>. This is because a lower threshold makes the model more likely to predict bankruptcy. In fact, if we lower the threshold all the way to 0, the model would achieve perfect recall because it would predict that every company in the test set is bankrupt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*kbNmLGtlFLOSK0TpVSxlCQ.png" /></figure><p>Of course, this isn’t ideal. While perfect recall may sound great, lowering the threshold too much leads to a large number of <strong>false positives</strong>. As a result, our model might predict that many companies will go bankrupt when they actually won’t, which reduces accuracy. So, while increasing recall is important, it comes with the trade-off of increasing false positives.</p><p>This balance between <strong>recall</strong> and the <strong>false positive rate</strong> is something we need to consider carefully when adjusting our model. So, just remember: <strong>high recall means “catch them all” </strong>—but at the cost of more false positives. Now, let’s talk about precision.</p><p>Precision measures how well our model identifies observations that belong to the positive class without mistakenly labeling false positives. I remember it as: &quot;<strong>Precision means making a careful decision</strong>.&quot;</p><p>Like other metrics, precision is a score between 0 and 1, with 1 being the best and 0 the worst. But what does precision mean in the context of our project? Of all the companies in our test set that the model predicted would go bankrupt, precision is the fraction that actually did go bankrupt. It’s important to understand the difference between precision and recall.</p><p>If you want a high recall, your model might predict that every company will go bankrupt, regardless of false positives. This would result in a lot of companies predicted to fail, even though many are actually fine. On the other hand, if you want high precision, the model should only predict bankruptcy when it’s highly certain. Every false positive will lower the precision score, so precision is about making careful, confident predictions.</p><p>We saw that to increase a model’s recall, we lower the probability threshold. So, what do we do if we want to increase precision? We raise the threshold. As the threshold increases, the model only predicts bankruptcy when it’s very confident. So, as we raise precision, the predictions become more reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*e52EQoeKlhH9qnjO6_gmMA.png" /></figure><p>However, there’s a trade-off. As we raise the threshold to improve precision, we get more false negatives. That means we miss some companies that actually go bankrupt. So, as precision increases, recall decreases. Conversely, lowering the threshold raises recall but lowers precision.</p><p>In reality, a model is rarely perfect in both precision and recall. What we’ve learned is that achieving high precision often comes at the cost of lower recall (more false negatives), and achieving high recall often means lower precision (more false positives).</p><p>Given this trade-off, one of our roles as data scientists is to decide whether we prioritize precision or recall, depending on the purpose of the model once deployed.</p><p>To have a good understanding, let’s discuss two scenarios for this model and how different project priorities can influence whether we favor precision or recall.</p><p>Let’s consider a scenario where recall is prioritized over precision. Imagine you work for a regulatory agency in the European Union, helping companies navigate bankruptcy proceedings. You want to build a model to predict which companies will go bankrupt so you can send them information about filing for legal protection before they crash.</p><p>On one hand, every time your model incorrectly flags a healthy company and sends them information (a false positive), it costs 500 euros in administrative expenses. On the other hand, if a company actually goes bankrupt but doesn’t receive the information in time (a false negative), the legal costs to the European court system amount to 50,000 euros. Clearly, the cost of a false negative is much higher than that of a false positive.</p><p>Given these costs, we want to determine the optimal threshold for our model. I’ve built a widget similar to the previous one, which includes a confusion matrix, precision and recall scores, and administrative and legal costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*JDGABGSFHE-3qIaDF2yR1A.png" /></figure><p>Every time we send bankruptcy information to a company that remains healthy (a false positive), we waste 500 euros. If we fail to send the information to a company that goes bankrupt (a false negative), it costs 50,000 euros. These costs are tracked on the dashboard. At the current threshold, our total cost is around 700 thousand euros. Let’s see what happens when we adjust the threshold.</p><p>First, if we raise the threshold too high, the model will predict fewer companies as going bankrupt. This might seem like a good idea because we avoid wasting money on false positives, but it leads to a large number of false negatives. The high cost of these false negatives causes our total cost to balloon, which is clearly not ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*_N0P38qNySDk7wElPgNf3A.png" /></figure><p>Now, let’s lower the threshold all the way to zero, meaning we predict that every company will go bankrupt. This results in a huge number of false positives, as we send information to every company, regardless of their actual risk. While this reduces the cost of false negatives, our administrative costs still approach 1 million euros. So, sending mailers to everyone is also not the best approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*jxYHyjcBBwhsf3Szj7NbKA.png" /></figure><p>The best strategy lies in finding a balance. In this case, setting the threshold around 0.33 achieves the lowest total cost, around 266,000 euros. This threshold minimizes false negatives while keeping false positives at a manageable level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*LZjihiirb5pSfqFdRMB-yQ.png" /></figure><p>So, in this scenario, favoring recall is the best course of action because the cost of missing a bankrupt company is much higher than the cost of sending unnecessary mailers. However, blindly maximizing recall isn’t optimal either—we need to find the sweet spot that balances the two. This example highlights a case where prioritizing recall over precision makes sense.</p><p>For the second example, let’s say we work at a private equity firm that purchases distressed businesses, improves them, and then sells them for a profit. You want to build a model to predict which companies will go bankrupt so that you can purchase them ahead of your competitors. If the firm purchases a company that is indeed insolvent, it can make a profit of $100 million or more. But if it purchases a company that isn’t insolvent and can’t be resold at a profit, the firm will lose $250 million.<br>So, for the profit, for every true positive, the company makes $100 million. For the costs, and the false positives, the firm will lose $250 million.</p><p>So, let&#39;s see what happens if we take this threshold and we lower it. So, we&#39;re doing a high recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*W7jo2O4apmMlrhw9D20JnA.png" /></figure><p>And what we can see here is that suddenly we’re losing billions and billions and billions of dollars. So that’s definitely not something we want to do, and it certainly not offsetting our profit, or rather our profit is not offending our losses.</p><p>But if we raise the threshold to about 0.85, we’re able to maintain strong profits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*P9DDcSz6qiSv5CJ9-ddu6g.png" /></figure><p>As you can see, we’re still capturing true positives, but we’ve significantly reduced, if not eliminated, false positives. This allows us to maximize profit without incurring unnecessary losses. Of course, in real-world scenarios, some losses are inevitable, but this example demonstrates that when the cost of a false positive is very high, it’s crucial to prioritize precision. <strong>A</strong> <strong>high-precision model ensures careful decision-making</strong>.</p><p>So, we’ve now explored a recall-focused model for our EU bankruptcy scenario and a high-precision model for the venture capital case. And by that, we arrived at the end of this part and the end of the project.</p><h3>Conclusion</h3><p>Today was quite eventful! Let&#39;s summarize what we covered. Firstly, we delved into gradient boosting and its contrast to random forest. While random forest trains in parallel on data subsets, gradient boosting trains multiple models in sequence on all the data, making it slower. As a result, we had to use a smaller set of hyperparameters to reduce training time.</p><p>Next, we explored new metrics for evaluating classification models, including precision score and recall score. Precision involves making careful decisions, while recall aims to catch all relevant instances. We discussed the balance between precision and recall and how it depends on real-world usage, exemplified by our discussion on the European regulatory agency.</p><p>We now comprehend the significance of precision and recall in different contexts. This wraps up project four, where we learned to work with files, including opening and closing JSON files, decompressing them, and saving/loading model files. Additionally, we are now well-versed in using ensemble modules, such as random forest and decision tree classifiers, along with the new metrics and interactive dashboards.</p><p>I hope you found this project enjoyable and look forward to seeing you in the next one. Take care, happy data science, and happy coding! Bye for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=404bbdf09aaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Bankruptcy Prediction: Random Forests and Hyperparameter Tuning Explained]]></title>
            <link>https://medium.com/@sawsanyusuf/improving-bankruptcy-prediction-random-forests-and-hyperparameter-tuning-explained-5438fc8423ee?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/5438fc8423ee</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 09:34:15 GMT</pubDate>
            <atom:updated>2024-10-04T09:34:15.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hw15aRKjRZ4RLCAA" /><figcaption>Photo by Jakub Żerdzicki on Unsplash</figcaption></figure><p>Hello and welcome to part three of project four, Bankruptcy in Taiwan. In previous parts, we’ve covered decompressing and loading JSON files, dealing with imbalanced data, and building a decision tree model to predict bankruptcy. We’re now looking to improve our model’s performance using two techniques. First, we’ll convert our decision tree model into a random forest model, and then we’ll perform hyperparameter tuning using grid search with cross-validation.</p><p>So, our goals for this part include improving the performance of our bankruptcy model using the random forest predictor, evaluating the model’s generalization ability, tuning the model’s hyperparameters, and building a prediction function using our saved model.</p><p>We&#39;ll start by preparing the data by importing and splitting it. Then, we&#39;ll focus on oversampling as a practice. Moving on to the model-building phase, we&#39;ll apply a similar baseline approach. Still, in the iteration phase, we&#39;ll delve into random forest implementation, cross-validation, and hyperparameter tuning using grid search.</p><p>Next, we&#39;ll evaluate the model&#39;s accuracy and confusion matrix, then move on to communication, where we&#39;ll assess feature importances, save the model using the Pickle library, and build a prediction function.</p><p>We&#39;ll learn new vocabulary about ensemble models, bagging models, and the random forest model, specifically.</p><p>We&#39;ll continue using familiar libraries such as gzip for opening compressed files, JSON for loading JSON files, Pickle for saving and loading models, Matplotlib for visualizations, Pandas for data wrangling, and some relatively new friends like the random over_sampler, simple_imputer, confusion_matrix display, and make_pipeline.</p><p>We&#39;ll be introducing the random forest classifier from the ensemble module and leveraging the cross-validation method from model selection for hyperparameter tuning. Additionally, we&#39;ll utilize the train-test split method for dividing our data into training and testing sets.</p><pre># Import libraries<br>import json<br>import pickle<br><br>import matplotlib.pyplot as plt<br>import pandas as pd<br><br>from imblearn.over_sampling import RandomOverSampler<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.impute import SimpleImputer<br>from sklearn.metrics import ConfusionMatrixDisplay<br>from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split<br>from sklearn.pipeline import make_pipeline</pre><p>We will proceed with the loading and splitting processes and then move on to the resampling section.</p><h3>1. Prepare Data</h3><h4>1.1. Import</h4><pre>def wrangle(filename):<br><br>      # Open compressed file, load into dictionary<br>      with gzip.open (filename, &quot;r&quot;) as f:<br>               data = json.load(f)<br><br>      # Load dictionary into DataFrame, set index<br>      df = pd.DataFrame().from_dict(data[&quot;data&quot;]).set_index(&quot;company_id&quot;)<br><br>      return df</pre><pre>df = wrangle(&quot;taiwan-bankruptcy-data.json&quot;)<br>print(df.shape)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yWrDn_bKXSnePSuzGha2w.png" /></figure><h4>1.2 Split</h4><pre>target = &quot;bankrupt&quot;<br>X = df.drop(columns= target)<br>y = df[target]<br>print(&quot;X shape:&quot;, X.shape)<br>print(&quot;y shape:&quot;, y.shape)</pre><pre>X shape: (6819, 95)<br>y shape: (6819,)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=42)<br>print(&quot;X_train shape:&quot;, X_train.shape)<br>print(&quot;y_train shape:&quot;, y_train.shape)<br>print(&quot;X_test shape:&quot;, X_test.shape)<br>print(&quot;y_test shape:&quot;, y_test.shape)</pre><pre>X_train shape: (5455, 95)<br>y_train shape: (5455,)<br>X_test shape: (1364, 95)<br>y_test shape: (1364,)</pre><h4>1.3. Resample</h4><p>We loaded our data into a dataframe, then we performed a vertical split to create a feature matrix and a target vector, followed by a horizontal split to create training and test sets. Now that we are aware of having imbalanced data, it’s time to perform oversampling to balance it out. It’s important to note that we are performing this resampling only after setting aside our training data; no modifications should be made to the data before setting aside the test set.</p><p>The initial step is to instantiate the random over-sampler by calling the function with the random state as the only argument. Since this is a randomized process, we set the random state equal to 42. Once the random over-sampler is instantiated and assigned to the variable ‘oversampler,’ we will use it to fit and resample our data by applying the fit_resample() method, similar to using a Scikit-learn transformer. This will be done in one step using X_train and y_train.</p><p>It’s worth noting that our training set contains approximately 5,500 observations. Therefore, after performing the resampling, we should observe a significantly larger dataframe with the addition of the resampled observations.</p><pre>over_sampler = RandomOverSampler(random_state=42)<br>X_train_over, y_train_over = over_sampler.fit_resample(X_train, y_train)<br>print(X_train_over.shape)</pre><pre>(10572, 95)</pre><p>Upon inspection, it’s evident that our dataset has indeed grown in size, confirming that the resampling process was successful. With our training data now prepared, we can proceed to build our model.</p><h3>2. Build Model</h3><h4>2.1. Baseline</h4><pre>acc_baseline = y_train.value_counts(normalize=True).max()<br>print(&quot;Baseline Accuracy:&quot;, round(acc_baseline, 4))</pre><pre>Baseline Accuracy: 0.9691</pre><h4>2.2. Iterate</h4><p>Have you heard the expression, &quot;Two heads are better than one&quot;? The idea is that when making an important decision, it&#39;s wise to get a second opinion or even multiple opinions. Interestingly, this same principle applies to machine learning. A single decision tree can do a decent job of predicting something like bankruptcy, but we can improve performance by using multiple decision trees. When we combine several models into one predictor, this is called an ensemble model.</p><p>There are several ways to use decision trees in an ensemble, and in this section, we’ll focus on the Random Forest technique. Random Forest uses a method called &quot;bagging,&quot; where we fit multiple models on random subsets of the data. Each tree in the forest makes its prediction, and the final prediction is determined by a majority vote—whether a company will go bankrupt or not, in this case. I&#39;ll walk you through an example, but keep in mind that in a Random Forest, we train multiple models in parallel on different subsets of the training data.</p><p>Before we dive into Random Forests, let’s consider a parallel from ecology. A diverse ecosystem is healthier because it relies on biodiversity. Similarly, a diverse set of decision trees will improve the performance of our Random Forest. The key to creating this diversity is training each tree on different subsets of the data. Now, let’s explore how this works.</p><p>Imagine we have our dataset, X for features and y for the target variable. To introduce variation, the first step is to select a random subset of the data—this means picking rows from our dataset at random. Then, we introduce another layer of randomness by restricting each decision tree to only consider a subset of the features. For example, if we have 64 features, each tree might only look at 8 of them. This forces each tree to learn from different aspects of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*VvP-ipZymBo-ccIcQoHVjQ.png" /></figure><p>After training the first decision tree, we repeat the process: select a new random subset of data, choose a new random subset of features, and train a new tree. Each tree will look different from the others because of the varied data and features it has seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*EcfZtA38JztrrvcD_ShDdw.png" /></figure><p>We continue this process until we have a &quot;forest&quot; of trees—typically 100 trees by default in Scikit-learn. For simplicity, let’s imagine we’ve trained three trees. Once they’re trained, the trees will make predictions. Suppose one tree predicts bankruptcy for a company, while the other two vote against it. Since the majority voted &quot;no,&quot; the final prediction will be that the company will not go bankrupt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*wjZEKmqHjHjmbcD7m-Ep7w.png" /></figure><p>One last point: because each tree is trained on a subset of the data, we can train all the trees in parallel, which speeds up the process significantly. The combination of random subsets of data and features ensures diversity among the trees, leading to better overall predictions.</p><p>Now that we&#39;ve covered the concept, let’s move on to the actual implementation. We&#39;ll create a Random Forest model using Scikit-learn. Since we’re dealing with missing data, we’ll use a pipeline to combine a Random Forest classifier with an imputer. You’ll see that I&#39;ve labeled the model as `clf`, short for the classifier. The pipeline will handle both missing data and model training efficiently.</p><pre>clf = make_pipeline(<br>          SimpleImputer(), <br>          RandomForestClassifier(random_state=42))<br>print(clf)</pre><pre>Pipeline(steps=[(&#39;simpleimputer&#39;, SimpleImputer()),<br>                (&#39;randomforestclassifier&#39;,<br>                 RandomForestClassifier(random_state=42))])</pre><p>At the beginning of this article, I mentioned that we’d be doing some hyperparameter tuning. In previous projects, we would typically set aside a portion of our training data as a validation set to test different hyperparameter configurations. However, this approach has a drawback: by setting aside a validation set, we reduce the amount of data available for training, which could negatively impact performance. This problem becomes even more pronounced when working with small datasets, where every data point is valuable for training.</p><p>One way to avoid this issue is by using a technique called cross-validation (CV). Let’s walk through how it works. First, assume we&#39;ve already set aside our test set for final evaluation. So now, we’re working only with our training data, with `X` for features and `y` for the target variable.</p><p>The traditional method involves randomly splitting off a portion of the training data to serve as the validation set, while the rest is used to train the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*RYPmUZkDxCJdYdMVAyivvA.png" /></figure><p>Cross-validation improves on this by using a more systematic approach. Specifically, we’ll be using k-fold cross-validation, where `k` refers to the number of folds we divide the dataset into—typically five by default.</p><p>Here’s how it works: we split the dataset into five equal parts, or &quot;folds.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*eBaabwGFaf19fhGYGiQzVQ.png" /></figure><p>For the first iteration, we train the model using four of these folds, reserving the fifth as the validation set. After training, we evaluate the model on the validation fold, producing an accuracy score—let’s say 0.95 for this first fold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*s-ZoS9KlldKjgGGcOovfoQ.png" /></figure><p>Next, we repeat the process, but this time we designate a different fold as the validation set and use the remaining four folds for training. This gives us a second accuracy score, perhaps 0.94.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*y9VekoUdqoMLMrkmGDeahQ.png" /></figure><p>We continue this process until each of the five folds has been used as the validation set once. In the end, we have five accuracy scores, each reflecting the model&#39;s performance on a different subset of the training data. If these scores are similar, it suggests that the model is likely to generalize well to unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*yb_tyouxM7YLueX7vUsv8w.png" /></figure><p>Now, let’s move on to the implementation of cross-validation in Scikit-learn. Although it’s more common to incorporate cross-validation directly into hyperparameter tuning, it’s still helpful to understand the basic mechanics.</p><p>We start by creating a variable to store the accuracy scores from each fold. Then, we use the `cross_val_score` function. The first argument is the classifier we’ve built, in this case, our pipeline that includes both the imputer and the random forest classifier (`clf`). Next, we provide the training data—`X_train_over` and `y_train_over`, as we’re working with oversampled data. Finally, we specify two more parameters: `cv`, which controls the number of folds (we’ll set it to 5), and `n_jobs`, which we’ll set to -1 to use all available computational resources and speed up the process.</p><pre>cv_acc_scores = cross_val_score(clf, <br>                                X_train_over, <br>                                y_train_over, <br>                                cv = 5, <br>                                n_jobs= -1<br>)<br>print(cv_acc_scores)</pre><pre>[0.99338061 0.99432624 0.99432356 0.99668874 0.99432356]</pre><p>Two key takeaways from the results:</p><p>Firstly, all the accuracy scores are around 0.99, a significant improvement over the single decision tree model we used in the previous lesson. This indicates that the random forest is providing much better performance.<br>Secondly, the accuracy scores are very close to each other (e.g., 0.99, 0.996, 0.998), which suggests that the model is stable and likely to generalize well to new data.</p><p>Overall, these results are promising, and now that we understand how cross-validation works, we’ll move on to incorporating it into our hyperparameter tuning process.</p><p>But first, let’s talk about the hyperparameters we want to tune for our model and the different settings we want to try out.</p><p>We have identified three hyperparameters to work on: `number_of_estimators`, `max_depth`, and `sample_imputer` strategies. When specifying these hyperparameters, we will use a dictionary to pass the information to our model.</p><p>For the `number_of_estimators`, we will consider values between 25 and 75 (excluding 100) in intervals of 25. This will allow us to focus on concepts and learning skills rather than spending excessive time waiting for our model to train.</p><p>As for the `max_depth`, we will explore values of 10, 20, 30, and 40 to find the optimal setting.</p><p>For the `sample_imputer` strategy, we will evaluate the mean and median as the two options.</p><pre>params = {<br>    &quot;simpleimputer__strategy&quot;:[&quot;mean&quot;,&quot;median&quot;],<br>    &quot;randomforestclassifier__n_estimators&quot;:range(25,100,25),<br>    &quot;randomforestclassifier__max_depth&quot;:range(10,50,10)<br>}<br>params</pre><pre>{&#39;simpleimputer__strategy&#39;: [&#39;mean&#39;, &#39;median&#39;],<br> &#39;randomforestclassifier__n_estimators&#39;: range(25, 100, 25),<br> &#39;randomforestclassifier__max_depth&#39;: range(10, 50, 10)}</pre><p>To incorporate hyperparameter tuning into our model, we’ll use a grid search. Before diving into the implementation, let&#39;s first clarify the concept, and then we&#39;ll talk about the code.</p><p>We explored different settings for two hyperparameters: the maximum depth of the decision trees and the number of estimators (i.e., trees in the forest). For example, for max depth, we considered values of 10, 20, 30, and 40. For the number of estimators, we tried 25, 50, and 75. Now, we haven’t discussed the imputation strategy yet, but let’s focus on this grid of hyperparameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*BvJ1nVDPgQ0gjHDnlMfANw.png" /></figure><p>You might wonder why we’ve laid things out this way—it’s because I want to show you how grid search works. Think of each box in this grid as a specific set of hyperparameters. For instance, the first box represents a model with 25 estimators and a max depth of 10. In a grid search, we train a model for that specific combination of hyperparameters and evaluate its performance on a validation set. We store the resulting accuracy score for later comparison.</p><p>Next, the grid search will move to the next combination: 25 estimators and a max depth of 20, and so on, until all possible combinations have been evaluated. In this case, with four max depth values and three estimator values, we end up with 12 different models. Once training is complete, the grid search will compare all the accuracy scores and identify the combination that performed the best. Let’s say, for example, that 50 estimators and a max depth of 30 provided the highest accuracy. We can now confidently choose this combination as our optimal hyperparameter settings, knowing we&#39;ve tested every other possible combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*973Wk8bMqItORzz-gKNyrg.png" /></figure><p>Now, what about the imputation strategy? We can think of this grid as two-dimensional, but if we add another factor, like the imputation method (e.g., median vs. mean), we expand into three dimensions. This forms a cube of hyperparameters. Instead of 12 combinations, we’d have 4 max depths, 3 estimators, and 2 imputation strategies—giving us 24 possible models to evaluate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*SWFL3i_xEK-87fO0y_c62g.png" /></figure><p>In short, grid search systematically tests every possible combination of hyperparameters, evaluates the performance of each, and selects the best set based on the highest accuracy or another metric.</p><p>Now, let’s move on to implementation.</p><p>We’ll use `GridSearchCV` as our model. First, we instantiate the `GridSearchCV` object. The first argument is the classifier (`clf`) we created earlier, which includes both the imputation strategy and the random forest classifier.<br>Next, we define the `param_grid` argument, which contains a dictionary of the hyperparameters and their possible values. For example, this will include the different values for max depth and number of estimators.<br>After that, we specify `cv`, which determines how many folds to use for cross-validation. In this case, we’ll set it to 5.<br>We also want to speed up the process by parallelizing it, so we set `n_jobs = -1`, which tells the computer to use all available resources.</p><p>Finally, the `verbose` argument allows us to see the progress of the training, so we’ll set `verbose = 1`.</p><pre>model = GridSearchCV(<br>     clf,<br>     param_grid=params,<br>     cv=5,<br>     n_jobs=-1,<br>     verbose=1<br>)</pre><p>At this point, we’ve set up our grid search with `GridSearchCV`. It contains our estimator (a pipeline with a simple imputer and random forest classifier) and the parameter grid we want to explore. Now, we’re ready to fit the model and find the optimal hyperparameters.</p><pre>model.fit(X_train_over, y_train_over)</pre><p>After successfully training the model, the next step is to investigate which set of hyperparameters led to the best performance. To retrieve the results from the grid search, we start with the name of the model (in this case, `model`), and access the `cv_results_` attribute. This will return a dictionary containing all the details of the grid search. However, simply printing out this dictionary can be overwhelming and hard to interpret due to its complexity.</p><p>To make the results easier to explore, it&#39;s helpful to convert the dictionary into a DataFrame. This will allow us to neatly display the data and filter it as needed. Once the DataFrame is created, we can print out the first 10 rows to get an overview.</p><pre>cv_results = pd.DataFrame(model.cv_results_)<br>cv_results.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ylk5yHCRQPnIRmFSlmoJgw.png" /></figure><p>Each row in this DataFrame represents a different combination of hyperparameters used to train a model. For example, you can see details like the number of estimators and max depth for each model. Additionally, there’s information on how long each model took to train, which is presented as the mean training time. Since cross-validation was used, the model was trained five times, and this value reflects the average time across the folds.</p><p>On the right side of the DataFrame, we can observe the mean test score, which shows how well the model performed across the validation folds. There’s also a ranking of the test scores, which makes it easy to identify the best and worst performing models. The model with the rank of &quot;1&quot; represents the best performance.</p><p>Before diving deep into the data, it&#39;s useful to visualize the trade-offs between hyperparameter values and training time. Let’s create a few visualizations to explore how the hyperparameters impacted performance and training time, before we examine the best-performing model.</p><p>We&#39;ll start by examining how `max_depth` affects training time. The goal is to create a line plot with `max_depth` on the x-axis, ranging from smaller to larger values, and mean training time on the y-axis. This will allow us to observe any relationship between increasing `max_depth` and the training time—whether it increases, decreases, or stays the same.</p><p>However, we need to account for the fact that our data includes multiple dimensions: besides `mean training time`, we also have the number of estimators, `max_depth`, and imputation strategy. Since we can&#39;t visualize all of these in a single 2D plot, we&#39;ll simplify things by holding one variable constant. In this case, we&#39;ll filter the data to include only the models where `max_depth` is fixed at a specific value, allowing us to focus on the relationship between the number of estimators and the mean training time.</p><p>To start, we’ll filter the grid search results to focus only on rows where `max_depth` is equal to a particular value, say 10. To do this, we’ll apply a mask to the `cv_results_` DataFrame, filtering for rows where the `param_randomforestclassifier__max_depth` is 10. Once we have this subset, we can move ahead and create our plot.</p><pre># Create mask<br>mask = cv_results[&quot;param_randomforestclassifier__max_depth&quot;]==10<br><br># Plot fit time vs n_estimators<br>plt.plot(<br>    cv_results[mask][&quot;param_randomforestclassifier__n_estimators&quot;],<br>    cv_results[mask][&quot;mean_fit_time&quot;]<br>)<br><br># Label axes<br>plt.xlabel(&quot;Number of Estimators&quot;)<br>plt.ylabel(&quot;Mean Fit Time [seconds]&quot;)<br>plt.title(&quot;Training Time vs Estimators (max_depth=10)&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*9k8r5RglkPQPuV0dbnPfIg.png" /></figure><p>Now, looking at the plot, there are two interesting observations:</p><p>There is a clear relationship between the number of estimators and the mean training time. As the number of estimators increases, the training time also increases, which is expected. More trees in the random forest require more computation, leading to longer training times.<br>Then, for each value of the number of estimators (e.g., 25, 50, 75), we see two different mean training times. This difference is due to the imputation strategy—one point represents the model trained with the mean imputation strategy, while the other represents the median strategy. We’ll want to explore how these imputation strategies impact training time and performance in more detail.</p><p>After looking at the number of estimators, we’ll now move on to analyze the effect of `max_depth`.</p><p>So, again, we need a 2D line plot. We&#39;re looking at three different hyperparameters, so we need to hold one of them constant. In this case, we&#39;ll keep the number of estimators constant at 25.</p><pre>mask = cv_results[&quot;param_randomforestclassifier__n_estimators&quot;]==25<br># Plot fit time vs max_depth<br>plt.plot(<br>cv_results[mask][&quot;param_randomforestclassifier__max_depth&quot;],<br>cv_results[mask][&quot;mean_fit_time&quot;]<br>)<br># Label axes<br>plt.xlabel(&quot;Max Depth&quot;)<br>plt.ylabel(&quot;Mean Fit Time [seconds]&quot;)<br>plt.title(&quot;Training Time vs Max Depth (n_estimators=25)&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5iQXmaJeKry9RMzaJSnsw.jpeg" /></figure><p>When looking at the plot, it appears quite erratic. There seems to be some increase in training time as max depth increases, but what really surprises me are the significant differences between the two different patient strategies. Let&#39;s revisit the data frame and focus only on mean fit time.</p><p>From the data, it&#39;s evident that the mean consistently outperforms the median, resulting in significant differences in training times. The question that arises is whether using the median results in better model performance in terms of accuracy but at the cost of longer computational time and increased resource consumption.</p><p>Now, we need to identify the best hyperparameters for this model to determine our final evaluation and practical implementation.</p><p>I&#39;ll begin by extracting the best set of hyperparameters from our model using `model.best_params_`. This returns a dictionary with the optimal values.</p><pre>model.best_params_</pre><pre>{&#39;randomforestclassifier__max_depth&#39;: 40,<br>&#39;randomforestclassifier__n_estimators&#39;: 50,<br>&#39;simpleimputer__strategy&#39;: &#39;median&#39;}</pre><p>From this, we can see that the best `max_depth` was 40, which makes sense for a highly flexible tree. Interestingly, the best number of estimators was 50, which is a bit surprising. I initially expected that more estimators (or &quot;opinions&quot;) would lead to better performance, but in this case, 50 provided the best results. It’s also worth noting that the best imputation strategy turned out to be the median.</p><p>So, we were correct that median imputation yields the best performance in terms of accuracy, though perhaps not in terms of training time. This highlights a trade-off we need to consider between performance and computational cost.</p><p>Now that we know the optimal hyperparameters, we can also check the best score achieved during the grid search.</p><pre>model.best_score_</pre><pre>0.9978939791055105</pre><p>The highest accuracy we achieved is approximately 0.997, almost 0.998, which sets a very high standard. It’ll be interesting to see if our model performs just as well on the training set.</p><p>Often, after completing a grid search or cross-validation, people want to retrieve their best model. With `best_estimator_`, we can extract the model with the best hyperparameters. This returns a pipeline that includes the median imputation strategy, a max depth of 40, and 50 estimators for the random forest classifier.</p><pre>model.best_estimator_</pre><pre>Pipeline(steps=[(&#39;simpleimputer&#39;, SimpleImputer()),<br>                (&#39;randomforestclassifier&#39;,<br>                 RandomForestClassifier(max_depth=40,n_estimators=50,<br>                           ,random_state=42))])</pre><p>We could assign this best model to another variable and use it to make predictions with `predict()`.</p><pre>model.predict(X_train_over)</pre><pre>array([False, False, False, ... ,True, True, True])</pre><p>Finally, let&#39;s move on to evaluating the accuracy score for our model.</p><h4>2.3. Evaluate</h4><p>The moment of truth. Let’s see how our model performs:</p><pre>acc_train = model.score(X_train_over, y_train_over)<br>acc_test = model.score(X_test, y_test)<br>print(&quot;Training Accuracy:&quot;, round(acc_train, 4))<br>print(&quot;Test Accuracy:&quot;, round(acc_test, 4))</pre><pre>Training Accuracy: 1.0<br>Test Accuracy: 0.9589</pre><p>After reviewing both the training and test accuracy, we see that we&#39;ve just exceeded the baseline with a training accuracy close to perfect, and a test accuracy score of 0.9589.</p><p>However, accuracy alone doesn&#39;t tell the whole story. A more insightful way to evaluate our model&#39;s performance is by using a confusion matrix. Let&#39;s plot the confusion matrix and compare it to the one we built in the previous section.</p><pre>ConfusionMatrixDisplay.from_estimator(model, X_test, y_test);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLyk-aLUi0dFVWUZvlDnuA.jpeg" /></figure><p>At first glance, this looks promising, but interpreting raw numbers can be tricky. To get a clearer understanding, let’s directly compare the confusion matrix from this session with the one from the last session.</p><p>The previous confusion matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tagKxQh16ZCaM2ud_Bzocg.jpeg" /></figure><p>In this case, we’re comparing the performance of the random forest model to that of the decision tree. What differences do you notice? Why might these differences lead to a slightly better accuracy score for the random forest?</p><p>Recall that the left column in each matrix represents predictions where the model guessed that a company would not go bankrupt (i.e., the false negative class). We can see that both matrices show an increase in these values, meaning the random forest is predicting that more companies will not go bankrupt. Since most companies in reality don’t go bankrupt, this boosts the number of correct predictions, leading to a higher overall accuracy.</p><p>However, this strategy comes with a trade-off. While the model reduces false positives—cases where the model predicts bankruptcy but the company doesn’t actually go bankrupt—it also increases false negatives, where the model predicts that a company will not go bankrupt, but it eventually does. So, while the accuracy has improved, the confusion matrix reveals a more nuanced picture.</p><p>The key question here is whether it&#39;s better for the model to have more false positives or more false negatives. The answer depends on how we intend to apply this model in the real world. We&#39;ll delve deeper into this question in the next part of our project.</p><p>For now, when predicting bankruptcy, we need to bear in mind whether having more false positives or false negatives is more acceptable.</p><h3>3. Communication Results</h3><p>Now it’s time to communicate our results. In this phase, we’ll focus on two main tasks. First, we&#39;ll plot the feature importances, which we&#39;ve done in previous projects, though with some slight differences here. After that, we&#39;ll save our trained model as a pickle file. But for now, let’s concentrate on the feature importances.</p><p>There are a few steps involved. First, we need to get the feature names from our training set. Then, we&#39;ll retrieve the corresponding importances from the model. Finally, we’ll combine the two into a series and plot it.</p><p>To make this more readable, I’ll sort the values in ascending order so that the smallest feature importances are at the top and the largest are at the bottom.</p><p>Next, I’ll create the plot. We only interested in the top 10 most important features, which will be the largest values at the bottom of the sorted series. I’ll use `.tail(10)` to select them, then plot the series using `kind=&quot;barh&quot;` for a horizontal bar chart.</p><pre># Get feature names from training data<br>features = X_train_over.columns<br># Extract importances from model<br>importances = model.best_estimator_.named_steps[&quot;randomforestclassifier&quot;].feature_importances_<br># Create a series with feature names and importances<br>feat_imp = pd.Series(importances, index= features).sort_values()<br># Plot 10 most important features<br>feat_imp.tail(10).plot(kind= &quot;barh&quot;)<br>plt.xlabel(&quot;Gini Importance&quot;)<br>plt.ylabel(&quot;Feature&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWkVrtdePNBpASbrq2S6sA.jpeg" /></figure><p>With that, we’ll have a clear and concise feature importance plot. As expected, feature 27 stands out as the most important, based on Gini importance for this tree-based model, followed closely by features 24 and 13.</p><p>This plot will serve as a great visual deliverable for our non-technical audience. Now, it’s time to move on to saving our model.</p><p>After all the hyperparameter tuning and training, which took a considerable amount of time, it’s essential to save it so we can reuse it later without having to retrain from scratch.</p><p>First, we’ll set up a context manager using `with`. This allows us to safely open a file to save the model. Inside the `with` statement, we’ll use `open()` and specify the file name. In this case, we’ll name it &quot;model-2.pkl&quot; to keep it organized. Next, we need to set the mode to ’wb’, meaning we’re writing to the file in binary mode since it’s a model and not plain text. We’ll also assign an alias for the file object, typically done with `as f`.</p><p>Once the context is established, we’ll save the model using the `pickle` module.</p><pre>with open(&quot;model-2.pkl&quot;, &quot;wb&quot;) as f:<br>      pickle.dump(model, f)</pre><p>And just like that, the model is saved and ready to be loaded and used later without the need for retraining.</p><p>Now it&#39;s time to create our `make_predictions` function. The goal of this function is to accept user input and return a series of predictions. The first input we need is the file path to a JSON file containing data. We’ll use this path to read the JSON into a DataFrame. The second input will be the file path to a saved model. Once we have both the data and model, we’ll use the model to make predictions on the data and return the results as a series.</p><p>The `make_predictions` function will take two arguments: the `data_file_path` (the location of the JSON file) and the `model_file_path` (the location of the saved model). Our first task is to load and wrangle the data from the JSON file. Since we&#39;ve already written the wrangling logic, we can simply call the existing `wrangle` function to handle that part.</p><p>After wrangling the data, the next step is to load the model. We’ll use a context manager for this, similar to how we saved the model in the last step, but this time within the function. Using the `with` statement, we’ll open the model file path provided by the user. Since we’re reading a binary file, the mode will be `&#39;rb&#39;`. We’ll then load the model using `pickle.load()`.</p><p>Once the model is loaded, we can generate predictions. We’ll use `model.predict()` on our test data (`X_test`), which will return a NumPy array of predictions. Since we want the output as a Pandas Series (to retain the index and allow easy labeling), we’ll convert the predictions array into a series. We&#39;ll match the index of the original test data and give the series a descriptive name, like &quot;bankrupt.&quot;</p><pre>def make_predictions(data_filepath, model_filepath):<br>     # Wrangle JSON file<br>     X_test = wrangle(data_filepath)<br>     # Load model<br>     with open(model_filepath, &quot;rb&quot;) as f:<br>            model = pickle.load(f)<br>     # Generate predictions<br>     y_test_pred = model.predict(X_test)<br>     # Put predictions into Series with name &quot;bankrupt&quot;, and same index as X_test<br>     y_test_pred = pd.Series(y_test_pred, index = X_test.index, name =&quot;bankrupt&quot;)<br><br>     return y_test_pred</pre><p>Finally, let’s test the function to ensure it works correctly.</p><p>We’re providing two inputs: the file path to a specific test dataset for our minimum viable product (MVP) and the file path to the saved model.</p><pre>y_test_pred = make_predictions(<br>      data_filepath=&quot;data/taiwan-bankruptcy-data-mvp-features.json&quot;,<br>      model_filepath=&quot;model-2.pkl&quot;,<br>)<br>print(&quot;predictions shape:&quot;, y_test_pred.shape)<br>y_test_pred.head()</pre><pre>predictions shape: (526,)<br>company_id<br>4             False<br>32            False<br>34            False<br>36            False<br>40            False<br>Name: bankrupt, dtype: bool</pre><p>The function returned 526 predictions, and we can see that the company ID is correctly set as the index. The predictions are labeled as &quot;bankrupt,&quot; as expected, and everything is working smoothly. The model’s accuracy remains consistent at around 95%.</p><p>To summarize, we’ve successfully tested the prediction function, verified its output, and ensured that the model performs well. Now, we’re ready to move on to the next phase. But before that, let’s recap what we did.</p><h3>Conclusion</h3><p>We&#39;ve made significant progress in our project. First, we enhanced our bankruptcy prediction model by implementing a random forest approach. This involved using an ensemble model and bagging and leveraging multiple predictors within the random forest to improve our model&#39;s performance.</p><p>We also delved into cross-validation, a technique that involves dividing our data into folds to fine-tune our model and assess its ability to generalize, without discarding valuable data.</p><p>A particularly exciting part was performing a grid search to explore various hyperparameters and their potential values programmatically, enabling us to determine the best configuration for optimal performance.</p><p>Next, we examined the confusion matrix, concluding that while we surpassed our baseline, we need to carefully consider the trade-off between false positives and false negatives. We plan to delve deeper into this in the forthcoming article.</p><p>Finally, we developed a powerful prediction function that effectively leverages our model, producing a series of successful predictions. With this progress, we are now ready to move on to the next stage of our project, part four. See you there soon! Goodbye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5438fc8423ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Imbalanced Data and Predicting Bankruptcy with a Machine Learning Model]]></title>
            <link>https://medium.com/@sawsanyusuf/handling-imbalanced-data-and-predicting-bankruptcy-with-a-machine-learning-model-ac5207db7176?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac5207db7176</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 15:00:54 GMT</pubDate>
            <atom:updated>2024-09-30T15:00:54.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2_1IsfguCfX-Ht4M" /><figcaption>Photo by Melinda Gimpel on Unsplash</figcaption></figure><p>Hello everyone to the second part of our project, Bankruptcy in Taiwan. In <a href="https://medium.com/@sawsanyusuf/how-to-load-and-explore-bankruptcy-data-from-a-json-file-in-python-fef91ad27d21">part one</a>, we acquired the data stored in a JSON file and then, loaded it into a dataframe.</p><p>In this part, we will conduct exploratory data analysis and build a model to predict whether a company will go bankrupt. Our first goal is to identify imbalanced data and address it using a technique called resampling. We will then build a model to predict bankruptcy and evaluate its predictions using a confusion matrix and accuracy. Finally, we will learn how to save our model as a file.</p><p>To prepare our data, we will follow the steps of importing, exploring, and splitting the data, with an additional step of resampling. During the exploring phase, we will pay special attention to identifying class imbalance in the data.</p><p>When it comes to resampling, we will explore two techniques: under-sampling and over-sampling. In the model-building phase, we will start with a regular baseline and consider the implications of accuracy when dealing with imbalanced data.</p><p>During the iteration phase, we will build three different models to assess our over-sampling and under-sampling techniques. We will evaluate the models using accuracy and the confusion matrix.</p><p>In the communication phase of this part, we will focus on understanding feature importances and saving the model as a file, which can be deployed or shared with other team members.</p><p>We will be using several libraries for this session, including JSON for loading data, Pickle for saving models, Matplotlib and Seaborn for visualizations, and Imblearn for resampling techniques. We will also use familiar libraries such as Pandas, and Scikit-learn. Let’s get started!</p><pre>import json<br>import pickle<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import seaborn as sns<br><br>from imblearn.over_sampling import RandomOverSampler<br>from imblearn.under_sampling import RandomUnderSampler<br>from sklearn.impute import SimpleImputer<br>from sklearn.metrics import ConfusionMatrixDisplay<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import make_pipeline<br>from sklearn.tree import DecisionTreeClassifier</pre><h3>1. Prepare Data</h3><h4>1.1. Import</h4><p>We need to start wrangling, and what we need to do is take the code we used in the previous part for our wrangle function.</p><pre>def wrangle(filename):<br>       # Open compressed file, load into dictionary<br>       with open (filename, &quot;r&quot;) as f:<br>       data = json.load(f)<br><br>       # Load dictionary into DataFrame, set index<br>       df = pd.DataFrame().from_dict(data[&quot;data&quot;]).set_index(&quot;company_id&quot;)<br><br>       return df</pre><p>There are two steps to this wrangle function. The first step is to open a JSON file and load it into a dictionary. To do this, we need a context handler. The next step is to load the dictionary into the dataframe using Pandas setting the index to the company ID.</p><p>So, let’s use our wrangle function. We only need to pass in one argument, which is the file name.</p><pre>df = wrangle(&quot;taiwan-bankruptcy-data.json&quot;)<br>print(df.shape)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yWrDn_bKXSnePSuzGha2w.png" /></figure><p>We get a data frame. It’s the right size - 6,819 by 96. We can see that the index is the company ID, and now we have all these useful features to explore. So, let’s start our exploratory data analysis.</p><h4>1.2. Explore</h4><p>First of all, let’s review the information in this dataframe.</p><pre>df.info()</pre><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>Int64Index: 6819 entries, 1 to 6819<br>Data columns (total 96 columns):<br> #   Column    Non-Null Count  Dtype  <br>---  ------    --------------  -----  <br> 0   feat_1    6819 non-null   float64<br> 1   feat_2    6819 non-null   float64<br> 2   feat_3    6819 non-null   float64<br> 3   feat_4    6819 non-null   float64<br> 4   feat_5    6819 non-null   float64<br> 5   feat_6    6819 non-null   float64<br> 6   feat_7    6819 non-null   float64<br> 7   feat_8    6819 non-null   float64<br> 8   feat_9    6819 non-null   float64<br> 9   feat_10   6819 non-null   float64<br> 10  feat_11   6819 non-null   float64<br> 11  feat_12   6819 non-null   float64<br> 12  feat_13   6819 non-null   float64<br> 13  feat_14   6819 non-null   float64<br> 14  feat_15   6819 non-null   float64<br> 15  feat_16   6819 non-null   float64<br> 16  feat_17   6819 non-null   float64<br> 17  feat_18   6819 non-null   float64<br> 18  feat_19   6819 non-null   float64<br> 19  feat_20   6819 non-null   float64<br> 20  feat_21   6819 non-null   float64<br> 21  feat_22   6819 non-null   float64<br> 22  feat_23   6819 non-null   float64<br> 23  feat_24   6819 non-null   float64<br> 24  feat_25   6819 non-null   float64<br> 25  feat_26   6389 non-null   float64<br> 26  feat_27   6819 non-null   float64<br> 27  feat_28   6819 non-null   float64<br> 28  feat_29   6819 non-null   float64<br> 29  feat_30   6819 non-null   float64<br> 30  feat_31   6819 non-null   float64<br> 31  feat_32   6109 non-null   float64<br> 32  feat_33   6819 non-null   float64<br> 33  feat_34   6819 non-null   float64<br> 34  feat_35   6819 non-null   float64<br> 35  feat_36   6819 non-null   float64<br> 36  feat_37   6819 non-null   float64<br> 37  feat_38   6819 non-null   float64<br> 38  feat_39   6819 non-null   float64<br> 39  feat_40   6819 non-null   float64<br> 40  feat_41   6819 non-null   float64<br> 41  feat_42   6819 non-null   float64<br> 42  feat_43   6819 non-null   float64<br> 43  feat_44   6819 non-null   float64<br> 44  feat_45   6819 non-null   float64<br> 45  feat_46   6819 non-null   float64<br> 46  feat_47   6819 non-null   float64<br> 47  feat_48   6519 non-null   float64<br> 48  feat_49   6819 non-null   float64<br> 49  feat_50   6819 non-null   float64<br> 50  feat_51   6819 non-null   float64<br> 51  feat_52   6809 non-null   float64<br> 52  feat_53   6819 non-null   float64<br> 53  feat_54   6819 non-null   float64<br> 54  feat_55   6819 non-null   float64<br> 55  feat_56   6819 non-null   float64<br> 56  feat_57   6219 non-null   float64<br> 57  feat_58   6819 non-null   float64<br> 58  feat_59   6819 non-null   float64<br> 59  feat_60   6819 non-null   float64<br> 60  feat_61   6819 non-null   float64<br> 61  feat_62   6819 non-null   float64<br> 62  feat_63   6819 non-null   float64<br> 63  feat_64   6819 non-null   float64<br> 64  feat_65   6819 non-null   float64<br> 65  feat_66   6819 non-null   float64<br> 66  feat_67   6019 non-null   float64<br> 67  feat_68   6817 non-null   float64<br> 68  feat_69   6819 non-null   float64<br> 69  feat_70   6819 non-null   float64<br> 70  feat_71   6819 non-null   float64<br> 71  feat_72   6819 non-null   float64<br> 72  feat_73   6819 non-null   float64<br> 73  feat_74   5819 non-null   float64<br> 74  feat_75   6819 non-null   float64<br> 75  feat_76   6819 non-null   float64<br> 76  feat_77   6819 non-null   float64<br> 77  feat_78   6819 non-null   float64<br> 78  feat_79   6819 non-null   float64<br> 79  feat_80   6819 non-null   float64<br> 80  feat_81   6819 non-null   float64<br> 81  feat_82   6819 non-null   float64<br> 82  feat_83   6819 non-null   float64<br> 83  feat_84   6819 non-null   float64<br> 84  feat_85   6819 non-null   int64  <br> 85  feat_86   6819 non-null   float64<br> 86  feat_87   6819 non-null   float64<br> 87  feat_88   6819 non-null   float64<br> 88  feat_89   6814 non-null   float64<br> 89  feat_90   6819 non-null   float64<br> 90  feat_91   6819 non-null   float64<br> 91  feat_92   6819 non-null   float64<br> 92  feat_93   6319 non-null   float64<br> 93  feat_94   6819 non-null   int64  <br> 94  feat_95   6819 non-null   float64<br> 95  bankrupt  6819 non-null   object <br>dtypes: float64(93), int64(2), object(1)<br>memory usage: 5.0+ MB</pre><p>We have 6,819 rows, and it seems that we have some missing data that we’ll need to address. In terms of data types, most features are numerical and float values, except for the &#39;bankrupt&#39; feature, which is a boolean. When we look at the &#39;bankrupt&#39; column, it currently only shows True, but we can assume that there are also some False values present. In this context, False means &quot;not bankrupt&quot; and True means &quot;bankrupt&quot;.</p><pre>df[&quot;bankrupt&quot;].head()</pre><pre>	bankrupt<br>id	<br>1	True<br>2	True<br>3	True<br>4	True<br>5	True<br><br>dtype: object</pre><p>To summarize, we&#39;ve identified two key points: we have missing data that needs attention, and our features are mostly numerical except for the &#39;bankrupt&#39; feature, which is our target and represented as a boolean value. We&#39;ll now take a closer look at the &#39;bankrupt&#39; target.</p><p>It’s important to consider the balance between the two classes in our target variable &quot;bankrupt.&quot; By creating a bar chart for the value counts for the bankrupt class.</p><pre># Plot class balance<br>df[&quot;bankrupt&quot;].value_counts(normalize=True).plot(<br>     kind=&quot;bar&quot;, <br>     xlabel=&quot;Class&quot;, <br>     ylabel=&quot;Relative Frequency&quot;, <br>     title=&quot;Class Balance&quot;<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*WvgF5hSM3-Y4iugb_uJ5LQ.png" /></figure><p>We can see that less than five percent of our observations belong to the bankrupt or True class. This indicates a significant imbalance between the two classes.</p><p>In addition to the True and False classes, we can alternatively consider the positive and negative classes. In the context of predicting whether a company will go bankrupt, the <strong>positive class</strong> is associated with the &quot;yes&quot; prediction, indicating that the company will go bankrupt, while the <strong>negative class</strong> is associated with the &quot;no&quot; prediction, indicating that the company will not go bankrupt.</p><p>It’s essential to be clear about which class is being designated as positive and which is being designated as negative when preparing the data for analysis. In this case, the positive class is the company going bankrupt (True), and the negative class is the company not going bankrupt (False). Clarity on these class designations will be important for evaluating the model later on.</p><p>Now, I believe it’s important to delve into some of the features now. In a real-world data science project, we would need to explore all of the features, but for this learning-focused project, let’s efficiently focus on one feature: feature_27. Let’s take a closer look at that.</p><p>Before we proceed, it might be helpful to investigate what feature_27 represents by referring to the data dictionary, which contains information about all the features in this Taiwan bankruptcy dataset.</p><p>feature_27 is the profit on operating activities, which we can refer to as &quot;profit&quot; for simplicity. It’s calculated as profit on operating activities divided by financial expenses. Now that we understand this, let’s consider what this number might indicate for different types of companies.</p><p>As we plot feature_27, we could create a box plot or a side-by-side box plot. To achieve the latter, we’ll need to use seaborn.</p><pre># Create boxplot<br>sns.boxplot(x = &quot;bankrupt&quot;, y = &quot;feat_27&quot;, data = df)<br>plt.xlabel(&quot;Bankupt&quot;)<br>plt.ylabel(&quot;POA / financial expenses&quot;)<br>plt.title(&quot;Distribution of Profit/Expenses Ratio, by Class&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*yTuwrY8BJXVq7JuEXZmF2A.png" /></figure><p>Now, let&#39;s discuss the plot. On one side, we have companies that went bankrupt, while the other side represents companies that didn&#39;t. It&#39;s interesting to observe that companies that went bankrupt often have a lower profit ratio, while companies that didn&#39;t go bankrupt show larger outliers, indicating higher profits. This suggests that a company spending more than it earns may be an indicator of bankruptcy or future bankruptcy, while a company making substantial profits is less likely to go bankrupt.</p><p>However, the plot looks a bit unusual, with these unusual lines instead of the typical box shape of a box plot. We should attempt to obtain a clearer distribution or understand why we&#39;re seeing this strange box plot for this particular feature.</p><p>We need to use the describe() method on ‘feature_27&#39; and clean up the formatting for easy reading using the Apply() method. We can apply special formatting using Python formatting tricks. For example, using square brackets, commas, and periods to round off the numbers.</p><pre>df[&quot;feat_27&quot;]. describe().apply(&quot;{0:,.0f}&quot;.format)</pre><pre>count          8,312<br>mean           1,206<br>std           35,477<br>min         -190,130<br>25%                0<br>50%                1<br>75%                5<br>max        2,723,000<br>Name: feat_27, dtype: object</pre><p>Let&#39;s start with the quartiles - the 25th, 50th, and 75th percentiles. The 50th percentile is also the median, which means 50% of our companies are below and 50% are above it. Feature 27 represents companies either making a profit (above the median) or not making a profit (below the median).</p><p>The 25th and 75th percentiles show the range where 50% of all observations fall. For example, between 0 and 5, companies are either not making any profit or making some profit. We also have the minimum and maximum values, which indicate companies making significant losses or profits.</p><p>The data shows that most observations fall between 0 and 5, with some extreme values on both sides. This indicates a skewed distribution, where the median and mean (average) differ significantly due to the presence of outlier values, such as companies making significant profits.</p><p>Understanding this distribution is crucial, as it shows that the data is not normally distributed and has a skewed distribution, affecting the mean and median. Let’s create a histogram to visualize the data.</p><pre>df[&quot;feat_27&quot;].hist()<br><br>plt.xlabel(&quot;POA / financial expenses&quot;)<br>plt.ylabel(&quot;Count&quot;),<br>plt.title(&quot;Distribution of Profit/Expenses Ratio&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*D7JOmcWqgZRSQjfuOIqUPA.png" /></figure><p>Upon examining the plot, it’s evident that we have a highly skewed distribution. However, the long tail on the right side of the plot is barely visible. We can observe a long tail that extends to the end, indicating the skewed nature of the data. This skewness is caused by the presence of highly profitable companies, which act as outliers and are disrupting our analysis. To address this, we may need to remove some of these outliers by clipping them out.</p><p>We need to extract the observations that fall between the 10th percentile and the 0.1 quantile, as well as between the 9th and 90th quantile of ‘feature_27.’ First, we’ll find these quantiles using the quantile() method and store them as Q1 and Q9. Then, we’ll create a mask for our data frame using the between() method with Q1 and Q9 to filter the values we’re interested in.</p><pre># Create clipped boxplot to remove outliers<br>q1, q9 = df[&quot;feat_27&quot;]. quantile([0.1, 0.9])<br>mask = df[&quot;feat_27&quot;].between (q1, q9)</pre><p>Once we had the mask for our data frame, we proceeded to recreate the side-by-side box plot that we previously generated. The updated plot provides a clearer visualization of the distribution of the data.</p><pre>sns.boxplot(x = &quot;bankrupt&quot;, y= &quot;feat_27&quot;, data = df[mask])<br>plt.xlabel(&quot;Bankrupt&quot;)<br>plt.ylabel(&quot;Net Income to Total Assets&quot;)<br>plt.title(&quot;Distribution of Income/Assets Ratio, by Bankruptcy Status&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*C6PUKAtfek_Zb5_4Hb9W6A.png" /></figure><p>Upon closer inspection, we can observe a concentration of non-bankrupt companies on the upper end, contrasting with a smaller number of bankrupt companies in the same range. However, our primary focus is on the middle section, where both sets of companies appear to align closely. While there are observable differences, it’s important to consider whether these differences are substantial enough to be considered a significant signal, or if they may require further analysis for clarity.</p><p>Next, we need to address any issues with colinearity in our model by building a heatmap. Since the target variable is binary (bankruptcy), we should exclude it from the correlation matrix. To do this, we will drop the &quot;bankrupt&quot; column and then use the corr() method to obtain the correlation matrix.</p><p>After obtaining the correlation matrix, we will visualize it using the Seaborn library and then suppress the output.</p><pre>corr = df.drop(columns=&quot;bankrupt&quot;).corr()<br># Plot heatmap of `correlation`<br>sns.heatmap(corr);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*ENkvlgEEKGoZqYfs6lHuzg.png" /></figure><p>Remember, in the heatmap, red represents values close to zero, indicating a good correlation, while black signifies a strong negative correlation and white indicates a strong positive correlation. The diagonal line in the plot signifies features correlated with themselves, and the white and dark dots indicate a high correlation between different features.</p><p>Now let’s summarise, during the exploratory data analysis (EDA), we discovered several important points. Firstly, our data is imbalanced, so we’ll need to address this during the data preparation phase, possibly by resampling. Additionally, many features have missing values, so we’ll need to use an imputer when building our model. It’s also worth noting that many features are skewed, which may necessitate the use of a model less affected by skewed data or outliers, such as a decision tree model. Lastly, the dataset exhibits autocorrelation issues, indicating that a linear model may not be suitable. For a classification task, a decision tree model would be a better choice than a linear model like logistic regression.</p><h4>1.3. Split</h4><p>Now, we need to split our data vertically to create a feature matrix and a target vector, and then horizontally into training and test sets.</p><pre>target = &quot;bankrupt&quot;<br>X = df.drop(columns= target)<br>y = df[target]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>        X,y, <br>        test_size=0.2, <br>        random_state=42<br>)</pre><h4>1.4. Resample</h4><p>After splitting our data, the next step is to address the issue of class imbalance. It&#39;s important to note that we divided our data into a training set and a test set before doing any resampling. This ensures our test set contains authentic data from our dataset. Therefore, all changes and resampling are done only on the training data, and the test set remains untouched.</p><p>Now, let&#39;s focus on under-sampling. Under-sampling involves taking a random sample from our dataset to balance the number of observations between the positive and negative classes. This means we keep all the observations in the positive class and then randomly under-sample an equivalent number of observations from the negative class while discarding the rest. The result is a balanced dataset with an equal number of observations for both classes.</p><p>To perform under-sampling, we can use a random under-sampler, which works similarly to a Scikit-learn transformer. We can instantiate the random under-sampler and then fit and resample the training set using it. After under-sampling, we will have a dataset with a balanced distribution between the two classes.</p><pre>under_sampler = RandomUnderSampler(random_state=42)<br>X_train_under, y_train_under = under_sampler.fit_resample(X_train, y_train)<br>print(X_train_under.shape)<br></pre><pre>(338, 95)</pre><p>One potential drawback of under-sampling is that we are discarding a significant portion of the data, which may contain valuable information for model training. This could impact the model&#39;s performance, so it&#39;s important to evaluate our model&#39;s performance after under-sampling.</p><p>Next, we will move on to over-sampling. Again, let’s discuss the concept, and then move on to the code.</p><p>Over-sampling involves duplicating the smaller class until we achieve a balance between the two classes. This means repeatedly taking random samples from the smaller class and duplicating them until we have an equal representation of both classes.</p><p>Now, let’s talk about coding the over-sampling. The over-sampler works similarly to the under-sampler. First, we need to instantiate it, and then apply the random oversampling to the training data. The number of observations in our training set is currently 7,981, and after oversampling, this number will increase significantly.</p><pre>over_sampler = RandomOverSampler(random_state=42)<br>X_train_over, y_train_over = over_sampler.fit_resample(X_train, y_train)<br>print(X_train_over.shape)</pre><pre>(10572, 95)</pre><p>After over-sampling, we indeed have a balanced dataset, with half of the training data belonging to the positive class and the other half to the negative class. Now that we have various versions of our dataset to work with, our next step is to build the model. Let’s proceed with that.</p><h3>2. Build Model</h3><h4>2.1. Baseline</h4><p>It’s important to start by establishing a baseline before building our model. In the context of imbalanced data, we need to discuss accuracy.</p><p>To do this, we’ll follow the usual process. First, we’ll examine y_train using the value_counts() method. We’ll then normalize the results by setting normalize to true, and identify the maximum value using the max() method.</p><pre># Calculate the baseline accuracy score for our model<br>acc_baseline = y_train.value_counts(normalize=True).max()<br>print(&quot;Baseline Accuracy:&quot;, round(acc_baseline, 2))<br><br><br>&gt;&gt;&gt; Baseline Accuracy: 0.969</pre><p>The baseline accuracy for this model is almost 97% because 97% of our data belongs to one class, with less than 3% belonging to the other class. This is crucial to understand.</p><p>For example, if someone claims to have built an outstanding bankruptcy model with an accuracy of 94%, it might seem impressive. However, this accuracy score doesn&#39;t exceed the baseline. It simply reflects the imbalance in the data.</p><p>When dealing with imbalanced data, high accuracy scores may not be meaningful if they don’t surpass the baseline. It’s essential to bear this in mind as we move forward to build our model.</p><h4>2.2. Iterate</h4><p>In this part, I mentioned that we will be building three models, as we have three versions of our training data. These versions are regular training data, under-sampled training data, and over-sampled training data. We would like to build a model for each version of the data and compare their performance.</p><p>We will essentially be building the same model three times. We’ll start by using make_pipeline and then address the missing data by using an Imputer. I plan to select the median strategy for handling missing values based on the skewness of our data, and later we can experiment with other strategies. After that, I will add a decision_tree_classifier and set a random state for that as well (random state = 42). These three models will only differ in the training data they are built on.</p><pre># Fit on `X_train`, `y_train`<br>model_reg = make_pipeline(<br>              SimpleImputer(strategy = &quot;median&quot;), <br>              DecisionTreeClassifier(random_state=42))<br>model_reg.fit(X_train, y_train)<br><br># Fit on `X_train_under`, `y_train_under`<br>model_under = make_pipeline(<br>              SimpleImputer(strategy = &quot;median&quot;),<br>              DecisionTreeClassifier(random_state=42))<br>model_under.fit(X_train_under, y_train_under)<br><br># Fit on `X_train_over`, `y_train_over`<br>model_over = make_pipeline(<br>              SimpleImputer(strategy = &quot;median&quot;), <br>              DecisionTreeClassifier(random_state=42))<br>model_over.fit(X_train_over, y_train_over)</pre><p>Now that all three models have been trained, the next step is to evaluate their performance and determine which model performs best.</p><h4>2.3. Evaluate</h4><p>We need to evaluate the performance of three models using the accuracy score as our performance metric. To iterate through the three models, we will use a for loop. We have created a list with our three models, and we will iterate through the loop, referencing each model using the variable name &quot;m&quot;. We will start by applying our training data and then proceed with our test data.</p><p>After running the code, we will annotate the results to differentiate between the regular model, the model trained on the under-sampled data, and the model trained on the over-sample data.</p><pre>for m in [model_reg, model_under, model_over]:<br>     acc_train = m.score(X_train, y_train)<br>     acc_test = m.score(X_test, y_test)<br>     print(&quot;Training Accuracy:&quot;, round(acc_train, 4))<br>     print(&quot;Test Accuracy:&quot;, round(acc_test, 4))</pre><pre>Training Accuracy: 1.0<br>Test Accuracy: 0.9531<br>Training Accuracy: 0.813<br>Test Accuracy: 0.8057<br>Training Accuracy: 1.0<br>Test Accuracy: 0.9604</pre><p>Upon reviewing the results, we found that the training accuracy and the test accuracy for the under-sampled model are poor, indicating that we should discard this model because omitting data points affected its performance negatively.</p><p>Upon discarding the under-sampled model, we compared the regular model and the over-sampled model. We noticed that neither model surpassed the baseline accuracy and that their accuracies were almost identical. This suggests that for future models, we should avoid resampling or choose to use over-sampling for practice.</p><p>While achieving high accuracy scores is progress, it only provides part of the complete picture. We will further analyze the right and wrong predictions made by the models to gain a more nuanced understanding of their performance.</p><p>In order to better understand how our model makes predictions, we want to use a confusion matrix. We will create the confusion matrix in our code and then discuss how to interpret it.</p><p>To plot the confusion matrix to show how our best model performs on our validation set, we will use the confusion_matrix_display from the estimator. We will use model_reg, which performed the best, and the test feature matrix (X_test) and the test target vector (y_test). It&#39;s important to note that we are using the test set to evaluate our model without making any changes to it.</p><p>We&#39;ll suppress the text output with a semicolon and then the confusion matrix will be displayed. Although it may seem confusing at first, we will discuss what a confusion matrix is and how to interpret it.</p><pre>ConfusionMatrixDisplay.from_estimator(model_over, X_test, y_test);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*j_ZBxL8tjajWrqMU3K5kjg.png" /></figure><p>Let’s start with the x-axis which represents our model’s predictions. The two possible predictions are whether a company will go bankrupt or not. Bankruptcy is represented by &quot;True,&quot; which is our positive class, and &quot;False&quot; represents no bankruptcy, our negative class.</p><p>Moving to the y-axis, it represents the true labels: companies that actually went bankrupt (&quot;True&quot;) and those that didn&#39;t (&quot;False&quot;).</p><p>With a confusion matrix, there are now four categories: true positive, true negative, false positive, and false negative. It&#39;s important to understand these terms as the confusion matrix provides more information than just an accuracy score. Remembering the positive and negative classes in our dataset is crucial for interpreting the matrix.</p><p>Let’s revisit the confusion matrix we previously examined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*j_ZBxL8tjajWrqMU3K5kjg.png" /></figure><p>In the upper left-hand corner, we have the true negatives, which represent the instances where we correctly predicted no bankruptcy. On the opposite corner, we find the true positives, where our predictions of bankruptcy were accurate. These two sections represent our correct predictions, with the majority stemming from the true negatives. Our model struggled with identifying true positives, indicating a need for improvement in this area.</p><p>Moving forward, we will focus on enhancing our model’s ability to identify companies at risk of bankruptcy. This will be a key area to address as we continue our analysis. Now that we have completed the model building and evaluation process, there is just one last thing we’d like to check.</p><p>In this part, we won’t be doing any hyperparameter tuning. We’ve already covered a lot, so we’ll save that for a future lesson. However, I think it’s important to understand how deep our model has become. Although our regular model performed the best, I believe we’ll be focusing more on over-sampling in this session. Thus, let’s concentrate on our over-sampled model to get the depth of the model.</p><pre>depth = model_over.named_steps[&quot;decisiontreeclassifier&quot;].get_depth()<br>print(depth)<br><br>&gt;&gt;&gt; 33</pre><p>The depth of this model is around 33, which is quite deep, considering the amount of data we’ve input. This information will be useful for future hyperparameter tuning. With the model-building phase completed, it’s time to move on to communication.</p><h3>3. Communication Results</h3><p>So, at the beginning of the article, I mentioned that we wanted to facilitate two types of communication. Firstly, we aimed to create a deliverable suitable for a non-technical audience, to explain the key features the model considers when making predictions. Secondly, we also wanted to produce a technical deliverable for the potential deployment of the model by a team. Our initial task involves obtaining the feature importances.</p><p>Our focus will be on the &quot;model_over&quot; model, which is a pipeline. So we’ll first access the decision tree classifier using `named_steps()`. Then, we’ll retrieve the feature importances and organize them into a series. I’ll include the data for the series, using the already created `importance`, and label the index with the column names from our training data, which are consistent across all the training sets. I will use `train_over.columns` for this. Lastly, I’ll sort these in ascending order.</p><p>Next, we&#39;ll plot the 15 most significant features by retrieving the tail of the series, as the most significant features are at the bottom. We&#39;ll create a horizontal bar chart for this purpose.</p><pre># Get importances<br>importances = model_over.named_steps[&quot;decisiontreeclassifier&quot;].feature_importances_<br><br># Put importances into a Series<br>feat_imp = pd.Series(importances, index=X_train_over.columns).sort_values()<br><br># Plot series<br>feat_imp.tail(15).plot(kind= &quot;barh&quot;)<br>plt.xlabel(&quot;Gini Importance&quot;)<br>plt.ylabel(&quot;Feature&quot;)<br>plt.title(&quot;model_over Feature Importance&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*syfyVDJXMGdZRgIAgWedFg.jpeg" /></figure><p>We can see that feature_27, which we were focusing on, is one of the most important features of our model. Moving on, we have feature 26. This is a good time to explore feature_26 to see if it makes sense and develop some theories about why it might be a crucial metric.</p><p>Now, we have a great plot to share with our non-technical audience. Next, it’s time to transition to the technical aspects. So it’s time to save our model to a file.</p><p>It’s important to save our model to a file for various reasons. Firstly, we might need to share it with someone in our team for deployment on a website and making predictions. Also, if training the model is time-consuming due to a large dataset, it’s better to save it after training so that we don’t have to repeat the training process every time.</p><p>To save the model, we can use a context manager. In the following code, ‘model.pkl’ represents the file name, and ‘wb’ indicates file is open for writing in binary mode. We utilize the ‘pickle’ library to dump the model into the file. After executing this code, a file named ‘model.pkl’ will be generated, containing the pickled version of the model, which can be shared or saved for later use.</p><pre># save our best-performing model to a a file named `&quot;model-1.pkl&quot;`<br>with open(&quot;model-1.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(model_over, f)</pre><p>Next, let’s explore how to load a saved model. The process of loading the file is similar to the way we loaded files in the last lesson when we were working with JSON files.</p><p>First, we need to use a context handler and then open the file &quot;model-1&quot; with the appropriate permissions for reading in binary mode. We will assign the file to an alias &quot;f&quot;. Then, we will create a variable &quot;loaded_model&quot; and use the pickle.load function to load the contents of the file &quot;f&quot;, which is the pickle file we just saved.</p><pre>with open(&quot;model-1.pkl&quot;, &quot;rb&quot;) as f:<br>     loaded_model = pickle.load(f)<br><br>print(loaded_model)</pre><pre>Pipeline(steps=[(&#39;simpleimputer&#39;, SimpleImputer(strategy=&#39;median&#39;)),<br>                (&#39;decisiontreeclassifier&#39;,<br>                 DecisionTreeClassifier(random_state=42))])</pre><p>Upon printing out the model, we can confirm that we have successfully loaded our model.</p><h3>Conclusion</h3><p>Let’s recap what we did for today. We started by loading our data and noticed the imbalance in the dataset. We learned about addressing this imbalance through resampling, specifically under-sampling and over-sampling. Over-sampling proved to be more effective. We then built multiple models to predict bankruptcy and evaluated their performance, with over-sampling and regular models performing close to the baseline. However, accuracy scores can be misleading with imbalanced data.</p><p>We proceeded to create a confusion matrix to understand how our models were making correct and incorrect predictions, which revealed our models&#39; ability to identify non-bankrupt companies but struggle with bankrupt companies.</p><p>Finally, we saved our trained model to a file using Pickle and then successfully loaded it back. We now aim to improve our model and potentially surpass the baseline in the next part. Take care and happy data science! Goodbye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac5207db7176" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Load and Explore Bankruptcy Data from a JSON File in Python]]></title>
            <link>https://medium.com/@sawsanyusuf/how-to-load-and-explore-bankruptcy-data-from-a-json-file-in-python-fef91ad27d21?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/fef91ad27d21</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 20:33:48 GMT</pubDate>
            <atom:updated>2024-09-23T20:33:48.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8HYcFjkhJYZ1P5sw" /><figcaption>Photo by Timo Volz on Unsplash</figcaption></figure><p>Hello and welcome to part one of our project four, <strong>Bankruptcy in Taiwan</strong>.</p><p>In this project, we will analyze Taiwan&#39;s bankruptcy data to predict whether a company will go bankrupt based on various financial indicators.</p><p>In this first part, we will be finishing the first step, which is acquiring the data, which is stored in a JSON file. We must open the file, explore its contents, and then load it into a dataframe.</p><p>So, our goals for this session are to learn how to open and load its contents (in this case, a JSON file), explore the dataset, and load it into a dataframe.</p><p>We will follow a slightly modified workflow for this part, which involves &quot;open, explore, and import&quot; steps as opposed to the traditional &quot;import, explore, and split&quot; steps.</p><p>For the &quot;open&quot; step, we will open the JSON file. During the exploration phase, we will discuss the JSON file format and syntax, as well as how to troubleshoot coding errors. Moving on to the &quot;import&quot; step, we will import the JSON data into a dataframe, which will be used to train our model.</p><p>The libraries we will be using today include Pandas, as well as two modules from the Python standard library: JSON, for working with JSON data in Python, and compressed data.</p><pre>import json<br>import pandas as pd<br></pre><p>Before getting further to work, let’s talk a little bit about JSON files and how they are organized.</p><p>JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a text-based format and is widely used for transmitting data in web applications, between a server and a client.</p><p>A JSON file typically consists of data organized into key-value pairs. The structure is very similar to how data is organized in dictionaries in Python or objects in JavaScript.</p><p>So now, let’s take a peek inside our file and see what the data looks like.</p><p>Firstly, this file looks very similar to files we&#39;ve seen in the past. It starts with an open curly brace and seems to be organized with open and closing curly braces.</p><pre>{<br>  &quot;schema&quot;: {<br>    &quot;fields&quot;: [<br>      {<br>        &quot;name&quot;: &quot;id&quot;,<br>        &quot;type&quot;: &quot;integer&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_1&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_2&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_3&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_4&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_5&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_6&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;feat_7&quot;,<br>        &quot;type&quot;: &quot;number&quot;<br>      },</pre><p>It seems familiar, similar to dictionaries. One small difference is the use of double quotation marks, which is necessary for JSON but not in Python. Python allows the use of both single and double quotation marks interchangeably.</p><p>So, what we can see is that in this JSON file. In this JSON file, we have three main keys organizing the data: metadata, data, and schema.</p><p>Let&#39;s start with the metadata, which contains information about the dataset&#39;s source, authors, and links to the original article and dataset. This context is important for data cleaning.</p><pre>&quot;metadata&quot;: {<br>  &quot;title&quot;: &quot;Financial ratios and corporate governance indicators <br>              in bankruptcy prediction: A comprehensive study&quot;,<br>  &quot;authors&quot;: &quot;Deron Liang, Chia-Chi Lu, Chih-Fong Tsai, Guan-An Shih&quot;,<br>  &quot;journal&quot;: &quot;European Journal of Operational Research&quot;,<br>  &quot;publicationYear&quot;: 2016,<br>  &quot;articleLink&quot;: &quot;https://doi.org/10.1016/j.ejor.2016.01.012&quot;,<br>  &quot;datasetLink&quot;: &quot;https://archive.ics.uci.edu/ml/datasets/Taiwanese+<br>                       Bankruptcy+Prediction&quot;<br>}</pre><p>The data is a list with 6,819 items. Each item represents an observation in the dataset, containing features and a key-value pair indicating if the company is bankrupt.</p><pre>{&#39;id&#39;: 1,<br> &#39;feat_1&#39;: 0.370594257300249,<br> &#39;feat_2&#39;: 0.424389446140427,<br> &#39;feat_3&#39;: 0.40574977247176,<br> &#39;feat_4&#39;: 0.601457213277793,<br> &#39;feat_5&#39;: 0.601457213277793,<br> &#39;feat_6&#39;: 0.998969203197885,<br> &#39;feat_7&#39;: 0.796887145860514,<br> &#39;feat_8&#39;: 0.808809360876843,<br> &#39;feat_9&#39;: 0.302646433889668,<br> &#39;feat_10&#39;: 0.780984850207341,<br> &#39;feat_11&#39;: 0.0001256968688759,<br> &#39;feat_12&#39;: 0.0,<br> &#39;feat_13&#39;: 0.458143143520965,<br> &#39;feat_14&#39;: 0.0007250725072507,<br> &#39;feat_15&#39;: 0.0,<br> &#39;feat_16&#39;: 0.147949938898487,<br> &#39;feat_17&#39;: 0.147949938898487,<br> &#39;feat_18&#39;: 0.147949938898487,<br> &#39;feat_19&#39;: 0.16914058806845,<br> &#39;feat_20&#39;: 0.311664426681757,<br> &#39;feat_21&#39;: 0.0175597803893099,<br> &#39;feat_22&#39;: 0.0959205276443286,<br> &#39;feat_23&#39;: 0.138736160277171,<br> &#39;feat_24&#39;: 0.0221022783580128,<br> &#39;feat_25&#39;: 0.848194994526472,<br> &#39;feat_26&#39;: 0.688979462807371,<br> &#39;feat_27&#39;: 0.688979462807371,<br> &#39;feat_28&#39;: 0.217535386199635,<br> &#39;feat_29&#39;: 4980000000.0,<br> &#39;feat_30&#39;: 0.000326977269203,<br> &#39;feat_31&#39;: 0.263099983681843,<br> &#39;feat_32&#39;: 0.363725271040572,<br> &#39;feat_33&#39;: 0.0022589633105668,<br> &#39;feat_34&#39;: 0.0012077550852353,<br> &#39;feat_35&#39;: 0.629951302036958,<br> &#39;feat_36&#39;: 0.0212659243655332,<br> &#39;feat_37&#39;: 0.207576261450555,<br> &#39;feat_38&#39;: 0.792423738549445,<br> &#39;feat_39&#39;: 0.0050244547286145,<br> &#39;feat_40&#39;: 0.390284354359258,<br> &#39;feat_41&#39;: 0.006478502486107,<br> &#39;feat_42&#39;: 0.0958848339765825,<br> &#39;feat_43&#39;: 0.137757333534424,<br> &#39;feat_44&#39;: 0.398035698256887,<br> &#39;feat_45&#39;: 0.0869565217391304,<br> &#39;feat_46&#39;: 0.0018138841264849,<br> &#39;feat_47&#39;: 0.0034873642818412,<br> &#39;feat_48&#39;: 0.0001820925974295,<br> &#39;feat_49&#39;: 0.0001165006532358,<br> &#39;feat_50&#39;: 0.0329032258064516,<br> &#39;feat_51&#39;: 0.0341641819543792,<br> &#39;feat_52&#39;: 0.392912869451166,<br> &#39;feat_53&#39;: 0.0371353015800987,<br> &#39;feat_54&#39;: 0.67277529248986,<br> &#39;feat_55&#39;: 0.166672958825266,<br> &#39;feat_56&#39;: 0.190642959052727,<br> &#39;feat_57&#39;: 0.004094405952288,<br> &#39;feat_58&#39;: 0.001996770860645,<br> &#39;feat_59&#39;: 0.0001473360247605,<br> &#39;feat_60&#39;: 0.147308450425486,<br> &#39;feat_61&#39;: 0.334015171333379,<br> &#39;feat_62&#39;: 0.276920158240506,<br> &#39;feat_63&#39;: 0.001035989991658,<br> &#39;feat_64&#39;: 0.676269176153092,<br> &#39;feat_65&#39;: 0.721274551521743,<br> &#39;feat_66&#39;: 0.339077006789355,<br> &#39;feat_67&#39;: 0.02559236799775,<br> &#39;feat_68&#39;: 0.903224771166726,<br> &#39;feat_69&#39;: 0.0020216130120256,<br> &#39;feat_70&#39;: 0.064855707690831,<br> &#39;feat_71&#39;: 701000000.0,<br> &#39;feat_72&#39;: 6550000000.0,<br> &#39;feat_73&#39;: 0.593830503987655,<br> &#39;feat_74&#39;: 458000000.0,<br> &#39;feat_75&#39;: 0.6715676535815,<br> &#39;feat_76&#39;: 0.424205762216667,<br> &#39;feat_77&#39;: 0.676269176153092,<br> &#39;feat_78&#39;: 0.339077006789355,<br> &#39;feat_79&#39;: 0.126549487816618,<br> &#39;feat_80&#39;: 0.637555395323871,<br> &#39;feat_81&#39;: 0.458609147666847,<br> &#39;feat_82&#39;: 0.52038191789012,<br> &#39;feat_83&#39;: 0.312904948119326,<br> &#39;feat_84&#39;: 0.11825047660899,<br> &#39;feat_85&#39;: 0,<br> &#39;feat_86&#39;: 0.716845343217827,<br> &#39;feat_87&#39;: 0.0092194400211029,<br> &#39;feat_88&#39;: 0.622878959445127,<br> &#39;feat_89&#39;: 0.601453290101533,<br> &#39;feat_90&#39;: 0.82789021403512,<br> &#39;feat_91&#39;: 0.29020189277926,<br> &#39;feat_92&#39;: 0.0266006307607414,<br> &#39;feat_93&#39;: 0.564050112276341,<br> &#39;feat_94&#39;: 1,<br> &#39;feat_95&#39;: 0.0164687409123162,<br> &#39;bankrupt&#39;: &#39;true&#39;}</pre><p>It’s worth noting that the boolean value True is represented as &quot;true&quot; in JSON, but in Python, it’s represented as &quot;True.&quot; This distinction means we can’t directly interpret JSON in Python and will need to translate it to manipulate the data.</p><p>Finally, the schema includes the primary key (likely the index column) and the fields with their corresponding data types. This information is crucial for importing the data into a pandas data frame, especially for more complex data schemas. The primary takeaway is that we have data, metadata, and schema.</p><pre>{&#39;fields&#39;: [{&#39;name&#39;: &#39;id&#39;, &#39;type&#39;: &#39;integer&#39;},<br>  {&#39;name&#39;: &#39;feat_1&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_2&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_3&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_4&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_5&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_6&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_7&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_8&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_9&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_10&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_11&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_12&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_13&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_14&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_15&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_16&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_17&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_18&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_19&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_20&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_21&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_22&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_23&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_24&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_25&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_26&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_27&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_28&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_29&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_30&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_31&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_32&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_33&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_34&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_35&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_36&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_37&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_38&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_39&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_40&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_41&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_42&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_43&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_44&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_45&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_46&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_47&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_48&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_49&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_50&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_51&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_52&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_53&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_54&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_55&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_56&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_57&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_58&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_59&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_60&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_61&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_62&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_63&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_64&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_65&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_66&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_67&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_68&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_69&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_70&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_71&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_72&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_73&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_74&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_75&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_78&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_79&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_79&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_80&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_81&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_82&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_83&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_84&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_85&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_86&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_87&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_88&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_89&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_90&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_91&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_92&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_93&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_94&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;feat_95&#39;, &#39;type&#39;: &#39;number&#39;},<br>  {&#39;name&#39;: &#39;bankrupt&#39;, &#39;type&#39;: &#39;boolean&#39;}],<br> &#39;primaryKey&#39;: [&#39;id&#39;],<br> &#39;pandas_version&#39;: &#39;0.20.0&#39;}</pre><p>Now that we understand the dataset’s structure, we need to load it into Python and convert it into a dataframe.</p><h3>1. Prepare Data</h3><h4>1.1. Open</h4><p>We have the data in a JSON file and we have a rough idea of its structure. We want to put this data into a dataframe. My first thought is to check if there’s a way to load the data directly into a dataframe using a tool provided by the Pandas library. After searching for &quot;Pandas JSON,&quot; I found the read_json command, similar to read_csv.</p><pre>df = pd.read_json(&quot;taiwan-bankruptcy-data.json&quot;)<br>df.head()<br></pre><pre>ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.<br></pre><p>We’ve encountered an error:</p><p>ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.</p><p>When we face an error, try searching for the error message on the web. Stack Overflow is a useful resource for finding solutions to problems like this. Here are three things to keep in mind when using Stack Overflow:</p><p>1. Context: Look for specific questions that provide relevant details about the issue, such as the operating system, hardware, and the code that caused the error.<br>2. Reproducible Code: Make sure the question includes enough information for you to reproduce the problem yourself.<br>3. An Answer: Look for questions that have been answered, indicated by a green check mark next to the solution. Give the suggested solution a try to see if it resolves your problem.</p><p>After locating a relevant post, one of the answers that include all of what we search for, saying that we just need to use pythons built-in JSON handling capabilities, and they actually give us a full bit of code to work with. They tell us what we need to import, they’re actually showing us how to open the file and then load the data. This is very good, and now we will try to redo this and see if we can do it in a better way and get that data into a dataframe.</p><p>Just a note, it’s important to note that while it is acceptable to reuse small code snippets from public forums, using substantial portions of code from private repositories without an explicit license for reuse is not permissible.</p><p>Let’s go back to the code, we’ve got this code:</p><pre># Open file and load JSON<br>with open(&quot;filename.json&quot;,&quot;r&quot;) as read_file:<br>      data = json.load(read_file)</pre><p>And if we have a compressed version of the JSON file, we need to import the gzip library to decompress the file :</p><pre>import gizp<br><br>with gzip.open (&quot;filename.json.gz&quot;, &quot;r&quot;) as read_file:<br>     data = json.load(read_file)</pre><p>Now, because our file is decompressed, we’ll use the first one, but still, we need to make a few adjustments. Firstly, the file name should be changed, and the alias for the data file should also be updated. Finally, I need to rename the variable storing the loaded data.</p><p>Once these changes are applied, the code be ready for execution.</p><pre>with open(&quot;taiwan-bankruptcy-data.json&quot;,&quot;r&quot;) as read_file:<br>       taiwan_data = json.load(read_file)</pre><p>Now, what&#39;s going on here? Well, the first thing you need to see, is this first line is called a context handler. Let&#39;s start by understanding the concept of a context handler. A context handler is typically used to open a file, perform certain operations, and then automatically close the file to maintain system cleanliness. This is done by running the indented code within the context handler.</p><p>It’s important to note that we have already imported the necessary JSON file at the beginning of the article, so we’re all set. Now, we can proceed by using the JSON library and its load function to open the file and read its contents into a variable called “taiwan_data”.</p><p>Additionally, it&#39;s worth mentioning that we have opened the file with read permissions, indicated by &#39;r&#39;, which means we are only able to read the file&#39;s contents and cannot write to it, preventing accidental overwrites.</p><p>After running this code, we will print out the data and check its type to ensure that “taiwan_data” is indeed a dictionary. This confirms that the JSON library has successfully transformed the information from our JSON file into a dictionary format, allowing us to work with it using Python.</p><pre>print(type(taiwan_data))<br><br>&gt;&gt;&gt; &lt;class &#39;dict&#39;&gt;</pre><h4>1.2. Explore</h4><p>Now, we’ve successfully loaded our data into a dictionary, and now we want to verify that what’s in the dictionary matches the JSON file. The dictionary has three parent keys: data, metadata, and schema, and we want to confirm that they’re all present in the dictionary.</p><p>We’ll start by checking the keys in the dictionary using the command Poland_data.keys().</p><pre>taiwan_data.keys()</pre><pre>dict_keys([&#39;schema&#39;, &#39;data&#39;, &#39;metadata&#39;])</pre><p>We see that we have schema, data, and metadata, which confirm that the loading was successful.</p><p>schema tells us how the data is structured, metadata tells us where the data comes from, and data is the data itself.</p><p>Now, we’ll explore further to ensure everything is working as expected and to familiarize ourselves with the data content.</p><p>We’ll continue by exploring the metadata to check if it matches the original file.</p><pre>poland_data[&#39;metadata&#39;].keys()</pre><pre>dict_keys([&#39;title&#39;, &#39;authors&#39;, &#39;journal&#39;, &#39;publicationYear&#39;, <br>         &#39;articleLink&#39;, &#39;datasetLink&#39;])</pre><p>We can see the name of the article and a link to the data source. Next, we’ll examine the schema.</p><pre>poland_data[&#39;schema&#39;].keys()</pre><pre>dict_keys([&#39;fields&#39;, &#39;primaryKey&#39;, &#39;pandas_version&#39;])</pre><p>We can see the expected keys: fields, primary key, and pandas version.</p><p>Moving on to the data, we’ll inspect the type associated with the &#39;data&#39; key in “taiwan_data”, which is a list. Since the list contains 6,819 items, we’ll just look at the first item.</p><pre>taiwan_data[&quot;data&quot;][0]</pre><pre> {&#39;id&#39;: 1,<br> &#39;feat_1&#39;: 0.370594257300249,<br> &#39;feat_2&#39;: 0.424389446140427,<br> &#39;feat_3&#39;: 0.40574977247176,<br> &#39;feat_4&#39;: 0.601457213277793,<br> &#39;feat_5&#39;: 0.601457213277793,<br> &#39;feat_6&#39;: 0.998969203197885,<br> &#39;feat_7&#39;: 0.796887145860514,<br> &#39;feat_8&#39;: 0.808809360876843,<br> &#39;feat_9&#39;: 0.302646433889668,<br> &#39;feat_10&#39;: 0.780984850207341,<br> &#39;feat_11&#39;: 0.0001256968688759,<br> &#39;feat_12&#39;: 0.0,<br> &#39;feat_13&#39;: 0.458143143520965,<br> &#39;feat_14&#39;: 0.0007250725072507,<br> &#39;feat_15&#39;: 0.0,<br> &#39;feat_16&#39;: 0.147949938898487,<br> &#39;feat_17&#39;: 0.147949938898487,<br> &#39;feat_18&#39;: 0.147949938898487,<br> &#39;feat_19&#39;: 0.16914058806845,<br> &#39;feat_20&#39;: 0.311664426681757,<br> &#39;feat_21&#39;: 0.0175597803893099,<br> &#39;feat_22&#39;: 0.0959205276443286,<br> &#39;feat_23&#39;: 0.138736160277171,<br> &#39;feat_24&#39;: 0.0221022783580128,<br> &#39;feat_25&#39;: 0.848194994526472,<br> &#39;feat_26&#39;: 0.688979462807371,<br> &#39;feat_27&#39;: 0.688979462807371,<br> &#39;feat_28&#39;: 0.217535386199635,<br> &#39;feat_29&#39;: 4980000000.0,<br> &#39;feat_30&#39;: 0.000326977269203,<br> &#39;feat_31&#39;: 0.263099983681843,<br> &#39;feat_32&#39;: 0.363725271040572,<br> &#39;feat_33&#39;: 0.0022589633105668,<br> &#39;feat_34&#39;: 0.0012077550852353,<br> &#39;feat_35&#39;: 0.629951302036958,<br> &#39;feat_36&#39;: 0.0212659243655332,<br> &#39;feat_37&#39;: 0.207576261450555,<br> &#39;feat_38&#39;: 0.792423738549445,<br> &#39;feat_39&#39;: 0.0050244547286145,<br> &#39;feat_40&#39;: 0.390284354359258,<br> &#39;feat_41&#39;: 0.006478502486107,<br> &#39;feat_42&#39;: 0.0958848339765825,<br> &#39;feat_43&#39;: 0.137757333534424,<br> &#39;feat_44&#39;: 0.398035698256887,<br> &#39;feat_45&#39;: 0.0869565217391304,<br> &#39;feat_46&#39;: 0.0018138841264849,<br> &#39;feat_47&#39;: 0.0034873642818412,<br> &#39;feat_48&#39;: 0.0001820925974295,<br> &#39;feat_49&#39;: 0.0001165006532358,<br> &#39;feat_50&#39;: 0.0329032258064516,<br> &#39;feat_51&#39;: 0.0341641819543792,<br> &#39;feat_52&#39;: 0.392912869451166,<br> &#39;feat_53&#39;: 0.0371353015800987,<br> &#39;feat_54&#39;: 0.67277529248986,<br> &#39;feat_55&#39;: 0.166672958825266,<br> &#39;feat_56&#39;: 0.190642959052727,<br> &#39;feat_57&#39;: 0.004094405952288,<br> &#39;feat_58&#39;: 0.001996770860645,<br> &#39;feat_59&#39;: 0.0001473360247605,<br> &#39;feat_60&#39;: 0.147308450425486,<br> &#39;feat_61&#39;: 0.334015171333379,<br> &#39;feat_62&#39;: 0.276920158240506,<br> &#39;feat_63&#39;: 0.001035989991658,<br> &#39;feat_64&#39;: 0.676269176153092,<br> &#39;feat_65&#39;: 0.721274551521743,<br> &#39;feat_66&#39;: 0.339077006789355,<br> &#39;feat_67&#39;: 0.02559236799775,<br> &#39;feat_68&#39;: 0.903224771166726,<br> &#39;feat_69&#39;: 0.0020216130120256,<br> &#39;feat_70&#39;: 0.064855707690831,<br> &#39;feat_71&#39;: 701000000.0,<br> &#39;feat_72&#39;: 6550000000.0,<br> &#39;feat_73&#39;: 0.593830503987655,<br> &#39;feat_74&#39;: 458000000.0,<br> &#39;feat_75&#39;: 0.6715676535815,<br> &#39;feat_76&#39;: 0.424205762216667,<br> &#39;feat_77&#39;: 0.676269176153092,<br> &#39;feat_78&#39;: 0.339077006789355,<br> &#39;feat_79&#39;: 0.126549487816618,<br> &#39;feat_80&#39;: 0.637555395323871,<br> &#39;feat_81&#39;: 0.458609147666847,<br> &#39;feat_82&#39;: 0.52038191789012,<br> &#39;feat_83&#39;: 0.312904948119326,<br> &#39;feat_84&#39;: 0.11825047660899,<br> &#39;feat_85&#39;: 0,<br> &#39;feat_86&#39;: 0.716845343217827,<br> &#39;feat_87&#39;: 0.0092194400211029,<br> &#39;feat_88&#39;: 0.622878959445127,<br> &#39;feat_89&#39;: 0.601453290101533,<br> &#39;feat_90&#39;: 0.82789021403512,<br> &#39;feat_91&#39;: 0.29020189277926,<br> &#39;feat_92&#39;: 0.0266006307607414,<br> &#39;feat_93&#39;: 0.564050112276341,<br> &#39;feat_94&#39;: 1,<br> &#39;feat_95&#39;: 0.0164687409123162,<br> &#39;bankrupt&#39;: &#39;true&#39;}</pre><p>This initial check confirms that the data is structured correctly, including the representation of boolean values.</p><p>Everything looks promising, and we want to consider the data’s dimensionality as we plan to convert the dictionary into a dataframe. When we access the “data” key, we find that it contains a list. To count the number of items in a list, we can use the “len” command.</p><pre>len(taiwan_data[&quot;data&quot;])<br><br>&gt;&gt;&gt; 6819</pre><p>After using the “len” command on the list, we find that there are 6,819 observations. Therefore, when we load this data into a data frame, we should expect 6,819 rows.</p><p>Now, let’s move on to determining the number of columns in our dataframe. We want to calculate the number of features associated with the company with ID “1.”</p><pre>len(taiwan_data[&quot;data&quot;][0])<br><br>&gt;&gt;&gt; 97</pre><p>After retrieving the data for Company One from the &quot;taiwan_data&quot; list, we found that there are 97 features associated with Company One.</p><p>We know that one of these features will be the index, so our data frame should have 6,819 rows and 96 columns (excluding the index). To ensure that all companies in our dataset have the same number of features, we’ll iterate through the list of data using a for loop and check whether each company has 97 features.</p><pre>for item in taiwan_data[&quot;data&quot;]:<br>      if len(item) != 97:<br>         print(&quot;ALERT!!&quot;)</pre><p>After completing this check, we found that all companies have 97 features, including the index.</p><p>This information provides us with a clear understanding of our dataset. And now, we want to convert our dictionary into a data frame. To accomplish this, we’ll use the from_dict() method. We start by importing Pandas, then create a data frame using the from_dict() method, passing in the dictionary data. Finally, we’ll use the set_index() method to set the Company ID as the index.</p><pre>df = pd.DataFrame().from_dict(taiwan_data[&quot;data&quot;]).set_index(&quot;id&quot;)<br>print(df.shape)<br>df.head()</pre><pre>(6819, 96)<br><br>	feat_1	         feat_2	         feat_3	         feat_4	         feat_5	         feat_6	         feat_7	        feat_8	         feat_9	        feat_10	        ...     feat_87	        feat_88	         feat_89	feat_90	        feat_91	         feat_92	feat_93	    feat_94	feat_95	     bankrupt<br>id																					<br>1	0.370594	0.424389	0.405750	0.601457	0.601457	0.998969	0.796887	0.808809	0.302646	0.780985	...	0.009219	0.622879	0.601453	0.827890	0.290202	0.026601	0.564050	1	0.016469	true<br>2	0.464291	0.538214	0.516730	0.610235	0.610235	0.998946	0.797380	0.809301	0.303556	0.781506	...	0.008323	0.623652	0.610237	0.839969	0.283846	0.264577	0.570175	1	0.020794	true<br>3	0.426071	0.499019	0.472295	0.601450	0.601364	0.998857	0.796403	0.808388	0.302035	0.780284	...	0.040003	0.623841	0.601449	0.836774	0.290189	0.026555	0.563706	1	0.016474	true<br>4	0.399844	0.451265	0.457733	0.583541	0.583541	0.998700	0.796967	0.808966	0.303350	0.781241	...	0.003252	0.622929	0.583538	0.834697	0.281721	0.026697	0.564663	1	0.023982	true<br>5	0.465022	0.538432	0.522298	0.598783	0.598783	0.998973	0.797366	0.809304	0.303475	0.781550	...	0.003878	0.623521	0.598782	0.839973	0.278514	0.024752	0.575617	1	0.035490	true<br><br>5 rows × 96 columns</pre><p>The resulting data frame has 6,819 rows and 96 columns.</p><h4>1.3. Import</h4><p>To streamline the process, let’s combine all these steps into<br>a single function that will open the file, load it into a DataFrame, and return it to us assomething we can use. First, we open the JSON file and load it into a dictionary. Then, we load the dictionary into a data frame.</p><pre>def wrangle(filename):<br>      #open the file, load into dict<br>      with open (filename, &quot;r&quot;) as f:<br>          data = json.load(f)<br><br>      # Turn dict into DataFrame<br>      df = pd.DataFrame().from_dict(data[&quot;data&quot;]).set_index(&quot;company_id&quot;)<br><br>      return df</pre><pre>df = wrangle(&quot;taiwan-bankruptcy-data.json&quot;)<br>print(df.shape)<br>df.head()</pre><pre>(6819, 96)<br><br>	feat_1	         feat_2	         feat_3	         feat_4	         feat_5	         feat_6	         feat_7	        feat_8	         feat_9	        feat_10	        ...     feat_87	        feat_88	         feat_89	feat_90	        feat_91	         feat_92	feat_93	    feat_94	feat_95	     bankrupt<br>id																					<br>1	0.370594	0.424389	0.405750	0.601457	0.601457	0.998969	0.796887	0.808809	0.302646	0.780985	...	0.009219	0.622879	0.601453	0.827890	0.290202	0.026601	0.564050	1	0.016469	true<br>2	0.464291	0.538214	0.516730	0.610235	0.610235	0.998946	0.797380	0.809301	0.303556	0.781506	...	0.008323	0.623652	0.610237	0.839969	0.283846	0.264577	0.570175	1	0.020794	true<br>3	0.426071	0.499019	0.472295	0.601450	0.601364	0.998857	0.796403	0.808388	0.302035	0.780284	...	0.040003	0.623841	0.601449	0.836774	0.290189	0.026555	0.563706	1	0.016474	true<br>4	0.399844	0.451265	0.457733	0.583541	0.583541	0.998700	0.796967	0.808966	0.303350	0.781241	...	0.003252	0.622929	0.583538	0.834697	0.281721	0.026697	0.564663	1	0.023982	true<br>5	0.465022	0.538432	0.522298	0.598783	0.598783	0.998973	0.797366	0.809304	0.303475	0.781550	...	0.003878	0.623521	0.598782	0.839973	0.278514	0.024752	0.575617	1	0.035490	true<br><br>5 rows × 96 columns</pre><h3>Conclusion</h3><p>Let’s quickly recap what we’ve covered before moving on to the next part. First, we learned how to use a context manager to open and load a JSON file into a dictionary, regardless of whether it was compressed or decompressed. Then, we extensively explored the dictionary, which helped us reacquaint ourselves with a dictionary mindset.</p><p>Finally, we transformed the dictionary into a proper dataframe, which will enable us to train a model. We also combined the steps of opening a file and turning it into a dataframe into a single function, making it easy to wrangle the data with just one line of code. In the next session, we’ll continue exploring the data and build our first model. I look forward to seeing you in part two. Goodbye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fef91ad27d21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Demographic Features to a Logistic Regression Model: Investigating the Impact of Caste on…]]></title>
            <link>https://medium.com/@sawsanyusuf/earthquake-damage-in-nepal-4-beyond-the-model-data-ethics-4cc7c94dcc43?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cc7c94dcc43</guid>
            <category><![CDATA[data-ethics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 21:02:39 GMT</pubDate>
            <atom:updated>2024-09-22T20:40:03.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adding Demographic Features to a Logistic Regression Model: Investigating the Impact of Caste on Earthquake Damage Prediction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTYAUcsb7zRuDskhz_NBTw.jpeg" /></figure><p>Hello and welcome everyone to the final part of our project, Project 3. In this session, we’ll be using the tools we’ve already learned about to build a model and explore the question of ethics in interpreting and using the model in the real world.</p><p>For today, our main goals are:</p><ol><li>Prepare a household dataset for binary classification, specifically focusing on the ‘household_demographics’ table in the database.</li><li>Group high cardinality categorical features into a smaller number of categories for exploration.</li><li>Create a logistic regression model to predict severe damage and explain model predictions using odds ratios.</li><li>Investigate important features related to “caste,” a demographic piece in the database, to understand how the model uses these features.</li></ol><p>Following our ML workflow, we’ll work with the new table, the household_demographics table, for data preparation. Our exploration will involve grouping high cardinality categorical features and the split will remain the same, just train and test split this time. Building the model will be familiar, serving as another opportunity to build muscle memory. When it comes to new content, we’ll be communicating results by looking at odds ratios and investigating the apparent role of cast in building damage.</p><p>In terms of libraries, there won&#39;t be any new ones used today. We&#39;ll be using familiar tools from Sqlit3 to pull data out of the database to build a pipeline. It&#39;s just another opportunity to get more familiar with our old friends.</p><pre>import sqlite3<br>import warnings<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>from category_encoders import OneHotEncoder<br><br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import Pipeline, make_pipeline<br><br>warnings.simplefilter(action=&quot;ignore&quot;, category=FutureWarning)<br></pre><h3>1. Prepare Data</h3><p>First, we need to connect to the database.</p><pre>%load_ext sql<br>%sql sqlite:///nepal.sqlite<br></pre><p>Once connected, we can start by examining the household_demographics table. We’ll retrieve the first five rows of the table.</p><pre>SELECT * <br>FROM household_demographics <br>LIMIT 5<br></pre><pre>household_id	gender_household_head	age_household_head	caste_household	education_level_household_head	income_level_household	size_household	is_bank_account_present_in_household<br>101     	Male            	31.0	                Rai	        Illiterate              	Rs. 10 thousand	         3.0       	0.0<br>201      	Female          	62.0                  	Rai	        Illiterate              	Rs. 10 thousand	         6.0    	0.0<br>301	        Male             	51.0	                Gharti/Bhujel	Illiterate              	Rs. 10 thousand	         13.0   	0.0<br>401	        Male             	48.0            	Gharti/Bhujel	Illiterate	                Rs. 10 thousand	         5.0     	0.0<br>501	        Male            	70.0             	Gharti/Bhujel	Illiterate	                Rs. 10 thousand	         8.0	        0.0</pre><p>After reviewing the returned table, we observed that there is a household ID column. Each row in the table corresponds to an individual household, and we have information about the head of each household, including gender, age, caste, education level, head income size, and whether they have a bank account.</p><p>Next, let’s determine the table size.</p><pre>%%sql<br>select count(*) from household_demographics<br></pre><pre>* sqlite:///nepal.sqlite Done.<br><br>count(*)<br>249932<br></pre><p>This table has around 250,000 observations. We plan to merge it with the ones we previously worked with and create our dataset. As we have noticed, this table includes the household ID column found in the id_map table.</p><pre>%%sql<br>select * from id_map limit 5<br></pre><pre>* sqlite:///nepal.sqlite Done.<br><br>household_id building_id  vdcmun_id  district_id<br>5601         56            7          1<br>6301         63            7          1<br>9701         97            7          1<br>9901         99            7          1<br>11501        115           7          1  <br></pre><p>In our new dataset, we will include all the columns from household_demographics, all the columns from buildings_structure, only the municipality ID column from id_map, and the ‘damage_grade’ column from building_damage (which will be our target variable). We will merge all the household demographic information with all the building structure information, and then add the municipality ID and the target variable.</p><p>We will be doing this step-by-step. Let’s start with the household demographics table. We will use an alias &quot;h&quot; for the household_demographics table, and then add an alias for the id_map table as &quot;i&quot;. Following that, we will add columns from the id_map table, and then proceed to join the building_structure table using an alias &quot;s&quot;. We will then add all the columns from the household demographics and building structure tables.</p><p>As a left join, we will join the building_damage table (using an alias &quot;d&quot;) and add the damage grade column. Finally, we will limit the results to only households in Gorka by adding a where clause with the condition &quot;district ID district = 4&quot;.</p><pre>%%sql<br>select h.*, <br>       s.*,<br>       i. vdcmun_id,<br>       d.damage_grade<br>from household_demographics as h<br>join id_map as i on i.household_id = h.household_id<br>join building_structure as s on i.building_id = s.building_id<br>join building_damage as d on i.building_id = d.building_id<br>where district_id = 4<br>limit 5<br></pre><p>The next step is to take this query and put it into our wrangle function.</p><h4>1.1. Import</h4><p>The first step is to convert the query into a query string and then read the results into a dataframe. Once that’s done, I’ll use the wrangle function to get the results into a data frame.</p><pre>def wrangle(db_path):<br>       # Connect to database<br>       conn = sqlite3.connect(db_path)<br>       # Construct query<br>       query = &quot;&quot;&quot;<br>            select h.*,<br>                   s.*,<br>                   i. vdcmun_id,<br>                   d.damage_grade<br>            from household_demographics AS h<br>            join id_map as i on i.household_id = h.household_id<br>            join building_structure as s on i.building_id = s.building_id<br>            join building_damage as d on i.building_id = d.building_id<br>            where district_id = 4<br>            &quot;&quot;&quot;<br>       # Read query results into DataFrame<br>       df = pd.read_sql(query, conn, index_col= &quot;household_id&quot;)<br>       <br>       # Identify leaky columns<br>       drop_cols = [col for col in df.columns if &quot;post_eq&quot; in col]<br><br>       # Add high-cardinality / redundant column<br>       drop_cols.append(&quot;building_id&quot;)<br><br>       # Create binary target column<br>       df[&quot;damage_grade&quot;] = df[&quot;damage_grade&quot;].str[-1].astype(int)<br>       df[&quot;severe_damage&quot;] = (df[&quot;damage_grade&quot;] &gt; 3).astype(int)<br><br>       # Drop old target<br>       drop_cols.append(&quot;damage_grade&quot;)<br><br>       # Drop multicollinearity column<br>       drop_cols.append(&quot;count_floors_pre_eq&quot;)<br><br>       # Drop columns<br>       df.drop(columns=drop_cols, inplace=True)<br><br>       return df</pre><pre>df = wrangle(&quot;nepal.sqlite&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yHbkCF4CJopW5KOGiQlaw.png" /></figure><p>We’ve prepared the dataframe, so it’s time to start exploring the data.</p><h4>1.2. Explore</h4><p>We’ve noticed that many features in the household_demographics table have categorical values, so we’ll need to check for low or high-cardinality features that might require some attention.</p><pre># Check for high- and low-cardinality categorical features<br>df.select_dtypes(&quot;object&quot;).nunique()<br></pre><pre>gender_household_head           2<br>caste_household                 63<br>education_level_household_head  19<br>income_level_household          5<br>land_surface_condition          3<br>foundation_type                 5<br>roof_type                       3<br>ground_floor_type               5<br>other_floor_type                4<br>position                        4<br>plan_configuration              10<br>superstructure                  11<br>dtype: int64</pre><p>It seems that the education level with 19 unique values is fine for now. However, the categorical variable &quot;caste_household&quot; with 63 unique values needs some data cleaning.</p><p>Before making any decisions, let&#39;s conduct further exploration. I&#39;ll start by doing some value counts. Instead of generating the entire series, I&#39;ll just look at the first 10 values.</p><pre>df[&quot;caste_household&quot;].value_counts().head(10)</pre><pre>                   count<br>caste_household	<br>Gurung             15119        <br>Brahman-Hill       13043<br>Chhetree            8766<br>Magar               8180<br>Sarki               6052<br>Newar               5986<br>Kami                3565<br>Tamang              2396<br>Kumal               2271<br>Damai/Dholi         1977 <br></pre><p>The largest group in our dataset is &quot;Gurung,&quot; and there are several other groups following that. Let’s also look at the smallest or least represented groups. So, I’ll check the last 15 rows.</p><pre>df[&quot;caste_household&quot;].value_counts().tail(15)                        </pre><pre>                        count<br>caste_household	<br>Khatwe	                   2<br>Lepcha	                   2<br>Satar/Santhal	           2<br>Meche	                   2<br>Kalar	                   2<br>Chamling	           2<br>Mewahang Bala	           1<br>Byasi/Sauka	           1<br>Yakkha	                   1<br>Kahar	                   1<br>Koche	                   1<br>Natuwa	                   1<br>Bantar/Sardar	           1<br>Dev	                   1<br>Pattharkatta/Kushwadiya	   1</pre><p>It’s interesting to note that we have several groups with very few examples in our dataset. In such cases, data scientists commonly aggregate these into a single category called &quot;Other.&quot;</p><p>I propose that we take the top 10 ethnicities by count and place all other values into the &quot;other&quot; category. To achieve this, we can use value_counts() to extract the top 10 and then rework the column accordingly. First, I’ll obtain the list of the top 10 names using the index method.</p><pre>top_10 = df[&quot;caste_household&quot;].value_counts().head(10).index</pre><p>Now that we have the names of the top 10, we can rework the column so that any values not in this list are categorized as &quot;Other.&quot; I’ll use a lambda function for this purpose.</p><pre>df[&quot;caste_household&quot;] = df[&quot;caste_household&quot;].apply(<br>        lambda c: c if c in top_10 else &quot;Other&quot;<br>)</pre><p>After applying the lambda function to the column, let’s check the value counts to verify that the reassignment was successful. The goal is to have 11 unique values, consisting of the top 10 and the &quot;Other&quot; category.</p><pre>df[&quot;caste_household&quot;].value_counts()                        </pre><pre>                   count<br>caste_household	<br>Gurung             15119        <br>Brahman-Hill       13043<br>Chhetree            8766<br>Other               8528<br>Magar               8180<br>Sarki               6052<br>Newar               5986<br>Kami                3565<br>Tamang              2396<br>Kumal               2271<br>Damai/Dholi         1977 </pre><p>Once this is done, I’ll incorporate the code into our wrangle function and reassign the resulting series to the column. After re-running the wrangle function, we can confirm that the cast household column now has 11 unique values.</p><pre>df[&quot;caste_household&quot;].nunique()<br><br><br>&gt;&gt;&gt; 11</pre><h4>1.3. Split</h4><p>It’s time to perform our vertical split, separating the feature matrix and the target vector. Before doing that, I noticed that there was one high-cardinality categorical feature that we didn’t discuss. It didn’t even show up because it was encoded as an integer, and that is &#39;vdcmun_id’, which stands for the municipality ID.</p><p>Every municipality in our district has a unique identifier, but it&#39;s a high-cardinality feature that we&#39;re not going to use in our model. However, we will use it later on in the communication phase, so instead of dropping it in a wrangle function, we&#39;ll leave it in but ensure that it doesn&#39;t end up in our feature matrix.</p><p>Therefore, our split will be a bit different from the usual. I’ll use &#39;df.drop&#39; and pass in a list of columns to drop. The first item in the list will be our target &#39;severe_damage’, which we defined earlier. The other one will be &#39;vdcmun_id’. Finally, we’ll need to create our target vector.</p><pre>target = &quot;severe_damage&quot;<br>X = df.drop(columns= [target, &quot;vdcmun_id&quot;])<br>y = df[target]</pre><p>Now let’s make the horizontal split, we’ll divide our data into training and test sets using a randomized train-test split. Our test set will be 20% of our total data.</p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>         X,y, test_size=0.2, random_state=42<br>)</pre><h3>2. Build Model</h3><p>Now we’ll build our model. We’ll start with the same baseline accuracy, around 64%. Then we’ll build the model using a one-hot encoder with logistic regression. To avoid convergence warnings, I’ll increase the number of max iterations to 3000, which means a longer training time.</p><pre>acc_baseline = y_train.value_counts(normalize=True).max()<br>print(&quot;Baseline Accuracy:&quot;, round(acc_baseline, 2))<br><br>model_lr = make_pipeline (<br>     OneHotEncoder(use_cat_names=True),<br>     LogisticRegression(max_iter=3000)<br>)<br>model_lr.fit( X_train, y_train )<br><br>acc_train = model_lr.score(X_train, model_lr.predict(X_train))<br>acc_test = model_lr.score(X_test, y_test)<br>print(&quot;LR Training Accuracy:&quot;, acc_train)<br>print(&quot;LR Testing Accuracy:&quot;, acc_test)</pre><pre>Baseline Accuracy: 0.63<br>LR Training Accuracy: 0.7258296558858586<br>LR Testing Accuracy: 0.7189826711471305</pre><p>The accuracy score remained consistent at around 0.71-0.72 for both training and test sets, indicating no overfitting issue. The model seemed to be performing well. So next, we actually need to take the information out of the model and make some plots to explain why our model is making the predictions that it’s making.</p><h3>3. Communication Results</h3><p>The first step is to extract our features and our importances, and then put them together in a series.</p><p>To proceed, I will start with the one-hot encoder for the feature names. Then, I’ll extract the importances by accessing the logistic regression coefficients. We need to handle the coefficients returned as a nested list, so I will retrieve the inner list and organize it into a pandas series, using feature names as the index.</p><p>Since logistic regression involves odds ratios rather than feature importances, I will convert the importances using the exponential function (np.exp) and then sort the values.</p><pre>features = model_lr.named_steps[&quot;onehotencoder&quot;].get_feature_names()<br>importances = model_lr.named_steps[&quot;logisticregression&quot;].coef_[0]<br>feat_imp = pd.Series(np.exp(importances), index=features).sort_values()<br>feat_imp.head()<br></pre><pre>ground_floor_type_RC          0.559758<br>roof_type_RCC/RB/RBC          0.606094<br>foundation_type_RC            0.622649<br>other_floor_type_RCC/RB/RBC   0.677787<br>caste_household_Magar         0.746214<br>dtype: float64<br></pre><p>Not surprisingly, foundation-type reinforced concrete seemingly has the lowest odds ratio, suggesting its importance in minimizing damage during an earthquake.</p><p>With this information in hand, it&#39;s time to plot the features associated with the most significant increase and decrease in severe damage.</p><p>We want to create a horizontal bar chart of the 10 biggest odds ratios. So, I can use the tail() method to get the 10 biggest ones, then plot the series with Pandas.</p><pre>feat_imp.tail(10).plot(kind=&quot;barh&quot;)<br>plt.xlabel(&quot;Odds Ratio&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65rhVxeYX1EaTyOqfHc3OQ.jpeg" /></figure><p>It’s not surprising that the characteristic most associated with an increase in the odds of severe building damage is if the superstructure is stone without any cement joining the stones together.</p><p>However, it’s interesting to see that a Gurung household is associated with a 50% increase in the odds of building damage. I’m not interpreting this yet, but let’s look at the smallest odds ratios as well. I find it notable that our model sees the ethnicity of a household as a predictor for building damage.</p><p>So, instead of using the tail() method, I’ll use the head() method to see the other end of the series.</p><pre>feat_imp.head(10).plot(kind=&quot;barh&quot;)<br>plt.xlabel(&quot;Odds Ratio&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GI53RLDabh4Pw1_CDLP0TA.jpeg" /></figure><p>We can see that reinforced concrete is often associated with a decrease in severe damage, which is not surprising. However, we find it puzzling that a Magar household seems to be associated with almost a 70% reduction in the odds of building damage. This is one of those moments where we need to do a reality check as a data scientist.</p><p>Looking at these odds ratios, the model is telling us that if two identical buildings in the same location had different households (one Gurung and the other Magar), the first would be much more likely to suffer severe damage in an earthquake, and the second would not. For me, the people who live inside the building would not affect the behavior of that building in an earthquake. This shows that something else is going on, so we need to explore this further.</p><p>So now, I’m beginning to work with the entire data frame, rather than just the feature matrix and target vector. This means that I have access to the municipality. Our first task is to identify which municipalities within the Gorka district had the highest proportion of severely damaged buildings.</p><p>To do this, I will start by using a groupby() function. I’ll group by ‘vdcmun_id’ (municipality) and then focus on the ‘severe_damage’ column. I will aggregate this column to get the mean, which will give me the percentage of severely damaged buildings in each municipality. Lastly, I will sort these values from largest to smallest.</p><pre>damage_by_vdcmun = (<br>df.groupby(&quot;vdcmun_id&quot;)[&quot;severe_damage&quot;].mean().sort_values(ascending=False)<br>).to_frame()<br>damage_by_vdcmun</pre><pre>           severe_damage<br>vdcmun_id<br>31           0.930199<br>32           0.851117<br>35           0.827145<br>30           0.824201<br>33           0.782464<br>34           0.666979<br>39           0.572344<br>40           0.512444<br>38           0.506425<br>36           0.503972<br>37           0.437789<br></pre><p>By looking at this table, we can identify the municipalities within the Gorka district that were most affected by the earthquake in terms of building damage. For instance, nearly 100% of the buildings in municipality 31 were severely damaged, while others had varying proportions of severe damage. So, there’s a significant difference in building damage across municipalities. This information will guide our future analysis.</p><p>Let’s create a dataframe based on this series and then visualize the data using a plot. But how we can visualize this data? One option is to plot a vertical bar chart displaying the severity of damage across different districts and municipalities. However, we want to further refine this visualization. Instead of the bar chart, we aim to create a line chart that reflects the descending levels of damage across municipalities.</p><pre># Plot line<br>plt.plot(damage_by_vdcmun.values, color=&quot;grey&quot;)<br>plt.xticks(range(len(damage_by_vdcmun)), labels= damage_by_vdcmun.index)<br>plt.yticks(np.arange(0.0, 1.1, 0.2))<br>plt.xlabel(&quot;Municipality ID&quot;)<br>plt.ylabel(&quot;% of Total Households&quot;)<br>plt.title(&quot;Severe Damage by Municipality&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1-I3EBtSG5AZGL0DwM4ig.jpeg" /></figure><p>Now, we need to determine the distribution of the Gurung and Magar households across these municipalities.</p><p>To start, we’ll filter the data frame to include only Gurung households. I’ll create a mask for the data frame to return only rural Gurung households. Then, we will use the groupby() function to group the data by ‘vdcmun_id’ and calculate the raw count of Gurung households in each municipality.</p><p>After that, we want to calculate the proportion of Gurung households in each municipality by dividing the number of Gurung households by the total number of households in each municipality.</p><pre>damage_by_vdcmun[&quot;Gurung&quot;] = (<br>df[df[&quot;caste_household&quot;]== &quot;Gurung&quot;].groupby(&quot;vdcmun_id&quot;)[&quot;severe_damage&quot;].count()<br>/ df.groupby(&quot;vdcmun_id&quot;)[&quot;severe_damage&quot;].count()<br>)</pre><p>Following this, I will repeat the same process for Magar households, replacing the filter for Gurung households with Magar households. In the case of missing values for Magar households in some municipalities, I’ll fill those with a value of zero.</p><pre>damage_by_vdcmun[&quot;Kumal&quot;] = (<br>df[df[&quot;caste_household&quot;]== &quot;Magar&quot;].groupby(&quot;vdcmun_id&quot;)[&quot;severe_damage&quot;].count()<br>/ df.groupby(&quot;vdcmun_id&quot;)[&quot;severe_damage&quot;].count()<br>).fillna(0)</pre><pre>            severe_damage Gurung    Magar<br>vdcmun_id<br>31           0.930199     0.326937  0.000000<br>32           0.851117     0.387849  0.000000<br>35           0.827145     0.826889  0.000000<br>30           0.824201     0.338152  0.000000<br>33           0.782464     0.011943  0.029478<br>34           0.666979     0.385084  0.000000<br>39           0.572344     0.097971  0.000267<br>40           0.512444     0.246727  0.036973<br>38           0.506425     0.049023  0.100686<br>36           0.503972     0.143178  0.003282<br>37           0.437789     0.050485  0.048842<br><br></pre><p>After completing these calculations, we can observe that in the most severely damaged municipalities, there is a higher proportion of Gurung households, while in the least severely damaged municipalities, there is a higher number of Magar households. This suggests that the type of household does not influence the damage received. Instead, areas with higher damage have more growing families, whereas areas with less damage have a higher concentration of Magar households.</p><p>To further visualize the proportions of Gurung and Magar populations in these municipalities, we’ll use a bar plot. We prefer to stack the bars for Gurung and Magar populations on top of each other instead of side by side. Setting the &quot;stacked&quot; argument to true produces the desired visualization.</p><pre>damage_by_vdcmun.drop(columns=&quot;severe_damage&quot;).plot(<br>kind=&quot;bar&quot;, stacked=True<br>)<br>plt.plot(damage_by_vdcmun[&quot;severe_damage&quot;].values, color=&quot;grey&quot;)<br>plt.xticks(range(len(damage_by_vdcmun)), labels= damage_by_vdcmun.index)<br>plt.yticks(np.arange(0.0, 1.1, 0.2))<br>plt.xlabel(&quot;Municipality ID&quot;)<br>plt.ylabel(&quot;% of Total Households&quot;)<br>plt.title(&quot;Household Caste by Municipality&quot;)<br>plt.legend();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*yAhLfXXmha1eb60W38n9RA.png" /></figure><p>This visualization reveals that the municipalities with the highest levels of damage have a concentration of Gurung households, while those with lesser damage are home to the Magar population. It becomes evident that the distribution of populations, rather than any inherent characteristic of the populations themselves, influenced the levels of building damage.</p><p>Considering the implications of this analysis, I draw a parallel to earthquake insurance in California, where discrimination based on demographic characteristics could occur if not careful. This leads to the concept of &quot;weapons of math destruction&quot; (WMDs), which are models trained on biased data and perpetuate social problems or systems of injustice. It&#39;s crucial to recognize that models are only as good as the data they&#39;re trained on, and biases within the data can manifest in the model&#39;s outputs.</p><p>What does this mean for us as a data scientist? It’s an important reminder that our model isn’t just about math, and our job isn’t just about coding. It involves thinking about many different things, such as how our model works in the real world. We’ve already discussed the environmental impact of our model, and now we see the importance of how our model could perpetuate social problems and discriminate against people. When building these models, it’s not just about looking at coefficients; we need to consider how the model will operate in the world and whether it will help or harm. I know this is ending on a somber note, but it’s a very important point.</p><h3>Conclusion</h3><p>So, what did we accomplish today? First, we examined the household_demographic table and successfully combined it with three other tables in the database to create a new data set. During the process of cleaning this data set, we also learned how to handle high-cardinality categorical variables by grouping them into categories, thus reducing the number of categories by selecting the top 10 most represented ones and creating an &quot;Other&quot; category for the rest.</p><p>After that, we built a logistic regression model to forecast severe damage to buildings where these households were located. We were able to interpret the model&#39;s predictions using odds ratios. Interestingly, we discovered that caste was not an important feature in the model&#39;s predictions. Rather, it was the distribution of the population in municipalities that made the difference in the severity of damage caused by the earthquake.</p><p>We covered a lot of ground today, and I look forward to seeing you in the next project. Bye for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cc7c94dcc43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Earthquake Damage in Nepal (3): Predicting Damage with Decision Trees]]></title>
            <link>https://medium.com/@sawsanyusuf/earthquake-damage-in-nepal-3-predicting-damage-with-decision-trees-a7d5c17534d2?source=rss-694a29ec1850------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d5c17534d2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Sawsan Yusuf]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 21:10:51 GMT</pubDate>
            <atom:updated>2024-09-22T20:40:28.586Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using a Decision Tree Model for Predicting Building Damage in Earthquakes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Q6G-hTPpuOPlH7j" /><figcaption>Photo by Sergey Pesterev on Unsplash</figcaption></figure><p>Hello and welcome to part three of Project Three. In this project, we are focusing on classification. The goal is to create a model that can predict whether a building is severely damaged or not severely damaged in an earthquake. In the previous part, we learned about logistic regression. Today, we will be learning about another type of model: <strong>the decision tree.</strong></p><p>Our three goals for today are: <br>1. Create a decision tree model to predict severe damage.<br>2. Tune the hyperparameters for that model, focusing on one particular hyperparameter.<br>3. Explain our model predictions using something called Gini importance.</p><p>Following the ML workflow, for importing, we will keep everything the same and use the same wrangle function. We won&#39;t conduct additional EDA. Instead, we will perform a three-way split of our data into train, validation, and test sets under splitting.</p><p>We will continue to work on the accuracy score as our baseline for building the model. In the iteration phase, we will cover three main topics: decision trees, ordinal encoding for categorical variables, and plotting a validation curve to help tune the hyperparameters for our decision tree model.</p><p>For evaluation, in the last part of the ML workflow, we will focus on understanding Gini&#39;s importance.</p><p>We will also discuss a key term to remember when working with decision trees – nodes, parent nodes, child nodes, and terminal nodes.</p><p>Lastly, we will go over the new imports for this session, including the ordinal encoder from category encoders and the decision tree classifier from the tree module in scikit-learn. We will also use the helper function plot_tree to visualize the tree.</p><pre>import sqlite3<br>import warnings<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>from category_encoders import OrdinalEncoder<br>from sklearn.metrics import accuracy_score<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import Pipeline, make_pipeline<br>from sklearn.tree import DecisionTreeClassifier, plot_tree<br><br>warnings.simplefilter(action=&quot;ignore&quot;, category=FutureWarning)</pre><p>Let&#39;s proceed with the wrangle step.</p><h3>1. Prepare Data</h3><h4>1.1. Import</h4><p>We’ll use our wrangle function to import your data set into the DataFrame df.</p><pre>def wrangle(db_path):<br>     # Connect to database<br>     conn = sqlite3.connect(db_path)<br>     # Construct query<br>      query = &quot;&quot;&quot;<br>        SELECT distinct(i.building_id) AS b_id,<br>        s.*,<br>        d.damage_grade<br>        FROM id_map AS i<br>        JOIN building_structure AS s ON i.building_id = s.building_id<br>        JOIN building_damage AS d ON i.building_id = d.building_id<br>        WHERE district_id = 4<br>     &quot;&quot;&quot;<br>     # Read query results into DataFrame<br>     df = pd.read_sql(query, conn, index_col=&quot;b_id&quot;)<br>     # Identify leaky columns<br>     drop_cols = [col for col in df.columns if &quot;post_eq&quot; in col]<br>     # Add high-cardinality / redundant column<br>     drop_cols.append(&quot;building_id&quot;)<br>     # Create binary target column<br>     df[&quot;damage_grade&quot;] = df[&quot;damage_grade&quot;].str[-1].astype(int)<br>     df[&quot;severe_damage&quot;] = (df[&quot;damage_grade&quot;] &gt; 3).astype(int)<br>     # Drop old target<br>     drop_cols.append(&quot;damage_grade&quot;)<br>     # Drop multicollinearity column<br>     drop_cols.append(&quot;count_floors_pre_eq&quot;)<br>     # Drop columns<br>     df.drop(columns=drop_cols, inplace=True)<br><br>   return df</pre><pre>df = wrangle(&quot;nepal.sqlite&quot;)</pre><h4>1.2. Split</h4><p>We’ll start our splitting processes by creating our feature matrix X and target vector y. Our target is &quot;severe_damage&quot;.</p><pre>target = &quot;severe_damage&quot;<br>X = df.drop(columns = target)<br>y = df[target]</pre><p>Once we did our vertical split dividing it into feature matrix X and target vector y. Now, we’re going to do a horizontal split differently by creating a train-validation-test split. This split will be done in two steps.</p><p>Before getting into the code, let&#39;s talk about the validation set and its purpose. After splitting the data into X and y, we usually set aside around 20% of the data for the test set. This set is kept separate from the training data.</p><p>The validation set is used to fine-tune the model. After the initial training with the training data, we might adjust the model&#39;s hyperparameters and then check its performance using the validation set. This process allows us to iterate and make improvements until we are satisfied with the model&#39;s performance before finally testing it using the test set, which marks the end of the model-building process.</p><p>I’m going to start by performing our first train-test split. We have X_train, X_test, y_train, and y_test, and I will use these to split the data. We’ll be using four arguments in this split: x, y, test size (set to 0.2 for 20%), and a random state of 42.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=42)</pre><p>After that, we’ll further divide our training data into a training set and a validation set. The process will be similar to the first split, using the same train_test_split function, but this time with X_train and y_train. Here, we’ll again specify the test size as 0.2 (representing the validation set) and a random state of 42.</p><pre>X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)</pre><p>So, now we have three sets: the training set, the validation set, and the test set. It’s important to note that we allocated 20% of the data to both the validation and test sets, leaving 60% for training. This distribution follows a common rule of thumb, as some may allocate 10% for validation and 10% for testing. However, for now, we’ll stick with the 20-20-60 split.</p><h3>2. Build Model</h3><h4>2.1. Baseline</h4><pre>acc_baseline = y_train.value_counts(normalize=True).max()<br>print(&quot;Baseline Accuracy:&quot;, round(acc_baseline, 2))<br><br><br>&gt;&gt;&gt; Baseline Accuracy: 0.64</pre><h4>2.2. Iterate</h4><p>After we have established a baseline that we aim to surpass. It’s time to construct our model. In this session, we will be working with a new type of model: a decision tree, and we will be using it alongside an ordinal encoder. Before we delve into the coding, I’ll provide an overview of these two components and how they interact.</p><p>Let&#39;s start with decision trees. How do they function? The process begins with grouping all training observations into a single node, which we&#39;ll refer to as a &quot;node.&quot; In our dataset, the training data falls into two classes: severely damaged buildings, making up about two-thirds of the data, and non-severely damaged buildings, accounting for about one-third.</p><p>Firstly, let’s discuss what the decision tree aims to accomplish before delving into the process. The goal is to take the data within the single node and divide it into two child nodes in a way that ensures complete purity in both child nodes. By &quot;purity,&quot; we mean that one node will exclusively contain severely damaged houses, while the other will solely contain non-severely affected houses. However, achieving 100% purity in the initial split is not always possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*yNh2IgX1NlBT36lm_XIxVA.png" /></figure><p>In such cases, the impure nodes are further split into additional child nodes, to reach complete purity or minimal impurity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*otKU_C6dEGpE4QNWLgI8eA.png" /></figure><p>Although it might resemble a pyramid, envision the decision tree inverted, resembling more of a structure like a bush. Nevertheless, the term &quot;decision tree&quot; remains standard. The initial node is referred to as the &quot;root&quot; or the &quot;root node,&quot; while the final set of nodes is known as the &quot;terminal nodes&quot; or &quot;leaves.&quot; The number of divisions, or splits, required to progress from the impure root node to the pure terminal nodes is known as the &quot;depth.&quot; For example, a tree with one split and subsequent splits has a depth of two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*q7MiZn7yO2Qby1CQfbkqVQ.png" /></figure><p>Now, let&#39;s explore how the decision tree achieves these divisions. It begins by examining all features in the training data to identify a feature and an associated cut-off point that optimally facilitates the division. For instance, with a continuous variable such as building height, it may experiment with different cut-off points to achieve the desired purity in the resulting child nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*eUF8RcQzEho45qTrZEbXCw.png" /></figure><p>This process is repeated for each subsequent node until purity is achieved or impurity is minimized.</p><p>We will briefly discuss how this procedure works with categorical variables when we cover ordinal encoding. For now, keep this image in mind about continuous variables.</p><p>Now that we understand the decision tree and how it works, let’s compare it with the linear models we’ve been using in previous projects — specifically, linear regression.</p><p>First, let&#39;s compare the cost function. In the case of linear models, we aim to minimize the distance between data points by fitting a line through them. This requires minimizing a cost function determined by an equation. On the other hand, decision tree models are concerned with reducing impurity by subdividing data into pure nodes and do not focus on minimizing distance.</p><p>Moving on to relationships, linear models excel at describing linear connections or relationships between variables. They are restricted to linear relationships and are less flexible in this regard. On the other hand, decision tree models are capable of handling both linear and non-linear relationships, making them more versatile.</p><p>Lastly, let&#39;s consider the model type. Linear models are parametric, meaning their shape is predefined before training. In contrast, decision tree models are non-parametric and their structure depends on the nature of the data, allowing for greater flexibility.</p><p>In summary, decision tree models aim to reduce impurity by subdividing data, are more flexible than linear models, and can handle both linear and non-linear relationships.</p><p>Now let’s discuss ordinal encoding and its compatibility with decision tree models.</p><p>But, before that, let’s review OneHotEncoder. In a dataset, if we have a categorical feature like &quot;foundation&quot; with three observations (wood, reinforced concrete, and brick), OneHotEncoding would create new columns for each unique category. For example, the wood column, reinforced concrete column and brick column would be added, and binary encoding would represent the different foundation types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*5q371MXrfunVVRX7b9qKXg.png" /></figure><p>Now, let&#39;s talk about ordinal encoding. This method assigns a unique integer to each category in the column of interest. For instance, wood might be assigned 1, reinforced concrete as 2, and brick as 3. This is known as ordinal encoding because there&#39;s an order in these numbers, reflecting the order of the categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*cfZ58cqOjSHoqNHwoblWXQ.png" /></figure><p>The reason why we can&#39;t use ordinal encoding with linear models is that linear models rely on distance, and they evaluate distance by adding numbers together. This doesn&#39;t work well with categorical variables. On the other hand, decision tree models are not concerned with mathematical operations on categories. They divide nodes based on purity and don&#39;t need to perform mathematical operations on categories.</p><p>Ordinal encoding works well with decision trees because the decision tree algorithm aims to divide nodes into subgroups to achieve maximum purity, and it doesn&#39;t rely on mathematical operations with categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*vWBbsUsYpB7z_r1CSBYtXQ.png" /></figure><p>Using ordinal encoding reduces the high dimensionality problem and computation issues that we sometimes encounter in linear models. Additionally, one-hot encoding doesn&#39;t work effectively with decision tree models as it may lead to imbalanced trees.</p><p>In summary, use one-hot encoding with linear models and ordinal encoding with decision trees.</p><p>I believe we now have all the intellectual firepower we need to code this up in scikit-learn. So, let’s dive in. The first thing we need to do is build our model. We’ll start by creating our pipeline. I’ll start with the ordinal encoder, using the default arguments. Then I’ll add the decision tree classifier, which we imported earlier.</p><p>Please note that we’re using a decision tree classifier. There are also decision trees for regression, known as decision tree regressors, but in our case, we’re using the classifier. I’ll include one argument for our decision tree - the random state, which I’ll set equal to 42. The reason for including a random process in this decision tree is to ensure that it looks through the different features in a random order, making the process more reproducible.</p><p>Finally, I’ll call model.fit() to fit it into the training data, X_train, and y_train.</p><pre># Build Model<br>model = make_pipeline(<br>OrdinalEncoder(), DecisionTreeClassifier(random_state=42))<br># Fit model to training data<br>model.fit(X_train, y_train)</pre><p>One great thing about these decision tree models is that they train very quickly. We can see the first step - the ordinal encoder is taking up a lot of space here, and then here’s the second part, the decision tree classifier.</p><pre><br><br>Pipeline<br>Pipeline(steps=[(&#39;ordinalencoder&#39;,<br>                 OrdinalEncoder(cols=[&#39;land_surface_condition&#39;,<br>                                      &#39;foundation_type&#39;, &#39;roof_type&#39;,<br>                                      &#39;ground_floor_type&#39;, &#39;other_floor_type&#39;,<br>                                      &#39;position&#39;, &#39;plan_configuration&#39;,<br>                                      &#39;superstructure&#39;],<br>                                mapping=[{&#39;col&#39;: &#39;land_surface_condition&#39;,<br>                                          &#39;data_type&#39;: dtype(&#39;O&#39;),<br>                                          &#39;mapping&#39;: Flat              1<br>Moderate slope    2<br>Steep slope       3<br>NaN              -2<br>dtype: int64},<br>                                         {&#39;col&#39;: &#39;foundation_type&#39;,<br>                                          &#39;dat...<br>T-shape                             7<br>Building with Central Courtyard     8<br>Others                              9<br>H-shape                            10<br>NaN                                -2<br>dtype: int64},<br>                                         {&#39;col&#39;: &#39;superstructure&#39;,<br>                                          &#39;data_type&#39;: dtype(&#39;O&#39;),<br>                                          &#39;mapping&#39;: adobe mud               1<br>mud mortar ,stone       2<br>rc non engineered       3<br>mud mortar brick        4<br>bamboo                  5<br>timber                  6<br>rc engineered           7<br>cement mortar brick     8<br>other                   9<br>stone flag             10<br>cement mortar stone    11<br>NaN                    -2<br>dtype: int64}])),<br>                (&#39;decisiontreeclassifier&#39;,<br>                 DecisionTreeClassifier(random_state=42))])<br>OrdinalEncoder<br>OrdinalEncoder(cols=[&#39;land_surface_condition&#39;, &#39;foundation_type&#39;, &#39;roof_type&#39;,<br>                     &#39;ground_floor_type&#39;, &#39;other_floor_type&#39;, &#39;position&#39;,<br>                     &#39;plan_configuration&#39;, &#39;superstructure&#39;],<br>               mapping=[{&#39;col&#39;: &#39;land_surface_condition&#39;,<br>                         &#39;data_type&#39;: dtype(&#39;O&#39;),<br>                         &#39;mapping&#39;: Flat              1<br>Moderate slope    2<br>Steep slope       3<br>NaN              -2<br>dtype: int64},<br>                        {&#39;col&#39;: &#39;foundation_type&#39;, &#39;data_type&#39;: dtype(&#39;O&#39;),<br>                         &#39;mapping&#39;: Mud mo...<br>                         &#39;mapping&#39;: Rectangular                         1<br>Square                              2<br>Multi-projected                     3<br>L-shape                             4<br>E-shape                             5<br>U-shape                             6<br>T-shape                             7<br>Building with Central Courtyard     8<br>Others                              9<br>H-shape                            10<br>NaN                                -2<br>dtype: int64},<br>                        {&#39;col&#39;: &#39;superstructure&#39;, &#39;data_type&#39;: dtype(&#39;O&#39;),<br>                         &#39;mapping&#39;: adobe mud               1<br>mud mortar ,stone       2<br>rc non engineered       3<br>mud mortar brick        4<br>bamboo                  5<br>timber                  6<br>rc engineered           7<br>cement mortar brick     8<br>other                   9<br>stone flag             10<br>cement mortar stone    11<br>NaN                    -2<br>dtype: int64}])<br>DecisionTreeClassifier<br>DecisionTreeClassifier(random_state=42)</pre><p>With our model ready, it’s time to see how it’s performing. Normally, we would jump right to evaluation, but this time I’m interested in doing some hyperparameter tuning. Before we do any of that, I want to assess how this model performs, not with our test data, but with our validation data. We’ll start by calculating accuracy scores in two different ways. First, we’ll use the verbose method by comparing the accuracy_score of y_train and model.predict(X_train). Then, we’ll use the more compact approach by using the model.score(X_val, y_val). Both methods lead to the same destination.</p><pre>acc_train = accuracy_score(y_train, model.predict(X_train))<br>acc_val = model.score(X_val, y_val)<br>print(&quot;Training Accuracy:&quot;, round(acc_train, 2))<br>print(&quot;Validation Accuracy:&quot;, round(acc_val, 2))<br><br><br><br>&gt;&gt;&gt; Training Accuracy: 0.98<br>&gt;&gt;&gt; Validation Accuracy: 0.65</pre><p>When we look at the results, we notice that our training accuracy is almost perfect, reaching close to a hundred percent. However, our test accuracy is quite poor and doesn&#39;t even beat the baseline by much. It&#39;s clear that our model isn&#39;t generalizing well. We&#39;ll need to discuss why and look into some hyperparameter tuning to address this issue.</p><p>The problem lies in our model&#39;s near-perfect performance with the training data but its poor performance with the validation data. We need to figure out what&#39;s causing this and find a solution quickly.</p><p>When comparing linear models and decision tree models, we mentioned that decision tree models are very flexible. This flexibility comes from the fact that the model can make as many splits as it wants until it achieves absolute purity.</p><p>However, this flexibility leads to overfitting. Just like an untrimmed vine in a garden will spread to occupy every available space, the decision tree will begin to fit the data so precisely that it loses the ability to generalize to other datasets. The more depth the tree has, the more flexibility and overfitting it introduces.</p><p>The good news is that we can control the depth, which is a hyperparameter we can tune to make our model more or less flexible.</p><p>First, let’s see what the depth of our current tree is. The decision tree classifier is inside our model pipeline, so we’ll use named_steps() and then call the get_depth method.</p><pre>tree_depth = model.named_steps[&quot;decisiontreeclassifier&quot;].get_depth()<br>print(&quot;Tree Depth:&quot;, tree_depth)<br><br>&gt;&gt;&gt; 49</pre><p>The depth of our tree is 49, which is quite excessive. So, the next step is to determine the best depth for our model.</p><p>We will create a range of values from 1 to 50 with steps of 2 for the max depth.</p><pre>depth_hyperparams = range(1, 50, 2)</pre><p>Next, we will test these different max depth values to identify the one that provides the best result. We’ll establish the best way to build and evaluate our model using the training and validation data.</p><p>To start, we initialize two empty lists to store the training and validation accuracy scores for each max depth value. Then, we create a loop to iterate through the possible max depth values. For each value, we build a model, fit it to the training data, calculate the training accuracy, and append it to the training accuracy list. The same process is repeated for the validation accuracy, with the scores being appended to the validation accuracy list. We also check the first few values of both lists.</p><pre># Create empty lists for training and validation accuracy scores<br>training_acc = []<br>validation_acc = []<br>for d in depth_hyperparams:<br>       # Create model with `max_depth` of `d`<br>       test_model = make_pipeline(<br>            OrdinalEncoder(), DecisionTreeClassifier(max_depth=d, random_state=42)<br>       )<br>       # Fit model to training data<br>       test_model.fit(X_train, y_train)<br>       # Calculate training accuracy score and append to `training_acc`<br>       training_acc.append(test_model.score(X_train, y_train))<br>       # Calculate validation accuracy score and append to `training_acc`<br>       validation_acc.append(test_model.score(X_val, y_val))<br>print(&quot;Training Accuracy Scores:&quot;, training_acc[:3])<br>print(&quot;Validation Accuracy Scores:&quot;, validation_acc[:3])</pre><pre>Training Accuracy Scores: [0.7071072484228174, 0.7117395332421582,<br>0.7162394670666608]<br>Validation Accuracy Scores: [0.7088406564319746, 0.7132521616375508,<br>0.7166049055937886]</pre><p>After collecting the accuracy scores, we need to visualize the differences in accuracies for different max depths. We will create a plot with two lines representing the training and validation accuracies for each max depth value using Matplotlib.</p><pre># Plot `depth_hyperparams`, `training_acc`<br>plt.plot(depth_hyperparams, training_acc, label=&quot;training&quot;)<br>plt.plot(depth_hyperparams, validation_acc, label=&quot;validation&quot;)<br>plt.xlabel(&quot;Max Depth&quot;)<br>plt.ylabel(&quot;Accuracy Score&quot;)<br>plt.legend();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*-hxvfRcJn4Gqh0zVwNqfMQ.png" /></figure><p>Upon analyzing the plotted data, we can observe that as the max depth increases, the model’s ability to accurately predict the training data improves. However, the validation accuracy initially increases but then starts to decline, indicating that the model is overfitting. We need to find the max depth value before this divergence occurs, which will be the best hyperparameter setting for our model - in this case, a max depth of 6. Therefore, we will redo the model with the max depth set to 6.</p><pre># Build Model<br>model = make_pipeline(<br>   OrdinalEncoder(),<br>   DecisionTreeClassifier(max_depth=6, random_state=42))<br><br># Fit model to training data<br>model.fit(X_train, y_train)</pre><pre>acc_train = accuracy_score(y_train, model.predict(X_train))<br>acc_val = model.score(X_val, y_val)<br>print(&quot;Training Accuracy:&quot;, round(acc_train, 2))<br>print(&quot;Validation Accuracy:&quot;, round(acc_val, 2))<br><br><br><br>&gt;&gt;&gt; Training Accuracy: 0.72<br>&gt;&gt;&gt; Validation Accuracy: 0.72</pre><p>After we retrained the model to address the previous issue where one value was almost 100% and the other was close to the baseline. We achieved a 72% accuracy for both, resolving the overfitting issue and surpassing the baseline.</p><h4>2.3. Evaluate</h4><p>With the model fine-tuned and validated, it’s time to test it with the testing data to calculate the accuracy score. Hopefully, it will be around 72%.</p><pre>test_acc = model.score(X_test, y_test)<br>print(&quot;Test Accuracy:&quot;, round(test_acc, 2))<br><br>&gt;&gt;&gt; Test Accuracy: 0.72</pre><p>By tuning the model, we addressed the overfitting problem. Now, it’s time to move on to discussing how the model makes predictions.</p><h3>3. Communicate Results</h3><p>First, we’d like to visualize the decision tree we just created. I used the plot_tree() function to create a clear visualization. We need to pass in the decision tree and the feature names in our dataset. Then, we can interpret the visualization together as a group, as it provides insight into the splits, impurity, total samples, and sample proportions at each node in the decision tree.</p><pre> # Create larger figure<br>fig, ax = plt.subplots(figsize=(25, 12))<br># Plot tree<br>plot_tree(<br>        decision_tree= model.named_steps[&quot;decisiontreeclassifier&quot;],<br>        feature_names= X_train.columns,<br>        filled=True,     # Color leaf with class<br>        rounded=True,    # Round leaf edges<br>        proportion=True, # Display proportion of classes in leaf<br>        max_depth=3,     # Only display first 3 levels<br>        fontsize=12,     # Enlarge font<br>        ax=ax,           # Place in figure axis<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FT-byXJheBYV1HJe-B5E0Q.png" /></figure><p>This type of visualization can be especially valuable when communicating with non-technical audiences, as it presents the decision-making process in an easily understandable format. Finally, we want to discuss feature importance and how to interpret them within the context of a decision tree.</p><p>First, let’s grab the feature names. Since we used ordinal encoding, we didn’t create any new columns like we would with OneHotEncoding. So, to get the feature names, we can just use &#39;X_train.columns’.</p><p>Next, let’s talk about getting the feature importances. I found an attribute called feature importances in the documentation of the decision tree. So, I’ll access it using &#39;model.named_steps[’decision_tree_classifier’].feature_importances’.</p><p>Next, I&#39;ll create a dataframe and then we can visualize and discuss how to interpret the feature importance when dealing with decision trees.</p><pre>features = X_train.columns<br>importances = model.named_steps[&quot;decisiontreeclassifier&quot;].feature_importances_<br>feat_imp = pd.Series(importances, index=features).sort_values()<br>feat_imp.head()<br><br><br>position               0.000644<br>plan_configuration     0.004847<br>foundation_type        0.005206<br>roof_type              0.007620<br>land_surface_condition 0.020759<br>dtype: float64</pre><p>Now, let’s create that final visualization and go over how to interpret feature importance when working with decision trees.</p><p>But before we start, let’s review some key points. In the decision tree visualization, we notice that certain features are used multiple times for splitting and that the sum of the feature importance values equals one. This indicates that some features are reused throughout the tree and that their collective importance is fully accounted for.</p><pre># Create horizontal bar chart<br>feat_imp.plot(kind= &quot;barh&quot;)<br>plt.xlabel(&quot;Gini Importance&quot;)<br>plt.ylabel(&quot;Features&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*AX6QR-qlKabvP1Zq8jHvfA.jpeg" /></figure><p>Let’s start interpreting the plot. For example, let’s consider the feature &quot;superstructure.&quot; The Gini importance value for superstructure is around 0.6. It’s important to note that none of these values go over one; they’re all between zero and one, and they all sum to one. This means that the superstructure feature is responsible for about 60% of the increase in purity as the tree splits from the root to the leaves.</p><p>Similarly, the feature &quot;height of a building pre-earthquake&quot; seems to be responsible for around 8-9% of the reduction in impurity throughout the tree.</p><p>In essence, these values indicate the importance of a feature in the process of dividing the data from an impure node to pure leaf nodes.</p><p>There are two key points to consider here. Firstly, when we calculate feature importance for a linear model, we are essentially looking at the equation the model uses to make predictions. This allows a direct connection between a feature and the prediction. For instance, in a linear model, we can easily understand how changing the area of an apartment affects the predicted price.</p><p>However, in the current context, we don&#39;t have this direct connection. We can&#39;t determine the proportional effect of changing a feature on the prediction, such as increasing the area of a property by a certain amount.</p><p>Secondly, unlike linear models where we have positive and negative coefficients indicating the relationship between features and predictions, all the feature importance values for decision trees are positive. This means we can&#39;t discern whether a feature exerts upward or downward pressure on the model&#39;s prediction.</p><p>While decision trees are flexible, easy to visualize, and intuitive to understand, their explainability is not as straightforward as linear models. Choosing between these models involves considering factors such as explainability, accuracy, and computational requirements.</p><p>In summary, when building models as a data scientist, it’s crucial to balance the importance of explainability, accuracy, and computational resources to building effective models.</p><h3>Conclusion</h3><p>Part three is complete. Here’s a brief overview of what we covered. First, we built a decision tree model and tuned the hyperparameters, focusing on max depth. We also learned how to explain the predictions made by the model using Gini importance.</p><p>During data preparation, we emphasized the importance of creating separate training, validation, and test sets. The training set is used to train the model, the validation set is for hyperparameter tuning, and the test set is for final model evaluation before deployment.</p><p>In terms of model building, we started with a baseline accuracy and then delved into decision trees, their workings, and the concept of purity in reducing impurity. We also discussed ordinal encoding and its compatibility with decision trees but not with linear models.</p><p>Finally, we explored the validation curve and its impact on model flexibility and generalization. Additionally, we distinguished Gini importance from feature importance in linear models.</p><p>I’m excited to continue the discussion in part four as we delve into demographic data analysis. We’ll explore intriguing insights from the data and also address the potential traps in data science when critical thinking is overlooked. It promises to be an interesting conversation about ethics in data science, and I look forward to seeing you all. Bay for now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d5c17534d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>