<?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 Priyanshu Chaudhary on Medium]]></title>
        <description><![CDATA[Stories by Priyanshu Chaudhary on Medium]]></description>
        <link>https://medium.com/@chaudharypriyanshu7401?source=rss-42fcadbfb718------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rQrTEEF-xV17hsd9vfARIA.jpeg</url>
            <title>Stories by Priyanshu Chaudhary on Medium</title>
            <link>https://medium.com/@chaudharypriyanshu7401?source=rss-42fcadbfb718------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:30:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chaudharypriyanshu7401/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[Neural Networks Mathematics: From Beginner to Pro]]></title>
            <link>https://medium.com/@chaudharypriyanshu7401/neural-networks-mathematics-from-beginner-to-pro-8a5c084105c3?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a5c084105c3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Wed, 03 May 2023 11:28:56 GMT</pubDate>
            <atom:updated>2023-05-04T09:41:39.849Z</atom:updated>
            <content:encoded><![CDATA[<h4>MACHINE LEARNING</h4><h4>A Visual Guide to Learning Backpropagation and Stochastic Gradient Descent</h4><figure><img alt="Thinking about Neural Network mathematics. Image by Freepik and author" src="https://cdn-images-1.medium.com/max/697/1*rJnnI3n4nWDo2fu51yPckw.png" /><figcaption>Thinking about Neural Network mathematics. Image by <a href="https://www.freepik.com/free-vector/young-girl-with-empty-thoughts_23715518.htm#query=anime%20character%20thinking&amp;position=3&amp;from_view=search&amp;track=ais">Freepik</a> and <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><h4>Introduction</h4><p>Are you fascinated by deep learning neural networks’ brilliance but intimidated by the complex mathematics that lies beneath the surface? You’re not by yourself! The world of neural networks can appear to be a confusing maze of mathematics, linear algebra, and optimization techniques. But don’t worry: in this blog, I’ll simplify artificial neural network math and make it understandable to everyone, regardless of mathematical background.</p><p>This blog is for you if you are a beginner hoping to get started with neural networks or an experienced practitioner wishing to enhance your expertise. So sit back, relax, and prepare to embark on an adventure into the fascinating world of neural network math!</p><p>However, before I get into the details of backpropagation in neural networks, we should first understand some mathematical prerequisites.</p><h4><strong>Partial Differentiation—Chain Rule</strong></h4><p>Consider f(x,y) that depends on the variables x,y, in turn, depend on the independent variable t (independent variable stands for a variable that does not depend on any other variable). Then, if I want to calculate the partial derivative of f(x,y) with respect to t, I can use the chain rule.</p><figure><img alt="Illustration for calculating partial derivative of f wrt t. Image by author" src="https://cdn-images-1.medium.com/max/1024/1*ZcGIZ_zNv_6Wi4Eo-m_gOQ.png" /><figcaption>Illustration for calculating partial derivative of f wrt t. Image by <a href="https://medium.com/@chaudharypriyanshu7401">a</a>uthor</figcaption></figure><p>The tree chart in the above figure shows that f depends on x and y while x and y depend on t. Hence, the equation on the left can be calculated by using this figure. Considering the following rules</p><ol><li><em>The top node of the tree is the function we want to partially differentiate </em><em>f(x,y), and the bottom nodes of the tree represent the independent variable (</em><em>t).</em></li><li><em>To take the derivative of f(x, y) with respect to a specific independent variable (let’s say t), start at the top and follow the path that leads to that variable. Along the way, multiply all the derivatives that you encounter.</em></li><li><em>Add all the possible path products encountered (two in this case, as shown in the figure).</em></li></ol><p>Consider another example, as shown in the figure below. f is a function of x,y,z and x,y and z depends on independent variables s and t.</p><figure><img alt="Partial differentiation tree" src="https://cdn-images-1.medium.com/max/814/1*p4Xyh0ooX5r9YeaeI34rSA.png" /><figcaption>Partial differentiation tree. Image by author</figcaption></figure><p>In order to find the derivative of <em>f(x,y,z)</em> w.r.t s and t we break the given tree into two parts and apply the above rules defined above.</p><figure><img alt="Partial differentiation chain rule" src="https://cdn-images-1.medium.com/max/1024/1*6hExU0SVV87iL_W-wP8giA.png" /><figcaption>Partial differentiation chain rule. Image by author</figcaption></figure><h4><strong>Stochastic Gradient Descent</strong></h4><p>Stochastic gradient descent is an optimization algorithm. We use it to find the most optimal parameters (ϴ), such that the loss function can be minimized and we can get better prediction results. This statement can be written in mathematical terms as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*_zScwL6G2l7sqs7ipTwdkg.png" /><figcaption>The objective of stochastic gradient descent. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><blockquote>How can we now find the optimal parameters?</blockquote><p>The most famous equation is formulated as</p><figure><img alt="Stochastic gradient Descent" src="https://cdn-images-1.medium.com/max/857/1*C4BxJwub50lew1koDSv8Iw.png" /><figcaption>Stochastic gradient descent. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>Note: ∇ represents the gradient of the loss function.</p><blockquote><strong>Why are we calculating gradient instead of simple differentiation?</strong></blockquote><ol><li><em>In all cases of machine learning, we have a loss function that depends on multiple variables, i.e., a multivariate loss function f(ϴ).</em></li><li><em>Differentiation is used when dealing with a function that depends on a single variable. However, we must optimize all variables simultaneously when dealing with multivariate functions. This is where the gradient comes into play to minimize the multivariate loss function f(ϴ), also known as the objective function.</em></li></ol><blockquote><strong>But what is the objective of calculating the gradient?</strong></blockquote><p>We assume that our loss function is a convex function; hence, the loss function will be minimal when the slope of the loss function (gradient) is zero. (a rule of differential calculus)</p><p><em>Therefore, the negative sign in the equation makes sure that we optimize the parameter in the direction that leads to a reduction of the loss function toward its minimal value, as shown on the left side of the above figure.</em></p><h4>Backpropagation</h4><p>Now, let’s take a neural network. That has four layers; each layer has one neuron, and we are not taking any bias terms just for the sake of simplicity. The neural network is shown below.</p><figure><img alt="Forward propagation" src="https://cdn-images-1.medium.com/max/1024/1*24YHsunvt7VCWoHYDhMEiQ.png" /><figcaption>Forward propagation. Image by author</figcaption></figure><p><em>f </em>represents the neuron&#39;s output after passing through the activation function (<em>tanh()</em> here). We minimize the mean squared error loss function, which is formulated as</p><figure><img alt="Mean squared error" src="https://cdn-images-1.medium.com/max/541/1*xKFaSdpxro79ynon_YuDQw.png" /><figcaption>Mean squared error. Image by author</figcaption></figure><p>Now, SGD has the objective of minimizing the above loss. Therefore, in order to minimize it, we select a random point j from 1, 2, 3,..., n data points and use the famous SGD equation to change our neural network parameters. i.e.,</p><figure><img alt="Stochastic gradient descent for neural network" src="https://cdn-images-1.medium.com/max/493/1*eUU7F92FMeKTaf2gWRyYVQ.png" /><figcaption>Stochastic gradient descent. Image by author</figcaption></figure><p>Let’s evaluate the gradient in the above equation, I can find the solution as shown below.</p><figure><img alt="gradient calculation" src="https://cdn-images-1.medium.com/max/677/1*_28vuVmcXqnhVLC9YjWVaw.png" /><figcaption>gradient calculation. Image by author</figcaption></figure><p>So, everything boils down to the evaluation of the partial derivates of f4 wrt w1,w2,w3,w4 (independent variables) which I can evaluate using the chain rule method as described above. The tree structure for this case will be</p><figure><img alt="The partial differentiation tree structure" src="https://cdn-images-1.medium.com/max/533/1*UbiiWY2TPmHYsqoqOq0mdw.png" /><figcaption>The partial differentiation tree structure. Image by author</figcaption></figure><p>I will be using the forward propagation equations that I derived earlier.</p><figure><img alt="Neural Network forward Propagation equations" src="https://cdn-images-1.medium.com/max/401/1*SIuvDU0niZ5iSlVfpgCorw.png" /><figcaption>Forward Propagation equations</figcaption></figure><p>The process of calculating partial derivates is shown below.</p><figure><img alt="ackpropagation or Backward Propagation" src="https://cdn-images-1.medium.com/max/752/1*xjDEXMB20amJ4OQ1KVgsYw.png" /><figcaption>backpropagation.Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>In the three examples mentioned above, we can see that in order to calculate the partial derivatives of f4, we need to go back to the previous layers. This process is known as &quot;backpropagation.&quot; To illustrate this concept further, let’s consider the last example where we need to calculate the partial derivative of f4 with respect to w1.</p><figure><img alt="Illustration of backpropagation" src="https://cdn-images-1.medium.com/max/1024/1*g3UQK0dFryILHchJYQ9Bew.png" /><figcaption>Illustration of backpropagation. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>Notice how we are moving back to the layers to calculate the partial derivates. From the above figures, it is clear how backpropagation works.</p><h4>Conclusion</h4><p>To sum up, this blog has explained how backpropagation and stochastic gradient descent help improve neural networks. I&#39;ve included more pictures to make it easier to understand since people tend to remember visuals better. By grasping these ideas, you can gain a better understanding of how neural networks function and how to train them efficiently.</p><p>If you find this blog informative, don’t forget to like it, as it keeps me motivated. Also, follow me on <a href="https://medium.com/@chaudharypriyanshu7401"><em>Medium</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a5c084105c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas 2.0 vs Polars: The Ultimate Battle]]></title>
            <link>https://medium.com/cuenex/pandas-2-0-vs-polars-the-ultimate-battle-a378eb75d6d1?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/a378eb75d6d1</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 16:03:09 GMT</pubDate>
            <atom:updated>2023-04-10T14:41:20.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>PYTHON PROGRAMMING TIPS</h4><h4>In-Depth analysis in terms of Syntax, Speed, and Usability between Pandas 2.0 and Polars 0.17.0</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EHqvZVV4qNjRqrHiBK9-A.png" /><figcaption>Polars vs Pandas 2.0. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><h4>Introduction</h4><p>When dealing with enormous datasets, most of us have experienced the agony of sitting for hours while our Pandas code ran. Polars library comes in handy here.</p><blockquote>Polars is a lightning-fast library that can handle data frames significantly more quickly than Pandas.</blockquote><p>We’ve seen huge releases in these two libraries in the last month that claim significant speed gains. Pandas 2.0, which was just launched, supports Apache Arrows, leading to performance enhancements. Several fundamental operations, however, continue to be faster on NumPy arrays. Polaris 0.17.0, which was released last week, has also seen performance improvements[1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-KE584F6OXjPoFXcE8fJ9A.png" /><figcaption>But what makes Polars faster and more efficient than Pandas? Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><ol><li><strong>Built-in Support for Rust:</strong> Polars is written in <strong>Rust</strong>. Rust’s ability to be immediately compiled into machine code without the use of an interpreter can make it faster than Python.</li><li><strong>Parallelization</strong>: Polars leverage multithreading. It allows for vectorized operations that can be executed in parallel on multiple CPU cores.</li><li><strong>Python for Interface:</strong> Polars can be used as a Python library, providing an easy-to-use interface for data processing while leveraging the performance benefits of Rust.</li><li><strong>Lazy evaluation</strong>: Polars supports two APIs lazy as well as eager evaluation(used by pandas). In lazy evaluation, a query is executed only when required. While in eager evaluation, a query is executed immediately.</li></ol><p>In this post, I’ll be spilling the beans on</p><ol><li><em>Comparing the speed of both Pandas 2.0 (with Numpy and Pyarrow as backend) and Polars 0.17.0.</em></li><li><em>How to write simple to complex Pandas code effortlessly in the groundbreaking Polars library.</em></li></ol><p>We’ll be conducting an exciting performance showdown between the two libraries on 4-CPU core processors and 32 GB RAM. Get ready to take your data analysis skills to new heights!</p><h4>Getting Started</h4><p>In case you don’t have the library on your local machine. It can be installed via the pip command</p><pre>pip install polars==0.17.0 # Latest version<br><br>pip install pandas==2.0.0  # Latest pandas version</pre><p>In order to assess performance, we will be using a synthetic dataset comprised of 30 million rows and 15 columns. The dataset is composed of 8 categorical and 7 numerical features and has been artificially generated. The dataset can be accessed <a href="https://www.kaggle.com/datasets/chaudharypriyanshu/polars-20-vs-pandas-dataset-for-comparison/settings">here</a>.</p><p>A sample of the dataset is shown below</p><pre># Pandas<br>train_pd.head()<br><br>#Polars<br>train_pl.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*n1gCZufG1aJoG7hCGa9h5w.png" /><figcaption>Sample dataset for speed and syntax analysis</figcaption></figure><p>Import the Relevant libraries</p><pre>import pandas as pd<br>import polars as pl<br>import numpy as np<br>import time</pre><h4><strong>Reading the dataset</strong></h4><p>Let’s compare the parquet file reading times of both libraries. I have used the code below and used %%time to get the time of execution of codes.</p><pre>train_pd=pd.read_parquet(&#39;./train.parquet&#39;) #Pandas dataframe<br><br>train_pl=pl.read_parquet(&#39;./train.parquet&#39;) #Polars dataframe</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWibbnVYohpKbpjMmL15rw.png" /><figcaption>Reading time comparison. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>When it comes to reading parquet files, Polars and Pandas 2.0 perform similarly in terms of speed. However, Pandas (using the Numpy backend) takes twice as long as Polars to complete this task.</p><h4>Aggregation Operations</h4><p>To evaluate aggregation functions, use the code below, which gives a generic code for scenarios when aggregations (min, max, mean) must be calculated for many columns.</p><pre># pandas query<br>train_pd[nums].agg([&#39;min&#39;,&#39;max&#39;,&#39;mean&#39;,&#39;median&#39;,&#39;std&#39;)<br>train[cats].agg([&#39;nunique&#39;])<br><br># Polars query<br>train_pl.with_columns([<br>    pl.col(nums).min().suffix(&#39;_min&#39;),<br>    pl.col(nums).max().suffix(&#39;_max&#39;),<br>    pl.col(nums).mean().suffix(&#39;_mean&#39;),<br>    pl.col(nums).median().suffix(&#39;_median&#39;),<br>    pl.col(nums).std().suffix(&#39;_std&#39;),<br>    pl.col(cats).nunique().suffix(&#39;_unique&#39;),<br>])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-xfg0arCNVTv4AG3yzTwg.png" /><figcaption>Aggregation function time comparison. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>Pandas are definitely better in syntax and performance for simple queries, though the performance difference is quite minimal. It must be noted that Polars can work with a list of features that are to be aggregated using the same aggregation. whereas in the case of pandas that is not the case for the situation coded above, hence I have defined the two data frames for comparison.</p><h4>Filtering and Selection operations</h4><p>Selection and filter operations involve specifying a condition for extraction of the database on which the data frame is presented. In order to understand this consider the below queries</p><p><strong>Query 1</strong>: Count unique values for categorical columns when nums_8 is smaller than 10.</p><pre># Polars filter and select<br>train_pl.filter(pl.col(&quot;num_8&quot;) &lt;= 10).select(pl.col(cats).n_unique()) <br><br># Pandas filter and select<br>train_pd[train_pd[&#39;num_8&#39;]&lt;=10][cats].nunique()</pre><p><strong>Query 2</strong>: The mean of all numerical columns when cat_1 equals 1.</p><pre># Polars filter and select<br>train_pl.filter(pl.col(&quot;cat_1&quot;) == 1).select(pl.col(nums).mean())<br><br># Pandas filter and select<br>train_pd[train_pd[&#39;cat_1&#39;]==1][nums].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XR09526SmAUHrBwr0lfFzg.png" /><figcaption>Selection and filtering time comparison. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>In terms of performance, Polars is 2–5 times faster for numerical filter operations, whereas Pandas requires less code to be written. It must be noted that Pandas is slower when it comes to working with strings (categorical features).</p><h4>Grouping Operations</h4><p>Grouping operation is one of the essential features that is used to create aggregation features in machine learning, knowing the statistics of the data.</p><p>I have tested the performance of these libraries on functions I have defined below</p><p><strong>Function 1:</strong> count aggregated features for cat_1</p><p><strong>Function 2: </strong>Mean feature for num_7</p><p><strong>Function 3:</strong> Mean aggregated features for all numerical columns</p><p><strong>Function 4:</strong> count aggregated features for categorical columns</p><pre>nums=[&#39;num_7&#39;,&#39;num_8&#39;, &#39;num_9&#39;, &#39;num_10&#39;, &#39;num_11&#39;, &#39;num_12&#39;, &#39;num_13&#39;, &#39;num_14&#39;,&#39;num_15&#39;]<br>cats=[&#39;cat_1&#39;, &#39;cat_2&#39;, &#39;cat_3&#39;, &#39;cat_4&#39;, &#39;cat_5&#39;, &#39;cat_6&#39;]<br><br># Pandas Functions<br>Function_1= train_pd.groupby([&#39;user&#39;])[&#39;cat_1&#39;].agg(&#39;count&#39;)   #Function 1<br>Function_2= train_pd.groupby([&#39;user&#39;])[&#39;num_7&#39;].agg(&#39;mean&#39;)    #Function 2<br>Function_3= train_pd.groupby([&#39;user&#39;])[nums].agg(&#39;mean&#39;)       #Function 3<br>Function_4= train_pd.groupby([&#39;user&#39;])[cats].agg(&#39;count&#39;)      #Function 4<br><br><br># Polars Functions<br>Function_1= train_pl.groupby(&#39;user&#39;).agg(pl.col(&#39;cat_1&#39;).count()) #Function 1<br>Function_2= train_pl.groupby(&#39;user&#39;).agg(pl.col(&#39;num_7&#39;).mean())  #Function 2<br>Function_3= train_pl.groupby(&#39;user&#39;).agg(pl.col(nums).mean())     #Function 3<br>Function_4= train_pl.groupby(&#39;user&#39;).agg(pl.col(cats).count())    #Function 4</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9H3vtzvtpgEczi3OVtN2g.png" /><figcaption>Comparison of groupby functions. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>Polars appear to be the best choice for Grouping and aggregations. It should also be observed that Pandas 2.0 with the Pyarrow backend is noticeably slower in all circumstances than both Polars and Pandas 2.0 (numpy backend).</p><p>Next, let’s consider how the time changes as the number of grouping variables are raised from one to five, as coded below.<br><strong>Pandas 2.0 with Pyarrow support is not shown in the diagram since the expression evaluation takes more than 1000 seconds.</strong></p><pre># PANDAS: TESTING GROUPING SPEED ON 5 COLUMNS<br>for cat in [&#39;user&#39;, &#39;cat_1&#39;, &#39;cat_2&#39;, &#39;cat_3&#39;, &#39;cat_4&#39;]:<br>  cols+=[cat]<br>  st=time.time()<br>  temp=train_pd.groupby(cols)[&#39;num_7&#39;].agg(&#39;mean&#39;)<br>  en=time.time()<br>  print(cat,&#39;:&#39;,en-st)<br><br><br># POLARS: TESTING GROUPING SPEED ON 5 COLUMNS<br>for cat in [&#39;user&#39;, &#39;cat_1&#39;, &#39;cat_2&#39;, &#39;cat_3&#39;, &#39;cat_4&#39;]:<br>  cols+=[cat]<br>  st=time.time()<br>  temp=train_pl.groupby(cols).agg(pl.col(&#39;num_7&#39;).mean())<br>  en=time.time()<br>  print(cat,&#39;:&#39;,en-st)<br>  del temp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFoWyTh-Zt_JO3r79-0J2Q.png" /><figcaption>Grouping for one or more than one variable. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>The Polars have won again! Pandas 2.0 (Numpy Backend) evaluates grouping functions more slowly. whereas Pyarrow support for Pandas 2.0 is taking greater than 1000 seconds.</p><p><em>Note that Pandas by default remove null values while grouping, whereas Polars library doesn&#39;t.</em></p><h4>Sorting Operation</h4><p>We can quickly sort a data frame based on one or more columns, either in ascending or descending order, using the below codes.</p><pre>cols=[&#39;user&#39;,&#39;num_8&#39;] # columns to be used for sorting<br><br>#Sorting in Polars<br>train_pl.sort(cols,descending=False)<br><br># Sorting in Pandas<br>train_pd.sort_values(by=cols,ascending=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Blya6y4zfInlBPe-u2nOEA.png" /><figcaption>Sorting time comparison. Image by <a href="https://medium.com/@chaudharypriyanshu7401">author</a></figcaption></figure><p>Polars is still the fastest library for complex cases like sorting, and grouping as can be seen from the bar charts. While Pandas can take minutes of time to simply sort the data frame complex sorting functions can be evaluated in not more than 15 seconds in polars.</p><h4>Conclusion</h4><p>In conclusion, choosing the right tool for working with large datasets is essential for data scientists. Our exploration of the performance differences between Pandas and Polars highlights the benefits and drawbacks of each library. While Pandas is more syntactically appealing, Polars offers better throughput when working with larger data frames.</p><p>It’s important to note that since Polars is a newer library, some people may find it challenging to transition from Pandas. However, the decision to use either library ultimately depends on the size of your data and how crucial performance is for your work. By understanding the differences between these two powerful tools, data scientists can choose the best option for their specific needs and achieve more efficient and effective data analysis.</p><p>References:</p><p>[1] <a href="https://github.com/pola-rs/polars/releases/tag/py-0.17.0">https://github.com/pola-rs/polars/releases/tag/py-0.17.0</a></p><p>[2] <a href="https://www.pola.rs/">https://www.pola.rs/</a></p><p>[3] <a href="https://pandas.pydata.org/docs/dev/whatsnew/v2.0.0.html">https://pandas.pydata.org/docs/dev/whatsnew/v2.0.0.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a378eb75d6d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuenex/pandas-2-0-vs-polars-the-ultimate-battle-a378eb75d6d1">Pandas 2.0 vs Polars: The Ultimate Battle</a> was originally published in <a href="https://medium.com/cuenex">CueNex</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extract Neural Network Embeddings]]></title>
            <link>https://medium.com/cuenex/how-to-extract-neural-network-embeddings-37e5a167a94b?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/37e5a167a94b</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[credit]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 06:06:20 GMT</pubDate>
            <atom:updated>2023-03-29T06:53:08.248Z</atom:updated>
            <content:encoded><![CDATA[<h4>MACHINE LEARNING</h4><h4>Enhancing Predictive Accuracy with Neural Network Embeddings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1J2pYWOC-eTBF-ZTgibmAQ.jpeg" /><figcaption>automatic feature extraction</figcaption></figure><h4>Introduction</h4><p>In our previous feature engineering blog, we looked at the ways of <a href="https://medium.com/p/e1ded4b63ff7">handcrafted feature engineering</a>. In this blog, we will be looking at the automatic feature engineering done by neural networks and how to extract those embeddings and use them along with handcrafted features.<br>Note that we have utilized the TensorFlow framework for all our neural network-based pipelines, so this method will work only when you are using the TensorFlow framework. Before diving into the process of embeddings extraction, let&#39;s first understand what embeddings are and how the idea came about.</p><h4>Understanding embeddings</h4><p>Though the idea of embeddings was introduced in the <a href="https://asistdl.onlinelibrary.wiley.com/doi/abs/10.1002/(SICI)1097-4571(199009)41:6%3C391::AID-ASI1%3E3.0.CO;2-9">early 90s</a>, in the modern era, it became famous when in 2013, Tomas Mikolov and colleagues introduced the <a href="https://arxiv.org/abs/1301.3781">Word2Vec</a> algorithm, which used a neural network to generate embeddings that capture semantic relationships between words. This breakthrough led to the widespread adoption of word embeddings in NLP applications. Similarly, we can also represent the tabular data in the form of embeddings by passing it through single or multiple dense layers.</p><p>We can think of embeddings as outputs or encoded representations of data that machines can interpret and that capture temporal, spatial, and contextual information depending on the application. These encoded representations are subsequently delivered to a classifier layer or layers, which provide the desired output.</p><p>In our case, the data is from credit default detection, and the embeddings will be the output from all the intermediate layers of the neural network. Normally these encodings will be passed to the classifier head (the dense layer) in neural networks, but we can pass them to different models such as LGBM (light GBM), SVM (support vector machines), etc. that will act as a classifier head.</p><h4>Model</h4><p>We are using our previous neural network model that we have defined in our <a href="https://medium.com/p/c31d43eff10d">blog</a>.<strong> </strong>The Network along with an embedding layer is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*KERwV5uqKKJR30JvprrXRQ.png" /><figcaption>Neural Network with an embedding layer</figcaption></figure><p><strong>The changes that are to be made have been done in the below code.</strong></p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.callbacks import ReduceLROnPlateau, LearningRateScheduler, EarlyStopping<br>from tensorflow.keras.layers import Dense, Input, InputLayer, Add, Concatenate, Dropout, BatchNormalization<br><br>LR_START = 0.01  #defines the learning rate<br>def my_model(n_inputs=len(features)):<br>    &quot;neural network with skip connection, <br>    Returns a compiled instance of TensorFlow.keras.models.Model.&quot;<br>    activation = &#39;swish&#39;<br>    l1 = 1e-7<br>    l2 = 4e-4<br>    inputs = Input(shape=(n_inputs, ))<br>    x0 = BatchNormalization()(inputs)<br>    x0 = Dense(1024, <br>               kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x0)<br>    x0 = Dropout(0.1)(x0)<br>    x1 = Dense(64, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x0)<br>    x2 = Dense(64, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x1)<br>    x3 = Concatenate()([x2, x0])<br>    x3 = Dropout(0.1)(x3)<br>    x4 = Dense(16, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             name=&#39;embeddings&#39;)(x3)#specify the name of the layer<br>    x5 = Dense(1,<br>              activation=&#39;sigmoid&#39;,<br>             name=&#39;output&#39;)(x4)  #specify the name of the layer<br>    model = Model(inputs, [x5,x4])#output x4 to extract embeddings of x4 layer<br>    model.compile(optimizer=tf.keras.optimizers.Nadam(learning_rate=LR_START,clipvalue= 0.5,clipnorm = 1.0),loss=tf.keras.losses.BinaryCrossentropy(),loss_weights=[1., 0.0])<br>    return model</pre><p>Let’s understand the changes we have done.</p><p>Note that we can extract the embeddings from any of the layers that are present in our neural network(x0,x1,x2,x3, …). Here is an example of how we extract the embedding of layer x4.</p><p>To extract features, we have to specify the output in the Model layer of the x4 variable as illustrated below.</p><pre>x4 = Dense(16, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             name=&#39;embeddings&#39;)(x3)#specify the name of the layer<br>x5 = Dense(1,<br>              activation=&#39;sigmoid&#39;,<br>             name=&#39;output&#39;)(x4)  #specify the name of the layer<br>model = Model(inputs, [x5,x4]) #output x4 to extract embeddings of x4 layer</pre><p>Note that we have specified weights in our compile layer of the model so that it does not evaluate based on the x4 embeds as output, as also highlighted in the figure by a red circle.</p><pre>model.compile(optimizer=tf.keras.optimizers.Nadam(learning_rate=LR_START,clipvalue= 0.5,clipnorm = 1.0),loss=tf.keras.losses.BinaryCrossentropy(),loss_weights=[1., 0.0])<br>    return model</pre><h4>Training</h4><p>Now that we have added x4 embeds in our output, we also have to specify that our model does not evaluate on x4 embeds, or else it can lead to a logical error.</p><pre>from sklearn.model_selection import StratifiedKFold, StratifiedGroupKFold<br>from sklearn.preprocessing import StandardScaler, QuantileTransformer, OneHotEncoder<br><br>&#39;&#39;&#39; function for scaling data, training of model and validating it<br>code ref: https://www.kaggle.com/code/ambrosm/amex-keras-quickstart-1-training<br>&#39;&#39;&#39;<br>def fit_model(X_tr, y_tr, X_va=None, y_va=None, fold=0, run=0):<br><br>    global y_va_pred<br>    gc.collect()<br>    start_time = datetime.datetime.now()<br>    <br>    scaler = StandardScaler()  #scales the training data<br>    X_tr = scaler.fit_transform(X_tr)<br>    <br>    if X_va is not None:<br>        X_va = scaler.transform(X_va)  #scales the validation data<br>        validation_data = (X_va,[y_va, np.zeros((len(y_va),16))])<br>    else:<br>        validation_data = None<br>    # Define the learning rate schedule and EarlyStopping<br>    if USE_PLATEAU and X_va is not None: # use early stopping<br>        epochs = EPOCHS<br>        lr = ReduceLROnPlateau(monitor=&quot;val_output_loss&quot;, factor=0.7,  # scheduler  #specify in <br>                               patience=4, verbose=VERBOSE)<br>        es = EarlyStopping(monitor=&quot;val_output_loss&quot;,    #stop training if results does not improve for 12 epochs<br>                           patience=12, <br>                           verbose=1,<br>                           mode=&quot;min&quot;, <br>                           restore_best_weights=True)<br>        callbacks = [lr, es, tf.keras.callbacks.TerminateOnNaN()]<br><br>    else: # use exponential learning rate decay rather than early stopping<br>        epochs = EPOCHS_EXPONENTIALDECAY<br><br>        def exponential_decay(epoch):<br>            # v decays from e^a to 1 in every cycle<br>            # w decays from 1 to 0 in every cycle<br>            # epoch == 0                  -&gt; w = 1 (first epoch of cycle)<br>            # epoch == epochs_per_cycle-1 -&gt; w = 0 (last epoch of cycle)<br>            # higher a -&gt; decay starts with a steeper decline<br>            # ref:<br>            a = 3<br>            epochs_per_cycle = epochs // CYCLES<br>            epoch_in_cycle = epoch % epochs_per_cycle<br>            if epochs_per_cycle &gt; 1:<br>                v = math.exp(a * (1 - epoch_in_cycle / (epochs_per_cycle-1)))<br>                w = (v - 1) / (math.exp(a) - 1)<br>            else:<br>                w = 1<br>            return w * LR_START + (1 - w) * LR_END<br><br>        lr = LearningRateScheduler(exponential_decay, verbose=0)<br>        callbacks = [lr, tf.keras.callbacks.TerminateOnNaN()]<br>        <br>    # Construct and compile the model<br>    model = my_model(X_tr.shape[1])   #define and compile model<br>    # Train the model<br><br>    history = model.fit(X_tr, [y_tr,np.zeros((len(y_tr),16))],    #fit model <br>                        validation_data=validation_data, <br>                        epochs=epochs,<br>                        verbose=VERBOSE,<br>                        batch_size=BATCH_SIZE,<br>                        shuffle=True,<br>                        callbacks=callbacks)<br>    del X_tr, y_tr<br>    with open(f&quot;scaler_{fold}.pickle&quot;, &#39;wb&#39;) as f: pickle.dump(scaler, f)  #save standard scaler for real-time interaction <br>    model.save(f&quot;model_{fold}&quot;) #save model weights<br>    history_list.append(history.history)<br>    callbacks, es, lr, history = None, None, None, None<br><br>    lastloss = f&quot;Training loss: {history_list[-1][&#39;loss&#39;][-1]:.4f} | Val loss: {history_list[-1][&#39;val_loss&#39;][-1]:.4f}&quot;<br>        <br>        # Inference for validation<br>        y_va_pred = model.predict(X_va, batch_size=len(X_va), verbose=0)[0].ravel()<br>        <br>        # Evaluation: Execution time, loss and metrics<br>        score = evaluation_metric(y_va, y_va_pred)<br>        print(f&quot;{Fore.GREEN}{Style.BRIGHT}Fold {run}.{fold} | {str(datetime.datetime.now() - start_time)[-12:-7]}&quot;<br>              f&quot; | {len(history_list[-1][&#39;loss&#39;]):3} ep&quot;<br>              f&quot; | {lastloss} | Score: {score:.5f}{Style.RESET_ALL}&quot;)<br>        score_list.append(score)<br>        <br>        if DIAGRAMS and fold == 0 and run == 0:<br>            # Plot training history<br>            plot_history(history_list[-1], <br>                         title=f&quot;Learning curve&quot;,<br>                         plot_lr=True)<br><br>        # Scale and predict<br>        y_pred_list.append(model.predict(scaler.transform(test), batch_size=128*1024, verbose=0).ravel())</pre><p>Changes that we need to make in our training code are</p><ul><li>Change the validation_data shape as defined below.</li></ul><pre>validation_data = (X_va,[y_va, np.zeros((len(y_va),16))])</pre><ul><li>Change model.fit and change the training labels’ shape.</li></ul><pre>history = model.fit(X_tr, [y_tr,np.zeros((len(y_tr),16))],    #fit model <br>                        validation_data=validation_data, <br>                        epochs=epochs,<br>                        verbose=VERBOSE,<br>                        batch_size=BATCH_SIZE,<br>                        shuffle=True,<br>                        callbacks=callbacks)</pre><ul><li>Change the scheduler to an early stopping behavior so that model only evaluates the true labels, not the embeddings.</li></ul><pre>lr = ReduceLROnPlateau(monitor=&quot;val_output_loss&quot;, factor=0.7,  # scheduler  #specify in <br>                               patience=4, verbose=VERBOSE)<br>es = EarlyStopping(monitor=&quot;val_output_loss&quot;,    #stop training if results does not improve for 12 epochs<br>                           patience=12, <br>                           verbose=1,<br>                           mode=&quot;min&quot;, <br>                           restore_best_weights=True)</pre><p>Now everything is ready we have our embeddings extracted.</p><h4>How to use the embeddings?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-mD5MsyyZCFPwMTq40I3w.png" /><figcaption>Using both automated and handcrafted features.</figcaption></figure><p>The embeddings generated from the neural networks are in tabular format. Therefore, using them can simply be concatenated with the handcrafted features we made in our previous blogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syTCPIUSCQWDRQub85OGDA.png" /></figure><p>We can also extract the embeddings from the GRU model we created <a href="https://medium.com/cuenex/gru-for-credit-default-prediction-734c5dab10bf">here</a> and use those features in our final model. A combination of features carrying temporal information and the handcrafted feature can be of high significance to the model.</p><h4>Conclusion</h4><p>We now know that using embeddings produced by a neural network can be a practical substitute for designing features by hand. We can enhance the effectiveness and accuracy of our machine-learning models by utilizing embeddings, which will ultimately produce better outcomes and more diversity in our pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37e5a167a94b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuenex/how-to-extract-neural-network-embeddings-37e5a167a94b">How to Extract Neural Network Embeddings</a> was originally published in <a href="https://medium.com/cuenex">CueNex</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GRU for Credit Default Prediciton]]></title>
            <link>https://medium.com/cuenex/gru-for-credit-default-prediction-734c5dab10bf?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/734c5dab10bf</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[credit]]></category>
            <category><![CDATA[fraud]]></category>
            <category><![CDATA[gru]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 15:33:54 GMT</pubDate>
            <atom:updated>2023-03-16T01:39:50.043Z</atom:updated>
            <content:encoded><![CDATA[<h4>MACHINE LEARNING</h4><h4>Discover the Benefits of Recurrent Neural Networks for Credit Risk Assessment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*tsUVzSB5GfI4iNNtfJkXVQ.png" /><figcaption>Gated Recurrent unit. <a href="https://medium.com/@chaudharypriyanshu7401">Author</a></figcaption></figure><p>In our previous blogs, we looked at how we process raw data containing customers’ credit histories, create features that involve mean, last, and diff features, and implement models such as <a href="https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8">LGBM</a> and<a href="https://medium.com/cuenex/credit-default-prediction-neural-network-approach-c31d43eff10d"> neural networks</a> for default prediction based on the features we implemented. We also looked at some of the best ways of <a href="https://medium.com/cuenex/boost-the-model-performance-with-handcrafted-features-e1ded4b63ff7">feature engineering </a>that greatly improve the model’s performance.</p><p><em>In this blog, we will be looking at</em></p><ol><li><em>Transforming tabular data to sequential data.</em></li><li><em>How to train a GRU model using this dataset for a binary classification problem.</em></li></ol><p>The main benefits of using different models are that we diversify our prediction pipeline and play a key role in performance for fraud detection-based problems (in our case, credit default prediction). Also, we need to be able to leverage the sequential aspect of our data more efficiently. Recurrent neural networks such as GRU and LSTM are built to be trained on sequential (time<em> series) </em>data and hence can create automatic features that can be relevant to our pipeline.</p><p>For data pre-processing, we will use the <a href="https://rapids.ai/">Rapids</a> cudf and cupy libraries. NVIDIA’s Rapids is an open-source library suite that provides a range of GPU-accelerated data processing and machine-learning capabilities. Rapids libraries are built on top of CUDA, NVIDIA’s parallel computing platform, and offer a faster and more efficient approach to working with large-scale datasets.</p><h4>Tabular to sequential Conversion</h4><p>Some key points to be noted before conversion:</p><ol><li><em>Our dataset has close to 500k customers.</em></li><li><em>Each customer has 1–12 credit card statements generated.</em></li><li><em>Why 1–12 statements only? because a person may have joined later and paid the money(generated credit card statement), not every month. Hence there can be fewer than 12 statements for a customer.</em></li><li><em>We have a total of 147 features for every customer. i.e. 147 features for every statement.</em></li></ol><p>The tabular data has the shape of [S, F]. Where S is the total number of statements for ~500k customers and F the number of features (147 for our case).</p><p>Sequential models like GRUs need data in 3D format. hence we need to convert the provided tabular representation data into the sequential format as depicted below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*sdMDZrjFZ_ZpgCxk" /><figcaption>conversion from Tabular to Sequential</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*IQSBLuHUGPNaz8IihapgKw.png" /><figcaption>Tabular to Sequential data. <a href="https://medium.com/@chaudharypriyanshu7401">Author</a></figcaption></figure><p>Note:</p><p>Since there can be a variable number of bank statements per customer, it is important to make them equal by <strong>padding them up to the maximum value (12 in our case)</strong>. This can be done by using the below code</p><pre># Reference: https://www.kaggle.com/code/cdeotte/tensorflow-gru-starter-0-790<br>import cupy, cudf # GPU LIBRARIES<br>import numpy as np, pandas as pd # CPU LIBRARIES<br><br><br>train=cudf.read_csv(&#39;./train.csv&#39;)<br>targets=cudf.read_csv(&#39;./targets.csv&#39;)<br>CATS = [&#39;B_1&#39;, &#39;B_3&#39;, &#39;B_11&#39;, &#39;D_61&#39;, &#39;P_17&#39;, &#39;P_10&#39;, &#39;P_6&#39;, &#39;P_8&#39;, &#39;P_11&#39;]<br><br>customer = train[[&#39;customer_ID&#39;]].groupby(&#39;customer_ID&#39;).customer_ID.agg(&#39;count&#39;)<br><br>more = cupy.array([],dtype=&#39;int64&#39;) <br>for j in range(1,12):<br>    i = tmp.loc[tmp==j].index.values    #selecting customers with j number of statements<br>    more = cupy.concatenate([more,cupy.repeat(i,12-j)]) #pad customer 12-j times<br>df = train.iloc[:len(more)].copy().fillna(0) #fill null values<br>df = df * 0 - 1 #pad numerical columns with -1  (df*0 makes all values 0 of a dataframe)<br>df[CATS] = (df[CATS] * 0).astype(&#39;int8&#39;) #pad categorical columns with 0<br>df[&#39;customer_ID&#39;] = more<br>train = cudf.concat([train,df],axis=0,ignore_index=True) #concat original and pad data<br>        <br>    # ADD TARGETS (and reduce to 1 byte)<br>train = train.merge(targets,on=&#39;customer_ID&#39;,how=&#39;left&#39;)<br>train.target = train.target.astype(&#39;int8&#39;)<br># FILL NAN<br>train = train.fillna(-0.5) #this applies to numerical columns<br><br># SORT BY CUSTOMER THEN DATE<br>train = train.sort_values([&#39;customer_ID&#39;,&#39;year&#39;,&#39;month&#39;,&#39;day&#39;]).reset_index(drop=True) <br>train = train.drop([&#39;year&#39;,&#39;month&#39;,&#39;day&#39;],axis=1)<br><br># REARRANGE COLUMNS WITH 11 CATS FIRST<br>COLS = list(train.columns[1:])<br><br>COLS = [&#39;customer_ID&#39;] + CATS + [c for c in COLS if c not in CATS]<br>train = train[COLS]<br><br>train = train.iloc[:,1:-1].values.reshape((-1,12,147)) # reshape the data into sequential data [customer,statement,features]</pre><p>Note we must pad the numerical and categorical columns with those values that are not present in that feature else we are introducing noise to our dataset.</p><h4>Model</h4><p>Here we define a simple GRU model shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*xi0SdBbf3fByMAmCwm1zNQ.png" /></figure><ol><li><em>Takes input with shape [Batch_size, Statements, Features]. (</em><em>[Batch_size,12,147] for our case).</em></li><li><em>Convert the first 10 categorical features into embeddings.</em></li><li><em>Use a GRU layer with 64 units that will output </em><em>[Batch_size,64] a vector. The GRU layer account for accounting for the sequential aspect of data.</em></li><li><em>The two dense layers are cascaded together the first layer takes the output from GRU and passes it to the second layer from the GRU layer and outputs a vector of shape from the two layers is </em><em>[Batch_size,64] and </em><em>[Batch_size,32] respectively.</em></li><li><em>The final dense layer outputs the probability of customer default.</em></li></ol><pre>def gru_model():<br>    input = tf.keras.Input(shape=(12,147)) # shape of input<br>    embeds = []<br>    for k in range(11):<br>        emb = tf.keras.layers.Embedding(11,5) #convert to embdding of size 5<br>        embeds.append( emb(inp[:,:,k]) )<br>    x = tf.keras.layers.Concatenate()([inp[:,:,10:]]+embeds) #first 10 are categorical and remaningg are numerical that can be passed as it is<br>    <br>    #GRU layer outputs- [batch_size,64]<br>    x = tf.keras.layers.GRU(units=64, return_sequences=False)(x)<br>    <br>    #Dense layer outputs- [batch_size,64]<br>    x = tf.keras.layers.Dense(64,activation=&#39;relu&#39;)(x)<br>    #Dense layer outputs- [batch_size,32]<br>    x = tf.keras.layers.Dense(32,activation=&#39;relu&#39;)(x)<br>    <br>    # OUTPUT<br>    x = tf.keras.layers.Dense(1,activation=&#39;sigmoid&#39;)(x)<br>    <br>    # COMPILE MODEL<br>    model = tf.keras.Model(inputs=inp, outputs=x)<br>    opt = tf.keras.optimizers.Adam(learning_rate=0.004)<br>    loss = tf.keras.losses.BinaryCrossentropy()<br>    model.compile(loss=loss, optimizer = opt)<br>    return model<br><br><br># Define a learning rate scheduler to manipulate learning rate<br>LR=tf.keras.callbacks.ReduceLROnPlateau(<br>    monitor=&quot;val_loss&quot;,<br>    factor=0.1,<br>    patience=1,<br>    verbose=0,<br>    mode=&quot;auto&quot;,<br>    min_delta=0.001,<br>    cooldown=0,<br>    min_lr=0,<br>    **kwargs<br>)</pre><p>We will be using the same metric as was used in our previous blogs.</p><pre>#  Reference: https://www.kaggle.com/competitions/amex-default-prediction/discussion/327534<br>def default_metric(y_true, y_pred):<br><br>    labels     = np.transpose(np.array([y_true, y_pred]))<br>    labels     = labels[labels[:, 1].argsort()[::-1]]<br>    weights    = np.where(labels[:,0]==0, 20, 1)<br>    cut_vals   = labels[np.cumsum(weights) &lt;= int(0.04 * np.sum(weights))]<br>    top_four   = np.sum(cut_vals[:,0]) / np.sum(labels[:,0])<br><br>    gini = [0,0]<br>    for i in [1,0]:<br>        labels         = np.transpose(np.array([y_true, y_pred]))<br>        labels         = labels[labels[:, i].argsort()[::-1]]<br>        weight         = np.where(labels[:,0]==0, 20, 1)<br>        weight_random  = np.cumsum(weight / np.sum(weight))<br>        total_pos      = np.sum(labels[:, 0] *  weight)<br>        cum_pos_found  = np.cumsum(labels[:, 0] * weight)<br>        lorentz        = cum_pos_found / total_pos<br>        gini[i]        = np.sum((lorentz - weight_random) * weight)<br><br>    return 0.5 * (gini[1]/gini[0] + top_four)</pre><h4>Training</h4><p>Here we define our training module:</p><ul><li><em>Takes training data in the form of a 3D- numpy array as input.</em></li><li><em>Use stratified Kfold( 5 folds) to handle Data Imbalance.</em></li><li><em>Train a simple GRU model and validate it on our validation data.</em></li></ul><pre>PATH_TO_MODEL = &#39;./Models&#39;<br>from sklearn.model_selection import StratifiedKFold   <br>   # SAVE TRUE AND OOF<br>    true = np.array([])<br>    oof = np.array([])#for saving valid predictions<br>    VERBOSE = 2 # use 1 for interactive <br><br>    USE_FIRST_FOLD = True<br>    kf= StratifiedKFold(n_splits=5)<br>    for fold,(trn_idx,val_idx) in enumerate(kf.split(train,target)):<br>        print(&#39;#&#39;*25)<br>        print(f&#39;### Fold {fold+1}&#39;)<br>        X_train, X_test = X[trn_idx], X[val_idx]<br>        y_train, y_test = y[trn_idx], y[val_idx]<br><br>        # BUILD AND TRAIN MODEL<br>        model = gru_model()<br>        h = model.fit(X_train,y_train, <br>                      validation_data = (X_valid,y_valid),<br>                      batch_size=512, epochs=8, verbose=VERBOSE,<br>                      callbacks = [LR])<br>        #batch size =512, use 8 epochs only <br>        if not os.path.exists(PATH_TO_MODEL): os.makedirs(PATH_TO_MODEL)<br>        model.save_weights(f&#39;{PATH_TO_MODEL}gru_fold_{fold+1}.h5&#39;)<br><br>        # INFER VALID DATA<br>        print(&#39;#&#39;*25)<br>        print(&#39;Inferring validation data...&#39;)<br>        p = model.predict(X_valid, batch_size=512, verbose=VERBOSE).flatten()<br><br>        print(&#39;#&#39;*100)<br>        print(f&#39;Fold {fold+1} CV=&#39;, amex_metric_mod(y_valid, p) )<br>        print(&#39;#&#39;*100)<br>        true = np.concatenate([true, y_valid])<br>        oof = np.concatenate([oof, p])<br>        <br>        # CLEAN MEMORY<br>        del model, X_train, y_train, X_valid, y_valid, p<br>        gc.collect()<br><br>    if(USE_FIRST_FOLD):<br>        break;<br>    # PRINT OVERALL RESULTS<br>    if(!USE_FIRST_FOLD):<br>      print(&#39;#&#39;*25)<br>      print(f&#39;Overall CV =&#39;, default_metric(true, oof) )<br> </pre><pre>#########################<br>### Fold 1<br>#########################<br>Epoch 1/8<br>765/765 - 16s - loss: 0.2383 - val_loss: 0.2307<br>Epoch 2/8<br>765/765 - 9s - loss: 0.2258 - val_loss: 0.2299<br>Epoch 3/8<br>765/765 - 9s - loss: 0.2230 - val_loss: 0.2266<br>Epoch 4/8<br>765/765 - 9s - loss: 0.2210 - val_loss: 0.2294<br>Epoch 5/8<br>765/765 - 9s - loss: 0.2191 - val_loss: 0.2295<br>Epoch 6/8<br>765/765 - 9s - loss: 0.2176 - val_loss: 0.2242<br>Epoch 7/8<br>765/765 - 9s - loss: 0.2156 - val_loss: 0.2237<br>Epoch 8/8<br>765/765 - 9s - loss: 0.2142 - val_loss: 0.2254<br>Inferring validation data...<br>180/180 - 1s<br><br>Fold 1 CV= 0.7866987109852964</pre><p>We receive a score of 0.78669 on our defined metrics for the first fold. The score can further be improved by</p><ul><li><em>Training for all folds.</em></li><li><em>Adding more layers to the network.</em></li><li><em>More preprocessing of the data.</em></li><li><em>Changing learning rate, Learning rate scheduler.</em></li></ul><p>Things that can didn’t for our dataset but are worth trying:</p><ul><li><em>Use bidirectional GRU/LSTM</em></li><li><em>Use of 1D CNN block</em></li><li><em>Using all hidden states or some modifications of the states output from GRU layers.</em></li></ul><h4>Conclusion</h4><p>To sum up, this blog has highlighted the importance of incorporating sequential aspects of data while modeling, and how a tabular dataset can be transformed into a 3D sequential representation for better results. Although LGBM-based models may outperform other models on sequential data, ensembling and diversifying the pipeline can still benefit from their inclusion. Overall, it is essential to consider the sequential nature of data while building models, as it can significantly impact their performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734c5dab10bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuenex/gru-for-credit-default-prediction-734c5dab10bf">GRU for Credit Default Prediciton</a> was originally published in <a href="https://medium.com/cuenex">CueNex</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Default Prediction — Neural Network Approach]]></title>
            <link>https://medium.com/cuenex/credit-default-prediction-neural-network-approach-c31d43eff10d?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/c31d43eff10d</guid>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[credit]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 09:20:40 GMT</pubDate>
            <atom:updated>2023-03-06T10:52:08.230Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine learning</h4><h3>Credit Default Prediction — Neural Network Approach</h3><h4>An Illustrative modeling guide using Tensorflow</h4><figure><img alt="Artificial Neural Networks structural diagram" src="https://cdn-images-1.medium.com/max/1024/1*yBjt_ZxPCG4WiZvU-oFR8g.png" /><figcaption><strong>Artificial Neural Network</strong></figcaption></figure><p>In our previous posts, we explored the exciting world of<a href="https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8"> machine learning</a> and <a href="https://medium.com/cuenex/boost-the-model-performance-with-handcrafted-features-e1ded4b63ff7">feature engineering</a>, highlighting the importance of setting up a solid baseline for credit default prediction using the <a href="https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8">LightGBM</a> model. Today, we’re diving deeper into neural networks, a powerful form of artificial intelligence that&#39;s transforming how financial institutions can detect and manage credit defaults. Get ready to dive into our latest blog where we’ll be sharing our firsthand experience on how neural networks can be harnessed to predict credit defaults.</p><h4>Data preparation</h4><p>For this blog post, we’ll be utilizing the features we generated in our initial <a href="https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8">post</a>. We’ll be loading up the data that we meticulously engineered in our previous post and putting it to work.</p><pre>import pandas as pd<br>import numpy as np<br>import pickle<br>import gc<br><br>DATA_PATH=&#39;./&#39;  # Add the data path in which the training data is stored<br><br>train=pd.read_parquet(Data_Path+&#39;train.parquet&#39;)  # Name your training data as train.parquet<br>target=pd.read_csv(&#39;/content/train_labels.csv&#39;).target.values #load the training labels<br><br><br>print(&#39;shape of training data is:&#39;,train.shape)<br>display(train.head())</pre><figure><img alt="Sample image of the training data" src="https://cdn-images-1.medium.com/max/782/1*2ZGRbee8l5m8SKaO6PbVIQ.png" /><figcaption><strong>Sample image of training data</strong></figcaption></figure><p>To expedite the loading process via Pandas, we have stored our data in the parquet format, which also helps to reduce the size of our data.</p><p>We use the same metric we defined in our previous blog, a combination of AUC and Recall rate at a threshold of 4% coded below:</p><pre>from sklearn.metrics import roc_curve, roc_auc_score<br><br># code ref: https://www.kaggle.com/code/inversion/amex-competition-metric-python<br>def evaluation_metric(y_true, y_pred, return_components=False) -&gt; float:<br>    &quot;&quot;&quot;evaluation metric for ndarrays&quot;&quot;&quot;<br>    def top_four_percent_captured(df) -&gt; float:<br>        &quot;&quot;&quot;Corresponds to the recall for a threshold of 4 %&quot;&quot;&quot;<br>        df[&#39;weight&#39;] = df[&#39;target&#39;].apply(lambda x: 20 if x==0 else 1)<br>        four_pct_cutoff = int(0.04 * df[&#39;weight&#39;].sum())<br>        df[&#39;weight_cumsum&#39;] = df[&#39;weight&#39;].cumsum()<br>        df_cutoff = df.loc[df[&#39;weight_cumsum&#39;] &lt;= four_pct_cutoff]<br>        return (df_cutoff[&#39;target&#39;] == 1).sum() / (df[&#39;target&#39;] == 1).sum()<br>        <br>    def weighted_gini(df) -&gt; float:<br>        df[&#39;weight&#39;] = df[&#39;target&#39;].apply(lambda x: 20 if x==0 else 1)<br>        df[&#39;random&#39;] = (df[&#39;weight&#39;] / df[&#39;weight&#39;].sum()).cumsum()<br>        total_pos = (df[&#39;target&#39;] * df[&#39;weight&#39;]).sum()<br>        df[&#39;cum_pos_found&#39;] = (df[&#39;target&#39;] * df[&#39;weight&#39;]).cumsum()<br>        df[&#39;lorentz&#39;] = df[&#39;cum_pos_found&#39;] / total_pos<br>        df[&#39;gini&#39;] = (df[&#39;lorentz&#39;] - df[&#39;random&#39;]) * df[&#39;weight&#39;]<br>        return df[&#39;gini&#39;].sum()<br><br>    def normalized_weighted_gini(df) -&gt; float:<br>        &quot;&quot;&quot;Corresponds to 2 * AUC - 1&quot;&quot;&quot;<br>        df2 = pd.DataFrame({&#39;target&#39;: df.target, &#39;prediction&#39;: df.target})<br>        df2.sort_values(&#39;prediction&#39;, ascending=False, inplace=True)<br>        return weighted_gini(df) / weighted_gini(df2)<br><br>    df = pd.DataFrame({&#39;target&#39;: y_true.ravel(), &#39;prediction&#39;: y_pred.ravel()})<br>    df.sort_values(&#39;prediction&#39;, ascending=False, inplace=True)<br>    g = normalized_weighted_gini(df)<br>    d = top_four_percent_captured(df)<br><br>    if return_components: return g, d, 0.5 * (g + d)<br>    return 0.5 * (g + d)</pre><h4>Model Architecture:</h4><p>The architecture of the model we used in training is shown below:</p><figure><img alt="Neural Network Architecture for credit default detection" src="https://cdn-images-1.medium.com/max/386/1*0pdeed2jeFM1pabr4gr2Pg.png" /><figcaption>Neural Network Architecture</figcaption></figure><ul><li>The Input layer is created with the shape (n_inputs,), where n_inputs is the number of features in the input data.</li><li>During training, the activations of a prior layer are normalized using the batchNormalizationtechnique in neural networks. It can increase convergence speed, lessen overfitting, and stabilize training.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*xOOwm3vakHZZ9fkuAige3g.png" /><figcaption>reference:<a href="https://arxiv.org/pdf/1502.03167.pdf">https://arxiv.org/pdf/1502.03167.pdf</a></figcaption></figure><ul><li>The Dense layers are used in the given code to transform the input data by applying a set of learned weights to the previous layer’s inputs, followed by an activation function.</li><li>The Concatenate layer is used to create a <strong>skip connection</strong> between the output of the second Dense layer and the output of the first Dense layer, before the third Dense layer. The skip connection allows the output of the first Dense layer to be directly passed to the third Dense layer, without having to pass through the second Dense layer again. This can help to preserve information from the earlier layers and improve the flow of gradients during backpropagation.</li></ul><p>The neural network can be implemented using the below code.</p><pre>import tensorflow as tf<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.callbacks import ReduceLROnPlateau, LearningRateScheduler, EarlyStopping<br>from tensorflow.keras.layers import Dense, Input, InputLayer, Add, Concatenate, Dropout, BatchNormalization<br><br>LR_START = 0.01  #defines the learning rate<br>def my_model(n_inputs=len(features)):<br>    &quot;neural network with skip connection, <br>    Returns a compiled instance of TensorFlow.keras.models.Model.&quot;<br>    activation = &#39;swish&#39;<br>    l1 = 1e-7<br>    l2 = 4e-4<br>    inputs = Input(shape=(n_inputs, ))<br>    x0 = BatchNormalization()(inputs)<br>    x0 = Dense(1024, <br>               kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x0)<br>    x0 = Dropout(0.1)(x0)<br>    x = Dense(64, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x0)<br>    x = Dense(64, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x)<br>    x = Concatenate()([x, x0])<br>    x = Dropout(0.1)(x)<br>    x = Dense(16, <br>              kernel_regularizer=tf.keras.regularizers.L1L2(l1=l1,l2=l2),<br>              activation=activation,<br>             )(x)<br>    x = Dense(1,<br>              activation=&#39;sigmoid&#39;,<br>             )(x)<br>    model = Model(inputs, x)<br>    model.compile(optimizer=tf.keras.optimizers.Nadam(learning_rate=LR_START,clipvalue= 0.5,clipnorm = 1.0<br>                                                     ),loss=tf.keras.losses.BinaryCrossentropy())<br>    return model<br></pre><ul><li>The Dense layers in the code have different numbers of neurons and activation functions. The first Dense layer has 1024 neurons and uses the swish activation function. The second and third Dense layers have 64 neurons and also use the swish activation function. The fourth Dense layer has 16 neurons and uses the swish activation function. The swish function is formulated as :</li></ul><figure><img alt="Swish activation formula" src="https://cdn-images-1.medium.com/max/310/0*aoksXogcSKhQb4LX" /></figure><ul><li>Dropout layers are used in the given code to apply regularisation by randomly dropping out a fraction of the activations in the previous layer during training. In this code, the fraction of activations that drop out is set to 0.1. Dropout reduces the co-adaptation of neurons in the same layer, which helps to prevent overfitting.</li></ul><p>We define some parameters we will need for our model training</p><pre>from matplotlib import pyplot as plt<br>import random<br>import datetime<br>import math<br>from matplotlib.ticker import MaxNLocator<br>from colorama import Fore, Back, Style<br><br># Cross-validation of the classifier<br>ONLY_FIRST_FOLD = True<br>EPOCHS_EXPONENTIALDECAY = 100<br>VERBOSE = 0 # set to 0 for less output, or to 2 for more output<br>LR_END = 1e-5 # minimum learning rate possible<br>CYCLES = 1 #define how many cycles are there in our learning rate<br>EPOCHS = 200 #total epochs<br>DIAGRAMS = True<br>USE_PLATEAU = False # set to True for early stopping, or to False for exponential learning rate decay<br>BATCH_SIZE = 2048<br><br># Setting seeds for results reproducibility<br>np.random.seed(1)<br>random.seed(1)<br>tf.random.set_seed(1)</pre><h4>Model Training</h4><p>We define a function that trains a model given training and validation data, saves the model weights, and plots the corresponding learning curve.</p><pre>from sklearn.model_selection import StratifiedKFold, StratifiedGroupKFold<br>from sklearn.preprocessing import StandardScaler, QuantileTransformer, OneHotEncoder<br><br>&#39;&#39;&#39; function for scaling data, training of model and validting it<br>code ref: https://www.kaggle.com/code/ambrosm/amex-keras-quickstart-1-training<br>&#39;&#39;&#39;<br>def fit_model(X_tr, y_tr, X_va=None, y_va=None, fold=0, run=0):<br><br>    global y_va_pred<br>    gc.collect()<br>    start_time = datetime.datetime.now()<br>    <br>    scaler = StandardScaler()  #scales the training data<br>    X_tr = scaler.fit_transform(X_tr)<br>    <br>    if X_va is not None:<br>        X_va = scaler.transform(X_va)  #scales the validation data<br>        validation_data = (X_va, y_va)<br>    else:<br>        validation_data = None<br>    # Define the learning rate schedule and EarlyStopping<br>    if USE_PLATEAU and X_va is not None: # use early stopping<br>        epochs = EPOCHS<br>        lr = ReduceLROnPlateau(monitor=&quot;val_loss&quot;, factor=0.7,  # scheduler<br>                               patience=4, verbose=VERBOSE)<br>        es = EarlyStopping(monitor=&quot;val_loss&quot;,    #stop training if results does not improve for 12 epochs<br>                           patience=12, <br>                           verbose=1,<br>                           mode=&quot;min&quot;, <br>                           restore_best_weights=True)<br>        callbacks = [lr, es, tf.keras.callbacks.TerminateOnNaN()]<br><br>    else: # use exponential learning rate decay rather than early stopping<br>        epochs = EPOCHS_EXPONENTIALDECAY<br><br>        def exponential_decay(epoch):<br>            # v decays from e^a to 1 in every cycle<br>            # w decays from 1 to 0 in every cycle<br>            # epoch == 0                  -&gt; w = 1 (first epoch of cycle)<br>            # epoch == epochs_per_cycle-1 -&gt; w = 0 (last epoch of cycle)<br>            # higher a -&gt; decay starts with a steeper decline<br>            # ref:<br>            a = 3<br>            epochs_per_cycle = epochs // CYCLES<br>            epoch_in_cycle = epoch % epochs_per_cycle<br>            if epochs_per_cycle &gt; 1:<br>                v = math.exp(a * (1 - epoch_in_cycle / (epochs_per_cycle-1)))<br>                w = (v - 1) / (math.exp(a) - 1)<br>            else:<br>                w = 1<br>            return w * LR_START + (1 - w) * LR_END<br><br>        lr = LearningRateScheduler(exponential_decay, verbose=0)<br>        callbacks = [lr, tf.keras.callbacks.TerminateOnNaN()]<br>        <br>    # Construct and compile the model<br>    model = my_model(X_tr.shape[1])   #define and compile model<br>    # Train the model<br>    history = model.fit(X_tr, y_tr,    #fit model <br>                        validation_data=validation_data, <br>                        epochs=epochs,<br>                        verbose=VERBOSE,<br>                        batch_size=BATCH_SIZE,<br>                        shuffle=True,<br>                        callbacks=callbacks)<br>    del X_tr, y_tr<br>    with open(f&quot;scaler_{fold}.pickle&quot;, &#39;wb&#39;) as f: pickle.dump(scaler, f)  #save standard scaler for real-time interaction <br>    model.save(f&quot;model_{fold}&quot;) #save model weights<br>    history_list.append(history.history)<br>    callbacks, es, lr, history = None, None, None, None<br>    <br><br>    lastloss = f&quot;Training loss: {history_list[-1][&#39;loss&#39;][-1]:.4f} | Val loss: {history_list[-1][&#39;val_loss&#39;][-1]:.4f}&quot;<br>        <br>        # Inference for validation<br>        y_va_pred = model.predict(X_va, batch_size=len(X_va), verbose=0).ravel()<br>        <br>        # Evaluation: Execution time, loss and metrics<br>        score = evaluation_metric(y_va, y_va_pred)<br>        print(f&quot;{Fore.GREEN}{Style.BRIGHT}Fold {run}.{fold} | {str(datetime.datetime.now() - start_time)[-12:-7]}&quot;<br>              f&quot; | {len(history_list[-1][&#39;loss&#39;]):3} ep&quot;<br>              f&quot; | {lastloss} | Score: {score:.5f}{Style.RESET_ALL}&quot;)<br>        score_list.append(score)<br>        <br>        if DIAGRAMS and fold == 0 and run == 0:<br>            # Plot training history<br>            plot_history(history_list[-1], <br>                         title=f&quot;Learning curve&quot;,<br>                         plot_lr=True)<br><br>        # Scale and predict<br>        y_pred_list.append(model.predict(scaler.transform(test), batch_size=128*1024, verbose=0).ravel())</pre><p>The code-defined <strong>exponential decay</strong> scheduler is a learning rate scheduler that reduces the learning rate of a neural network model exponentially over time. Also in the below figure, it can be seen the green line defines the exponential decay of the learning rate.</p><p>When it comes to validating your machine learning model, choosing the right strategy is crucial. In order to tackle the issue of imbalanced data in our credit default prediction problem, we implemented the 10-stratified K-fold validation strategy as mentioned in our previous blog. By dividing the data into 10 equally sized folds, each fold is representative of the overall distribution of the data, ensuring that your model is tested on a diverse range of samples. With 90% of the data used for training and 10% reserved for validation, you can rest assured that your model is being put to the test under the most rigorous conditions.</p><pre>history_list = []<br>score_list = []<br>y_pred_list = []<br>kf = StratifiedKFold(n_splits=10) # stratified kfold<br>for fold, (idx_tr, idx_va) in enumerate(kf.split(train, target)):<br>    y_va = target[idx_va]<br>    tf.keras.backend.clear_session() <br>    gc.collect()#free memory<br>    fit_model(train.iloc[idx_tr][features], target[idx_tr], <br>              train.iloc[idx_va][features], y_va, fold=fold)<br>    if ONLY_FIRST_FOLD: break # we only need the first fold<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*2y4NUOLAgdkIg3EGeH2FYQ.png" /></figure><p>Here, we have shown the results of our first fold and training plot we receive a metric score of <strong>0.78543</strong> defined in our first blog.</p><p>Now, let&#39;s understand what this metric score suggests.</p><h4>Understanding the Metric Score</h4><p>The metric we’re using is a combination of the Gini coefficient and a 4% recall rate, calculated as an average value.</p><figure><img alt="ref:https://www.kaggle.com/code/ambrosm/amex-keras-quickstart-1-training" src="https://cdn-images-1.medium.com/max/401/1*Riu2IQzNBxznvJqyDnuMcw.png" /><figcaption>evaluation metric</figcaption></figure><ul><li>The <em>normalized Gini coefficient</em> is simply a scaled AUC: The normalized Gini coefficient is equal to 2*AUC-1 and is always between -1 and 1. The larger the light red area, the better the score. In our case, we receive a score of G=0.92012.</li><li>The <em>recall rate captured at a threshold of 4 % </em>corresponds to the y coordinate of the intersection between the green line and the red roc curve (marked with a green dot) and is always between 0 and 1. The higher the intersection point, the better the default detection capability of the model. We receive a score of R=0.65073.</li><li>We average the score evaluation_metric=(R+G)/2=.78543 which is the score of our first fold.</li></ul><h4><strong>Conclusion</strong></h4><p>In this blog, we discussed how we can leverage Neural Networks for credit default detection. The proposed model receives a score of .78543 for the single fold. The results can further be improved by:</p><ul><li><strong><em>Tuning model parameters</em></strong><em>: adding or changing the units in our neural network.</em></li><li><em>Adjusting the learning rate.</em></li><li><em>Adding more features we discussed in our previous </em><a href="https://medium.com/cuenex/boost-the-model-performance-with-handcrafted-features-e1ded4b63ff7"><em>blog</em></a><em>.</em></li><li><em>Training on all the 10 folds followed by averaging the predictions.</em></li></ul><p>As we continue to explore the potential of machine learning, we encourage you to stay tuned for more exciting developments in this field. Thank you for reading, and we hope this article has inspired you to leverage Neural Networks in your own credit default detection tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c31d43eff10d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuenex/credit-default-prediction-neural-network-approach-c31d43eff10d">Credit Default Prediction — Neural Network Approach</a> was originally published in <a href="https://medium.com/cuenex">CueNex</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost the Model Performance with Handcrafted Features]]></title>
            <link>https://medium.com/cuenex/boost-the-model-performance-with-handcrafted-features-e1ded4b63ff7?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ded4b63ff7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fraud]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 07:52:49 GMT</pubDate>
            <atom:updated>2023-02-27T08:26:06.822Z</atom:updated>
            <content:encoded><![CDATA[<h4>MACHINE LEARNING</h4><h4>Feature Engineering: The Hidden Gems of Credit Default Prediction</h4><p><em>“From raw iron comes the plough that tills the fields and feeds the people, and so too can raw data be transformed into insights that drive business growth and innovation through the process of feature engineering.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*2pf8QFG0cKlrZoL4.jpeg" /></figure><p>In our <a href="https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8">previous blog</a>, we took a high dive into the world of credit default prediction, exploring the foundational concepts and strategies needed to build a reliable model. Now, it’s time to take things to the next level with the powerful technique of feature engineering. By transforming raw data into insightful features, we can unlock new levels of accuracy and performance in our models, paving the way for more precise predictions and smarter business decisions. With feature engineering as your secret weapon, you can optimize your models like never before and elevate your business’s success.</p><p>Raw data is like a jigsaw puzzle with no picture — but with feature engineering, we can put the pieces together to reveal a stunning image of your business’s future! While it’s true that having large amounts of data is a treasure trove for financial institutions seeking to build machine learning models, it’s equally important to acknowledge that not all data is informative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*QwbqZS7jawF-t_Nh.png" /></figure><p>But feature engineering is not just about selecting the best features. It’s also about reducing the noise and redundancies in the data to improve the generalization of the models. This is crucial in a world where new data is constantly being generated, and models need to perform well on unseen data to be truly useful.</p><p>In short, while having tons of data is great, feature engineering is the artistic process of sculpting that data into something beautiful and useful for credit default detection. So join me in this blog as we explore the fascinating world of feature engineering and its role in building high-performance ML models.</p><h4>Dataset</h4><p>Our latest <strong>study</strong> will build upon our previous blog, diving into the world of credit default analysis. We’ll be working with a massive dataset of over half a million customers’ credit statements spanning an entire year. While all features have been anonymized, we do have access to info about the type of feature, including risk, balance, delinquency, and payment features.</p><p>However, the raw dataset isn’t without its flaws. We’re faced with a significant amount of noise that can be attributed to a large number of null values and missing statements, possibly due to customers being unable to pay their credit bills or joining the program later. To address these issues, we’ll need to create informative features that can help our model generalize well.</p><p>If you’re working with large datasets, you’ve likely experienced the frustration of waiting for hours or even days for Pandas to finish calculating features. This is where Rapids.ai comes in, providing a powerful suite of open-source libraries that leverage GPU acceleration to supercharge your data processing and feature engineering.</p><p>With <a href="http://rapids.ai/">Rapids.ai</a>, you can perform data filtering, grouping, and aggregation at lightning-fast speeds, unlocking the potential of your GPU to accelerate even the most complex data manipulation tasks. This can significantly reduce the time required for feature engineering, enabling you to work with larger datasets and iterate more quickly on your models.</p><pre># LOAD LIBRARIES<br>import pandas as pd, numpy as np # CPU libraries<br>import cudf # GPU libraries<br>import matplotlib.pyplot as plt, gc, os</pre><pre>print(&#39;RAPIDS version&#39;,cudf.__version__)<br>df = cudf.read_parquet(&#39;./data.parquet&#39;)</pre><p>But it’s not just about speed — Rapids.ai also provides a Pandas-like API for data manipulation, making it easy to transition from traditional CPU-based methods. You can use familiar functions and syntax to perform complex data transformations, all while taking advantage of GPU acceleration for maximum efficiency.</p><p>In short, if you’re looking to take your data processing and feature engineering to the next level, Rapids.ai is the perfect tool for the job. It’s fast, easy to use, and unlocks the full potential of your GPU to help you build better machine-learning models.</p><h3>Feature Generating methods</h3><p>There can be hundreds of ideas that can be used to generate features; however, we also have to make sure that the features contribute to an increment in the model’s performance or that they are just noisy features, that increase our machine’s memory.</p><p>The below charts show the ideas that are used in feature engineering and are described below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*-Jzx_-5mZ9VIRluQ.png" /></figure><h3>Aggregation features</h3><p>Aggregation features are the secret ingredient to making sense of complex data. By computing summary statistics or aggregations of numerical variables over a categorical grouping variable, like customer_ID (C_ID) or product category, we can uncover patterns and trends that might not be visible at first glance. With summary statistics such as mean, max, min, std, and median, we can build more accurate predictive models and extract meaningful insights from customer data, transactional data, or any other numerical data.</p><p>These statistical attributes per customer can be calculated</p><pre>cat_features = [&quot;B_1&quot;,&quot;B_2&quot;,&quot;D_1&quot;,&quot;D_2&quot;,&quot;D_10&quot;,&quot;P_21&quot;,&quot;D_126&quot;,&quot;D_3&quot;,&quot;D_42&quot;,&quot;R_66&quot;,&quot;R_68&quot;]<br>num_features = [col for col in all_cols if col not in cat_features] #all features accept cateforical features.<br>test_num_agg = df.groupby(&quot;customer_ID&quot;)[num_features].agg([&#39;mean&#39;, &#39;std&#39;, &#39;min&#39;, &#39;max&#39;, &#39;last&#39;,&#39;median&#39;]) #grouping by customerID<br>test_num_agg.columns = [&#39;_&#39;.join(x) for x in test_num_agg.columns]</pre><ul><li><strong>Mean</strong>: the average value of a numerical variable, which can give a general sense of the central tendency of the data. The mean value can capture:</li></ul><ol><li><em>Mean bank balance the customer has.</em></li><li><em>Average customer spending.</em></li><li><em>The average time between two credit statements (time between credit payments).</em></li><li><em>The average risk of lending money.</em></li></ol><ul><li><strong>Standard deviation (Std)</strong>: a measure of the spread of the data around the mean, which can give insights into the degree of variability in the data. The high degree of variability in the balance suggests that a customer spends.</li><li><strong>Minimum and maximum value</strong> can capture the wealth of a customer and also captures information about customer spending and risk.</li><li><strong>Median: </strong>when the data is highly skewed using the mean is not a better idea and hence median value(middle value of numerical value can be used.</li><li><strong>Last values</strong> are perhaps the most important feature as was also suggested in our previous blog since they carry the information about the latest known credit statement issued to the customer.</li></ul><h3>One Hot encoding features</h3><p>Using the above statistical attributes for the categorical variables is not sensible since calculating minimum, maximum, or standard deviation doesn’t give us any useful information. So what we should do?</p><p>Well, we can use features like count, and the number of unique to calculate features, the last value which can be calculated using</p><pre>cat_features = [&quot;B_1&quot;,&quot;B_2&quot;,&quot;D_1&quot;,&quot;D_2&quot;,&quot;D_10&quot;,&quot;P_21&quot;,&quot;D_126&quot;,&quot;D_3&quot;,&quot;D_42&quot;,&quot;R_66&quot;,&quot;R_68&quot;]<br>test_cat_agg = df.groupby(&quot;customer_ID&quot;)[cat_features].agg([&#39;count&#39;, &#39;last&#39;, &#39;nunique&#39;])<br>test_cat_agg.columns = [&#39;_&#39;.join(x) for x in test_cat_agg.columns]</pre><p>However, this information doesn’t capture whether a customer was categorized in a particular category or not which can be of interest for modeling.</p><p>To capture this information, we do so by one-hot encoding the variables and then taking aggregations of the variables such as mean, sum, and last.</p><p>The <strong>mean value </strong>will capture the ratio of the total number of times a customer fall into the category/ total number of bank statements. The <strong>sum</strong> will simply be the total number of times a customer falls into the category.</p><pre>from cuml.preprocessing import OneHotEncoder<br>df_categorical = df_last[cat_features].astype(object)<br>ohe = OneHotEncoder(drop=&#39;first&#39;, sparse=False, dtype=np.float32, handle_unknown=&#39;ignore&#39;)<br>ohe.fit(df_categorical)with open(&quot;ohe.pickle&quot;, &#39;wb&#39;) as f: <br>    pickle.dump(ohe, f) #save the encoder so that it can be used for test data as well df_categorical = pd.DataFrame(ohe.transform(df_categorical).astype(np.float16),index=df_categorical.index).rename(columns=str)<br>df_categorical[&#39;customer_ID&#39;]=df[&#39;customer_ID&#39;]<br>df_categorical.groupby(&#39;customer_ID&#39;).agg([&#39;mean&#39;, &#39;sum&#39;, &#39;last&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*eyXaiBpwnpJKEYQz.png" /></figure><h3>Ranking-based features</h3><p>Ranking-based features can be a game-changer when it comes to predicting customer behavior. By ranking customers based on specific attributes like income or expenses, we can gain valuable insights into their financial habits and better manage risk.</p><p>With cudf ’ rank function, we can easily calculate these features and use them to inform our predictive models. For example, we could rank customers based on their spending patterns, debt-to-income ratio, or credit score. These features could then be used to predict the likelihood of default or identify customers who are at risk of falling behind on payments.</p><p>In addition, rank-based features can also be used to identify high-value customers, target marketing efforts, and optimize loan offers. For example, we could rank customers based on their likelihood to accept a loan offer, and then target those with the highest rank.</p><p>A simple code to calculate the rank is</p><pre>df[feat+&#39;_rank&#39;]=df[feat].rank(pct=True, method=&#39;min&#39;)</pre><p>where pct is used for whether to do percentile ranking. The ranks of a customer can also be calculated based on categorical features.</p><pre>df[feat+&#39;_rank&#39;]=df.groupby([cat_feat]).rank(pct=True, method=&#39;min&#39;)</pre><p>We will see one of the use cases of categorical-based ranking in time-based features.</p><p><strong>Combined/Composite Features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*yV5r7_SjooQqrIrA.png" /></figure><p>One popular method for combining features is linear or non-linear combinations. This involves taking two or more existing features and combining them in a way that creates a new, composite feature. This composite feature can then be used to identify patterns, trends, and correlations that might not be visible when looking at the individual features on their own.</p><p>For example, imagine that we’re analyzing a dataset of customer spending habits. We might start by looking at individual features like age, income, and location. But by combining these features in a linear or non-linear way, we can create new composite features that tell us even more about our customers. For instance, we might combine income and location to create a composite feature that tells us about the average spending of customers in a certain area.</p><p>Of course, it’s important to keep in mind that not all combinations of features will be equally useful. The key is to identify which combinations are most relevant to the problem we’re trying to solve. This requires a deep understanding of the data and the problem domain, as well as careful analysis of the correlations between the composite features we create and the target variable we’re trying to predict.</p><p>The below diagram presents how we should make a combination of features and use the information for our model. Only those features are selected whose correlation with the target is greater than the maximum of 0.9 and the maximum of correlations of features combined.</p><pre>features=[col for col in train.columns if col not in [&#39;customer_ID&#39;,target]+cat_features]<br>for feat1 in features:<br>  for feat2 in features:<br>    th=max(np.corr(feat1,Y)[0],np.corr(feat1,Y)[0]) #calculate threshold<br>    feat3=df[feat1]-df[feat2] #difference feature<br>    corr3=np.corr(feat3,Y)[0]<br>    if(corr3&gt;max(th,0.9)): #if correlation greater than max(th,0.9) we add it as feature<br>      df[feat1+&#39;_&#39;+feat2]=feat3</pre><h3>Time/Date-based features</h3><p>When it comes to data analysis, time-based features can be a game-changer. By grouping data based on time attributes like months or days of the week, we can create powerful features that reveal valuable insights about our data. These features can range from simple averages like income and spending to more complex attributes like credit score changes over time.</p><p>With time-based features, we can identify patterns and trends that might not be visible when looking at the data in isolation. And by combining these features, we can unlock even more powerful insights. Check out the diagram below to see how time-based features can be used to create useful composite attributes that help us better understand our data. The below diagram illustrates how we can create some useful features by using timestamps.</p><p>First, we calculate the mean of values over the month (we can use the day of the month or week of the month, etc.) merge the obtained data frame with the original data and take the difference between the respective features.</p><pre>features=[col for col in train.columns if col not in [&#39;customer_ID&#39;,target]+cat_features]<br>month_Agg=df.groupby([month])[features].agg(&#39;mean&#39;)#grouping based on month feature<br>month_Agg.columns = [&#39;_month_&#39;.join(x) for x in month_Agg.columns]<br>month_Agg.reset_index(inplace=True)<br>df=df.groupby(month_Agg,on=&#39;month&#39;)<br>for feat in features: #create composite features b taking difference<br>  df[feat+&#39;_&#39;+feat+&#39;_month_mean&#39;]=df[feat]-df[feat+&#39;_month_mean&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*lh2SRb9kFEy9HAB-.png" /></figure><p>We can also make rank-based features by using time as a grouping variable which is illustrated below</p><pre>features=[col for col in train.columns if col not in [&#39;customer_ID&#39;,target]+cat_features]<br>month_Agg=df.groupby([month])[features].rank(pct=True) #grouping based on month feature<br>month_Agg.columns = [&#39;_month_&#39;.join(x) for x in month_Agg.columns]<br>month_Agg.reset_index(inplace=True)<br>df=pd.concat([df,month_Agg],axis=1) #concat to original dataframe</pre><h3>Shift/Lag features</h3><p>Lag features are an essential tool for effective prediction in financial data. These features involve calculating the difference between a current value and a previous value in a time series. By incorporating lag features into our analysis, we can better understand the patterns and trends in our data and make more accurate predictions.</p><p>A lag feature captures the change in a customer’s payment behavior over time. By calculating the difference between a current payment and the previous payment, we can determine if the customer’s payment behavior is improving or deteriorating.</p><p>For example, if the lag feature shows that a customer has consistently paid their credit card bill on time for several months, we might predict that they are less likely to default in the future. Conversely, if the lag feature shows that a customer has been consistently late or missing payments, we might predict that they are more likely to default.</p><pre># difference function calculate the lag difference for numerical features <br>#between last value and shift last value.<br>def difference(groups,num_features,shift):<br>    data=(groups[num_features].nth(-1)-groups[num_features].nth(-1*shift)).rename(columns={f: f&quot;{f}_diff{shift}&quot; for f in num_features})<br>    return data</pre><pre>#calculate diff features for last -2nd last, last -3rd last, last- 4th last<br>def get_difference(data,num_features):<br>    print(&quot;diff features...&quot;)<br>    groups=data.groupby(&#39;customer_ID&#39;)<br>    df1=difference(groups,num_features,2).fillna(0)<br>    df2=difference(groups,num_features,3).fillna(0)<br>    df3=difference(groups,num_features,4).fillna(0)<br>    df1=pd.concat([df1,df2,df3],axis=1)<br>    df1.reset_index(inplace=True)<br>    df1.sort_values(by=&#39;customer_ID&#39;)<br>    del df2,df3<br>    gc.collect()<br>    return df1train_diff = get_difference(df, num_features)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*RRVWdNKRZk369DUg.png" /></figure><h3>Rolling window-based features</h3><p>These features are nothing but taking the mean of the last 3(4,5, … x) values depending on what works for our data since the latest values based on time carry the latest information on customer status.</p><pre>xth=3 #define the window size<br>df[&quot;cumulative&quot;]=df.groupby(&#39;customer_ID&#39;).sort_values(by=[&#39;time&#39;],ascending=False).cumcount()<br>last_info=df[df[&quot;cumulative&quot;]&lt;=xth]<br>last_info = last_info.groupby(&quot;customer_ID&quot;)[num_features].agg([&#39;mean&#39;, &#39;std&#39;, &#39;min&#39;, &#39;max&#39;, &#39;last&#39;,&#39;median&#39;]) #grouping by customerID<br>last_info.columns = [&#39;_&#39;.join(x) for x in last_info.columns]</pre><h3>Miscellaneous Features</h3><p>Till now we created enough features that serve the potential of building an awesome default detection model. However, many more features can be created depending on the nature of the data we have. For example,</p><p>We can create features like null counts that calculates the total null values present for a customer and hence helps in capturing feature distribution which tree-based algorithms are not capable of understanding.</p><pre>def calc_nan(df,features):<br>    print(&quot;calculating nan_info...&quot;)<br>    df_nan = (df[features].mul(0) + 1).fillna(0) #marke non_null values as 1 and null as zero<br>    df_nan[&#39;customer_ID&#39;] = df[&#39;customer_ID&#39;]<br>    nan_sum = df_nan.groupby(&quot;customer_ID&quot;).sum().sum(axis=1) #total unknown values for a customer<br>    nan_last = df_nan.groupby(&quot;customer_ID&quot;).last().sum(axis=1)#how many last values that are not known<br>    del df_nan<br>    gc.collect()<br>    return nan_sum,nan_last</pre><p>Instead of using mean, we can use modified mean values such as time-based weighted average or <a href="https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/hull-moving-average#:~:text=The%20Hull%20Moving%20Average%20(HMA,smoothing%20at%20the%20same%20time.">hull moving average</a> (HMA).</p><h3>Conclusion</h3><p>In this article, we’ve covered some of the most common handcrafted feature engineering strategies that are used in the real world to predict default risk. However, there are always new and innovative ways to engineer features, and we can even let our neural networks do the feature engineering work for us!</p><p>In the next part of this blog series, we will explore the exciting world of automatic feature engineering, where we will use cutting-edge techniques like Neural networks to let our models generate features on their own. So, stay tuned and keep an eye out for the next part of the blog series! Until then, happy feature engineering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ded4b63ff7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuenex/boost-the-model-performance-with-handcrafted-features-e1ded4b63ff7">Boost the Model Performance with Handcrafted Features</a> was originally published in <a href="https://medium.com/cuenex">CueNex</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Default Prediction — Practical Tips for Successful Execution]]></title>
            <link>https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8?source=rss-42fcadbfb718------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62a92ab5df8</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Priyanshu Chaudhary]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 15:47:17 GMT</pubDate>
            <atom:updated>2023-02-21T02:32:14.325Z</atom:updated>
            <content:encoded><![CDATA[<h4>MACHINE LEARNING</h4><h3>Credit Default Prediction — Practical Tips for Successful Execution</h3><h4>Improve existing prediction baselines with advanced ML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0ANo_2eyaGFAmmv_PLTJ8g.jpeg" /></figure><p>According to <a href="https://www.reuters.com/markets/us/us-consumer-loan-delinquencies-seen-surging-13-year-high-2023-study-2022-12-14/">TransUnion</a> credit card and personal loan data, delinquencies are expected to increase to levels not seen since 2010 in the United States.</p><p>TransUnion forecasted severe credit card delinquencies to rise to 2.6% at the end of 2023 from 2.1% at the close of 2022. Unsecured personal loan delinquency rates will increase to 4.3% from 4.1% in the same timeframe.</p><p>Therefore, credit default prediction has always been central to managing risk in a consumer lending business. Credit default prediction allows lenders to optimize lending decisions, and minimize risk and exposure, which leads to a better customer experience and sound business economics. By predicting which customers are at the highest risk of defaulting on their credit card accounts, issuers can take proactive steps to minimize risk and exposure.</p><h4><strong>Background</strong></h4><p>We implemented this solution for one of the largest payment card issuers in the world. We are sharing practical tips for the successful execution of credit default prediction. This is primarily aimed at machine learning teams and business transformation leaders across startups, and mid-sized to large corporations.</p><p>This article encapsulates our successful execution journey of predicting credit defaults, and we will share many innovative/out-of-the-box approaches that worked well during the end-to-end execution of this project. We believe the innovative solutions in this series will improve existing ML baselines for default predictions.</p><h4>Project Description</h4><p>The approach involves analyzing a dataset containing credit card transactions and payment records for a group of customers over a 12-month period from 2021–2022.</p><p>Specifically, the data includes customer information from their last 1–13 statements. The analysis focuses on various features that are associated with credit card defaults, with the goal of accurately predicting if a customer is likely to default in the next 6 months. By analyzing these features, the aim is to identify patterns and trends that can be used to assess the risk of a customer defaulting on their credit card payments.</p><h4><strong>Dataset description</strong></h4><p>The dataset depicted in this article is anonymized and masked to maintain the confidentiality of the customer data. The features can be classified as follows:</p><ul><li><strong>D_* = Delinquency variables</strong></li><li><strong>S_* = Spend variables</strong></li><li><strong>P_* = Payment variables</strong></li><li><strong>B_* = Balance variables</strong></li><li><strong>R_* = Risk variables</strong></li></ul><p>There are a total of 100<strong> integer features</strong> and 100<strong> floating-point features</strong> representing a customer’s status for the past 12 months. The dataset includes information on customer statements that can vary from 1 to 13. There can be a gap of 30 to 180 days between each credit card statement for a customer(i.e. credit card statements can be missing for the customer). Each customer is represented by a customer id. The sample data for the first 5 statements of the customer with customer_ID=0 is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*f3Lks5_solyaTdyOi4kIRA.png" /></figure><p>Of the 7 million customer_IDs, 98% have a label of &quot;0&quot; (good customer, no default), and 2% have a label of &quot;1&quot; (bad customer, default).</p><h4>Types of approach</h4><p>The data includes the monthly credit card statements of each customer and hence many approaches can be used that leverage the property of time series or using</p><ol><li>Decision Tree models/ Neural Networks using aggregated features of customer’s data.</li><li>Recurrent Neural Networks/Transformers with raw data of each customer’s data.</li></ol><h4>Feature Engineering</h4><p>We start by creating aggregated features for all the customers:<br>since the data contains categorical, numerical features. We process them separately.</p><p>Since we want to predict a binary value of whether a customer will default or not, we can create aggregating features such as:</p><ol><li><em>Average values for the last 13 statements</em></li><li><em>Last values of the features, i.e, the last status of the customer</em></li><li><em>The minimum value in the feature</em></li><li><em>The maximum value in the feature</em></li><li><em>For categorical variables, we can count the number of unique values</em></li></ol><p>For <strong>numerical features</strong>, we created aggregated features such as <em>mean, standard deviation, minimum, maximum, median, and last</em>, which can be calculated using the below code snippet.</p><pre>Num_feats  = df.groupby(&quot;customer_ID&quot;)[numerical_features].agg([&#39;mean&#39;, &#39;std&#39;, &#39;min&#39;, &#39;max&#39;, &#39;median&#39;, &#39;last&#39;])<br>Num_feats.columns = [&#39;_&#39;.join(x) for x in Num_feats.columns]</pre><p>For <strong>categorical features</strong>, we create count, last, and several unique categories for customer-based features.</p><pre>Cat_feats  = df.groupby(&quot;customer_ID&quot;)[categorical_features].agg([&#39;count&#39;,&#39;last&#39;,&#39;nunique&#39;])<br>Cat_feats.columns = [&#39;_&#39;.join(x) for x in Cat_feats.columns]</pre><p>The dataset includes null values; we fill them with a certain value <strong>(-128 in this case) or leave them as nan since boosting trees-based models are capable of accounting for nan values</strong>.</p><p>A sample of data after feature engineering looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*w6p0K4oEEP2xjSlMy70SFg.png" /></figure><h4>Evaluation Metric</h4><p>Because the classes are highly imbalanced, accuracy would not be an ideal metric for evaluating a decision tree classifier. The possible metrics that can be used are:</p><ol><li><strong>AUC-ROC</strong>: The Area Under the Receiver Operating Characteristic curve, which measures the model’s ability to distinguish between Positive and Negative classes</li><li><strong>Recall</strong>: The proportion of True Positives among all Actual Positive cases</li><li><strong>Normalized Gini coefficient</strong>: The Normalized Gini Coefficient is equal to 2*AUC-1 and is between -1 and 1</li><li><strong>The Default Rate Captured at the p% threshold:</strong> True Positive rate (Recall) for a threshold set at p% of the total (weighted) sample count</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*PQVHRxRBkoHJ9pQi0YdEJQ.png" /></figure><p>For the above figure, the red area represents the AUC-ROC score, and the intersection of the green line with the curve represents the default rate captured at p% (the higher the intersection, the better).</p><p>We evaluate our approach using the average of the normalized Gini coefficient and the default rate captured at 4%.</p><pre><br>def evaluation_metric(y_true, y_pred):<br>    labels     = np.transpose(np.array([y_true, y_pred]))<br>    labels     = labels[labels[:, 1].argsort()[::-1]]<br>    weights    = np.where(labels[:,0]==0, 20, 1) # 0 labels are weighted by 20 due to upsampling of customers with label 0<br>    cut_vals   = labels[np.cumsum(weights) &lt;= int(0.04 * np.sum(weights))]<br>    top_four   = np.sum(cut_vals[:,0]) / np.sum(labels[:,0]) #calculates default rate at 4%<br><br>    #calculation of gini=2*AUC-1<br>    gini = [0,0]<br>    for i in [1,0]:<br>        labels         = np.transpose(np.array([y_true, y_pred]))<br>        labels         = labels [labels[:, i].argsort()[::-1]]<br>        weight         = np.where(labels[:,0]==0, 20, 1)  #weighing labels<br>        weight_random  = np.cumsum(weight / np.sum(weight))<br>        total_pos      = np.sum(labels[:, 0] *  weight) <br>        cum_pos_found  = np.cumsum(labels[:, 0] * weight)<br>        Lorentz        = cum_pos_found / total_pos  <br>        gini[i]        = np.sum((Lorentz - weight_random) * weight)<br><br>    return 0.5 * (gini[1]/gini[0] + top_four)</pre><h4>Model Evaluation Strategy</h4><p>Since the data has an imbalanced distribution of classes, using stratified K-folds as a cross-validation strategy is a good choice when dealing with imbalanced datasets. By ensuring that each fold has a similar proportion of the positive class as the overall dataset, you can better evaluate the performance of your model on the minority class. A pictorial representation of stratified K- folds is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvjAUqYQ9LWmhiyjYL4kCQ.png" /></figure><h4>Baseline Model</h4><p>LightGBM (LGBM) is a good choice for classification tasks, especially when dealing with large datasets as it is found to have state-of-the-art results when dealing with tabular datasets.</p><p>LGBM uses gradient boosting to build an ensemble of decision trees that can capture complex interactions between features. A single tree of the LGBM after training on our dataset is shown below.</p><pre>features = [f for f in train.columns if f != &#39;customer_ID&#39; and f != &#39;target&#39;]<br><br>#for storing validation results.<br>score_list = []<br>y_pred_list = []<br><br>kf = StratifiedKFold(n_splits=5) # generating 5 stratified folds<br>target=train[&quot;target&quot;]<br>for fold, (trn_ind, test_ind) in enumerate(kf.split(train, target)):<br>    start_time = datetime.datetime.now()<br>    <br>    #creating data for training<br>    X_train = train.iloc[trn_ind][features]<br>    y_train = target[trn_ind]<br>  <br>    #creating data fro validation<br>    X_valid = train.iloc[test_ind][features]<br>    y_valid = target[test_ind]<br>    <br>    #define lgbm classifier with parameters<br>    model = LGBMClassifier(n_estimators=1000,<br>                          learning_rate=0.03, reg_lambda=50,<br>                          min_child_samples=2400,<br>                          num_leaves=95,<br>                          colsample_bytree=0.19,<br>                          max_bins=511, random_state=101 )<br><br>  #to remove the warning by LGBM classifier<br>    with warnings.catch_warnings():<br>        warnings.filterwarnings(&#39;ignore&#39;, category=UserWarning)<br>    <br>    model.fit(X_train, y_train,<br>                  eval_set = [(X_valid, y_valid)], <br>                  eval_metric=[evaluation_metric],<br>                  callbacks=[log_evaluation(100)])<br><br>    y_va_pred = model.predict_proba(X_va, raw_score=True)<br>    score = evaluation_metric(y_va, y_va_pred)<br><br>    #save model with best evaluation scores.<br>    n_trees = model.best_iteration_<br>    if n_trees is None: <br>        n_trees = model.n_estimators<br>    <br>    print(f&quot;Fold {fold} | {str(datetime.datetime.now() - start_time)[-12:-7]} |&quot;<br>          f&quot; {n_trees:5} trees |&quot;f&quot;                Score = {score:.5f}{Style.RESET_ALL}&quot;)<br>    <br>    score_list.append(score)<br>    <br>    if ONLY_FIRST_FOLD: break # for the training of first fold only<br>    <br>    #delete the training and validation data to save memory<br>    del X_train, y_train,X_valid, y_valid<br><br>print(f&quot;OOF Score:    {np.mean(score_list):.5f}{Style.RESET_ALL}&quot;)</pre><pre>469 features<br>[100]	valid_0&#39;s binary_logloss: 0.247296	valid_0&#39;s : 0.764518<br>[200]	valid_0&#39;s binary_logloss: 0.22843	valid_0&#39;s : 0.779298<br>[300]	valid_0&#39;s binary_logloss: 0.223237	valid_0&#39;s : 0.786733<br>[400]	valid_0&#39;s binary_logloss: 0.220893	valid_0&#39;s : 0.790104<br>[500]	valid_0&#39;s binary_logloss: 0.219559	valid_0&#39;s : 0.791775<br>[600]	valid_0&#39;s binary_logloss: 0.218766	valid_0&#39;s : 0.792098<br>[700]	valid_0&#39;s binary_logloss: 0.218199	valid_0&#39;s : 0.793434<br>[800]	valid_0&#39;s binary_logloss: 0.217769	valid_0&#39;s : 0.79412<br>[900]	valid_0&#39;s binary_logloss: 0.21744	valid_0&#39;s : 0.794347<br>[1000]	valid_0&#39;s binary_logloss: 0.217244	valid_0&#39;s : 0.794655<br>Fold 0 | 04:34 |  1000 trees |                Score = 0.794655</pre><p>Compared to a maximum score of 1, we receive a score of 0.794655 on our evaluation metric which is the average of AUC and default rate measured at 4% for fold 1 (training our model on 80% of the data and validating it on 20%).</p><p>We will create a bar chart that displays the 15 most significant features and their corresponding importance scores.</p><pre>import warnings<br>warnings.simplefilter(action=&#39;ignore&#39;, category=FutureWarning)<br>import plotly.express as px<br>def plotImp(model, X , num = 20, fig_size = (40, 20)):<br>    feature_imp = pd.DataFrame({&#39;Value&#39;:model.feature_importances_,&#39;Feature&#39;:X.columns})<br>    fig = px.bar(feature_imp.sort_values(by=&quot;Value&quot;,ascending=False)[0:num], x=&quot;Value&quot;, y=&quot;Feature&quot;, orientation=&#39;h&#39;,color=&#39;Feature&#39;)<br>    fig.show()<br>plotImp(model,train[features],15)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iifsoeln51XVJbDyfQ3hvg.jpeg" /></figure><p>This indicates that the last aggregated features are the most important features which represent the most recent statement status and are the strongest indicator of their default risk. In addition, the customer’s Balanced and Delinquency variables are the most important features for accurate default prediction.</p><p>LGBMClassifier in Python&#39;slightgbm package provides a plot_tree() method to plot a single decision tree from the learned ensemble of trees. This can be useful to visualize the internal workings of the model and understand how it&#39;s making predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*ExUmHSv-04Oq9oylXzmjUg.png" /></figure><p>Now we have the baseline model ready. In our next blog, we will be discussing more approaches in detail such as:</p><ol><li>Introducing more feature engineering techniques.</li><li>Leveraging the time series characteristic of the data and using it to train Transformers and Recurrent Neural Networks(such as GRUs).</li><li>Using a combination of Tree-based models along with Neural Networks.</li></ol><p>We look forward to sharing practical tips from this successful project which would provide a ready-reckoner guide for credit default prediction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62a92ab5df8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cuenex/credit-default-prediction-practical-tips-for-successful-execution-f62a92ab5df8">Credit Default Prediction — Practical Tips for Successful Execution</a> was originally published in <a href="https://medium.com/cuenex">CueNex</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>