<?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 Aleksandr Katsalap on Medium]]></title>
        <description><![CDATA[Stories by Aleksandr Katsalap on Medium]]></description>
        <link>https://medium.com/@kacalap1?source=rss-6821a3ba8f22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kndv3WI2qo-Q6WEGyLULJw.jpeg</url>
            <title>Stories by Aleksandr Katsalap on Medium</title>
            <link>https://medium.com/@kacalap1?source=rss-6821a3ba8f22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:17:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kacalap1/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[Binning techniques overview]]></title>
            <link>https://medium.com/@kacalap1/binning-techniques-overview-b858570e346f?source=rss-6821a3ba8f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/b858570e346f</guid>
            <category><![CDATA[weight-of-evidence]]></category>
            <category><![CDATA[binning]]></category>
            <category><![CDATA[information-value]]></category>
            <category><![CDATA[risk-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Aleksandr Katsalap]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 01:56:02 GMT</pubDate>
            <atom:updated>2025-02-21T02:12:33.891Z</atom:updated>
            <content:encoded><![CDATA[<p>Binning techniques remain one of the most underrated approaches either in feature engineering or machine learning models regularisation procedures. So let’s unveil this term and make a detailed breakdown of binning types and their applications.</p><p><strong>Binning</strong> (or discretization) transforms a feature’s values into discrete intervals or categories called “bins.” This transformation can be applied to:</p><ul><li><strong>Numerical data</strong> — turning continuous or numerical values into intervals</li><li><strong>Categorical data</strong> — grouping categories into bigger groups with multiple categories</li></ul><p>Let’s talk in more detail about binning types, approaches, their pros and cons.</p><h3>Numerical binning</h3><h4><strong><em>1. Equal-width binning</em></strong></h4><ul><li><strong>How it works</strong>: Divides the feature’s range into bins of equal size (width).</li><li><strong>When to use</strong>: <br>- Data is roughly uniform or you need a quick, simple discretization. <br>- You need a simple interpretation: each bin represents the same numeric interval. <br>- You need a fast and simple approach with results that are easy to interpret.</li><li><strong>When NOT to use</strong>: <br>- Data is skewed (many values in one range). Some bins might end up empty or too large.<br>- You need to catch some complex data distribution patterns.</li><li><strong>Example</strong>: Splitting customers’ age into 5 bins of equal width:</li></ul><pre># We want to split age into these ranges:<br># [0–20), [20–40), [40–60), [60–80), [80–100)<br><br>import pandas as pd<br><br>df = pd.DataFrame({&#39;Age&#39;: [23, 45, 67, 34, 89, 12, 9, 55]})<br>df[&#39;AgeBins&#39;] = pd.cut(df[&#39;Age&#39;], bins=5)  # 5 equal-width bins<br><br># Now df[&#39;AgeBins&#39;] has one of the values [0–20), [20–40), [40–60),<br># [60–80) or [80–100)</pre><h4>2. Equal-frequency binning (quantile binning)</h4><ul><li><strong>How it works</strong>: Ensures each bin has roughly the same number of observations (based on quantiles).</li><li><strong>When to use</strong>:<br>- Data is skewed, and you want to get balanced bins with more or less equal amounts of objects per bin.<br>- You want to avoid empty or tiny bins that plague equal-width when distribution is uneven.<br>- You need a fast and simple approach.</li><li><strong>When NOT to use</strong>:<br>- If you don’t want to get numerical ranges in bins too wide or too narrow.</li><li><strong>Example</strong>: Splitting customers’ age into 5 bins with equal number of objects in each bin:</li></ul><pre>df[&#39;AgeBins&#39;] = pd.qcut(df[&#39;Age&#39;], q=4, labels=[&#39;Q1&#39;,&#39;Q2&#39;,&#39;Q3&#39;,&#39;Q4&#39;])<br><br># Now df[&#39;AgeBins&#39;] has one of values &#39;Q1&#39;,&#39;Q2&#39;,&#39;Q3&#39; or &#39;Q4&#39;</pre><h4>3. K-Means Binning</h4><ul><li><strong>How it works</strong>: Uses K-Means clustering on a single numerical feature to find bin boundaries.</li><li><strong>When to use:<br>- </strong>You want to find natural groupings where objects are close to each other.</li><li><strong>When NOT to use</strong>:<br>- If you are not satisfied with stochastic results.<br>- As the method requires more computation time, you shouldn’t use it if you need a faster result.</li><li><strong>Example</strong>: Splitting customers’ age into 5 bins where objects are close to each other within one bin compare to objects in other bins:</li></ul><pre>from sklearn.cluster import KMeans<br>import numpy as np<br><br>data = np.array(df[&#39;Age&#39;]).reshape(-1, 1)<br>kmeans = KMeans(n_clusters=5, random_state=42)<br>df[&#39;AgeBins&#39;] = kmeans.fit_predict(data)<br><br># Now df[&#39;AgeBins&#39;] has one of cluster number from 1 to 5</pre><h4>4. Decision Tree Binning (target based)</h4><ul><li><strong>How it works</strong>: Trains a small decision tree (for ex., with up to 5 leafs if we need 5 “bins”) to find the best split points relative to the target.</li><li><strong>When to use</strong>:<br>- You want to get splits that relate to your target variable.<br>- Good in credit scoring, rule-based models, or anywhere interpretability matters — just visualize your tree.</li><li><strong>When NOT to use</strong>:<br>- You don’t want to care about tree overfitting and regularisation parameters to mitigate it.</li><li><strong>Example</strong>: Splitting customers’ age into 5 groups (leafs) based on target according to decision tree-specific functional like impurity or index Gini:</li></ul><pre>from sklearn.tree import DecisionTreeClassifier<br><br>tree = DecisionTreeClassifier(max_leaf_nodes=5)<br>tree.fit(df[[&#39;Age&#39;]], target)<br>df[&#39;AgeBins&#39;] = tree.apply(df[[&#39;Age&#39;]])</pre><h4>5. Optimal binning (target based)</h4><ul><li><strong>How it works</strong>: uses advanced optimization techniques like linear programming and mixed-integer linear programming with such a criterias as <strong>Weight of Evidence (WOE)</strong>, <strong>Information Value (IV)</strong> to find the best bin edges.</li><li><strong>When to use</strong>:<br>- You need more flexibility and more control over the binning process. Modern Python libraries like <a href="https://github.com/guillermo-navas-palencia/optbinning">optbinning</a> provide a large choice of parameters and settings to control binning process and allow users to visualize binning results out of the box.<br>- In credit scoring, risk modeling, or whenever you need statistically optimal bin edges.<br>- Minimizing information loss and handling outliers gracefully.</li><li><strong>When NOT to use</strong>:<br>- You need simpler or faster methods: method is really computationally heavy.<br>- Data amount is too small: not possible to calculate stable IV and WOE values.</li><li><strong>Example</strong>: Splitting customers’ age into bins in which customers will have a highest difference in mean target (assuming it is binary: 0 or 1) in terms of <strong>Information Value (IV) </strong>metric:</li></ul><pre>from optbinning import OptimalBinning<br><br># Create a binning class object<br>optb = OptimalBinning(name=&quot;Age&quot;, dtype=&quot;numerical&quot;, solver=&quot;cp&quot;)<br>optb.fit(df[&#39;Age&#39;], target)<br><br># Getting binning results as a text column with bins like:<br># [0–22), [22–43), [43–69), [69–80), [80, inf)<br>df[&#39;AgeBins&#39;] = optb.transform(df[&#39;Age&#39;])<br><br># For getting bins visualization:<br>optb.binning_table.plot(metric=&quot;woe&quot;)<br><br># For getting binning results table:<br>optb.binning_table.build()</pre><figure><img alt="Binning results visualization provided by optbinning Python package" src="https://cdn-images-1.medium.com/max/432/0*nWbNlQNvLL1eDGoA.png" /><figcaption>Binning results visualization provided by optbinning Python package</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*hIRfFe4ghAHy7J_7.png" /><figcaption>Table with binning results provided by optbinning Python package</figcaption></figure><h3>Categorical Binning</h3><p>Maybe the “binning” term sounds strange and shouldn’t be applied to categorical values: there are no the same entities like “borders for segments” or “ranges” that we want to calculate for numerical features. What we are going to call “categorical binning” is a procedure to group all possible values of categorical features into several groups so that each one will contain one or more categories. It’s easier to give a simple example than to explain:</p><p><strong><em>Example</em></strong>:</p><p>Given list of U.S. states:</p><p><strong>CA, NY, CO, WA, TX, FL, AZ, NV, OR, MN, MO, IL, MA, CT, AK, MS, AR, WV</strong></p><p>Using categorical binning we can categorize them:</p><p><strong>Group 1: [CA, NY, MA, CT, AK]<br>Group 2:[CO, WA, TX, FL, IL]<br>Group 3:[MS, AR, WV]<br>Group 4:[AZ, NV, OR, MN, MO]</strong></p><p>and we will call these groups “bins” while talking about categorical binning.</p><p>Now, let’s describe two main types of categorical binning</p><h4>1. Frequency<strong>-based binning (grouping rare categories into single one)</strong></h4><ul><li><strong>How it works</strong>: Merges categories with very few observations into the “Other” bin.</li><li><strong>When to use</strong>:<br>- Large number of categories with <strong>many rare ones.</strong><br>- Simplifies data, reduces risk of overfitting.</li><li><strong>When NOT to use</strong>:<br>- There are no rare categories, for example, your categorical feature has 5 values, and each of them has approx. equal frequency, say, 20%.<br>- Each category has meaningful differences.<br>- Over-grouping might lose important information and patterns.</li><li><strong>Example</strong>: Merge U.S. states with low frequency into “Other” group:</li></ul><pre>import pandas as pd<br><br>df = pd.DataFrame({&#39;State&#39;: <br>  [&#39;NY&#39;,&#39;NY&#39;,&#39;LA&#39;,<br>   &#39;TX&#39;,&#39;TX&#39;,&#39;TX&#39;,<br>   &#39;DC&#39;,&#39;DC&#39;,&#39;DC&#39;,<br>   &#39;DC&#39;, &#39;MS&#39;, &#39;AR&#39;<br>]})<br><br>threshold = 2<br>counts = df[&#39;State&#39;].value_counts()<br><br># Rare values will be labeled as &quot;rare&quot;<br>df[&#39;State_Bin&#39;] = df[&#39;State&#39;].apply(<br>  lambda x: x if counts[x] &gt; threshold else &#39;Other&#39;<br>)</pre><h4>2. Optimal Binning for categorical data (target based)</h4><ul><li><strong>How it works</strong>: just like numerical optimal binning, uses advanced optimization techniques like linear programming and mixed-integer linear programming with such a criterias as <strong>Weight of Evidence (WOE)</strong>, <strong>Information Value (IV)</strong> to find the best grouping categories based on target separation (WOE, IV, etc.). Other words, absolutely the same technique can be used for categorical values as it was described for numerical values.</li><li><strong>When to use</strong>:<br>- You need to find statistically optimal grouping of categories, this approach often used in credit scoring or risk models. Python package <a href="https://github.com/guillermo-navas-palencia/optbinning">optbinning</a> can be applied to bin categorical values just like it was described for numerical ones.<br>- Helps reduce dimensionality for high-cardinality categorical features.</li><li><strong>When NOT to use</strong>:<br>- You need simpler or faster methods: method is really computationally heavy.<br>- Data amount is too small: not possible to calculate stable IV and WOE values.</li><li><strong>Example: </strong>Group U.S. states so that resulted groups will have a highest difference in mean target (assuming it is binary: 0 or 1) in terms of <strong>Information Value (IV) </strong>metric:</li></ul><pre><br><br>from optbinning import OptimalBinning<br>import pandas as pd<br><br>df = pd.DataFrame({&#39;State&#39;: <br>  [&#39;CA&#39;, &#39;NY&#39;, &#39;MA&#39;, &#39;CT&#39;, &#39;AK&#39;,<br>   &#39;CO&#39;, &#39;WA&#39;, &#39;TX&#39;, &#39;FL&#39;, &#39;IL&#39;,<br>]})<br><br># Create a binning class object<br>optb_cat = OptimalBinning(name=&quot;State&quot;, dtype=&quot;categorical&quot;, solver=&quot;cp&quot;)<br>optb_cat.fit(df[&#39;State&#39;], df[&#39;Target&#39;])<br><br>df[&#39;State_Bin&#39;] = optb_cat.transform(df[&#39;State&#39;])<br><br># For getting bins visualization:<br>optb.binning_table.plot(metric=&quot;woe&quot;)<br><br># For getting binning results table:<br>optb.binning_table.build()</pre><p>Just like in case with numerical values, <a href="https://github.com/guillermo-navas-palencia/optbinning">optbinning</a> provides a visualization interface for binning results.</p><h3>How binning can improve machine learning modeling?</h3><p>When it comes to machine learning modeling, let’s emphasize how binning can help to improve models quality and simplify your modeling daily routines in general:</p><ol><li><strong>Detects non-linear patterns for linear models<br></strong>Linear or logistic regression<strong> </strong>models suppose a linear relationship between features and the target. Binning transforms a continuous feature into discrete intervals that will capture non-linearity.<strong> </strong>A good example here is when we develop credit risk model, we first of all use optimal binning for both numerical and categorical features using WOE criteria, and after that we apply WOE transformation, where each bin will be presented by its WOE value: these WOE values are passed to logistic regression model as a features (link?)</li><li><strong>Improve categorical features processing<br></strong>Of course, modern gradient boosting algorithms like CatBoost have internal mechanisms to process categorical features. Preliminary binning can improve this procedure and reduce training time. But keep in mind, that binning itself can increase time for a feature engineering stage.</li><li><strong>High cardinality problem addressing<br></strong>Binning (grouping) of categorical features merges rare categories or similar categories, reducing cardinality. This helps models that struggle with thousands of distinct categories (e.g., city names, product IDs). Fewer categories usually speeds up model training and reduces overfitting. You can think about binning here as a type of regularisation for machine learning models.</li><li><strong>Handles Outliers and Skewed Data<br></strong>Outliers can disproportionately affect models like linear regression. Binning puts outliers into boundary bins. For skewed data, quantile binning or K-Means binning can balance how data is grouped. So this is a type of regularisation for machine learning models as well.</li><li><strong>Improves interpretability<br></strong>Last but not least, bins like “Low Income,” “Medium Income,” “High Income” are much easier to explain to non-technical stakeholders than raw numerical ranges. Such bins can reflect domain knowledge, and this fact ensures the model uses intervals that make business sense and can highlight relevant thresholds.</li></ol><h3>Resources</h3><ol><li>Optbinning GiHub <a href="https://github.com/guillermo-navas-palencia/optbinning">repo</a></li><li>Medium <a href="https://medium.com/@makhija.amit/mastering-optimal-binning-with-optbinning-a-comprehensive-guide-c6cf52572d64">post</a> about optbinning Python package usage guide</li><li>Deep dive into WOE <a href="https://community.altair.com/discussion/34012/weight-of-evidence-a-universal-modeling-gem">post</a></li><li>Example of manual binning in credit risk modeling on <a href="https://www.kaggle.com/code/chandrimad31/credit-risk-part-1-binning-woe-iv-pd-model">Kaggle</a></li><li>Advanced WOE and binning algorithms <a href="https://arxiv.org/pdf/2101.01494">paper</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b858570e346f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom transformers for Scikit-Learn Pipelines]]></title>
            <link>https://medium.com/@kacalap1/custom-transformers-for-scikit-learn-pipelines-776095db9074?source=rss-6821a3ba8f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/776095db9074</guid>
            <category><![CDATA[catboost]]></category>
            <category><![CDATA[sklearn-pipeline]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Aleksandr Katsalap]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 18:09:30 GMT</pubDate>
            <atom:updated>2024-06-02T18:18:17.900Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I think that<a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html"> Scikit-Learn pipelines</a> power still being underrated today as I see its usage pretty rarely in ML projects that I faced with for the last years. I’m not talking about some toy examples that include 2–3 steps from Scikit-Learn lib like “OneHotEncoder + PCA + LogisticRegression”. That’s why I decided to share my collection of custom Scikit-Learn transformers that I created during the last years and actively use in commercial ML projects.</blockquote><h4>General principles of how do Scikit-Learn transformers work</h4><p>In the beginning of this <a href="https://medium.com/ai-made-simple/pipelines-in-scikit-learn-46c61c5c60b2">article</a> by <a href="https://medium.com/@roiyeho">Dr. Roi Yehoshua </a>(paywalled) I found one of the best explanation of how do Scikit-Learn pipeline components work on a training and inference modes. Here is the illustration provided by its author:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*VBLO6RjE1HWgcE5m" /></figure><p>So we have a series of data transformations with one predictor in the end. This chain can work in 2 modes: <strong>fit</strong> and t<strong>ransform/predict</strong>:</p><p><strong>Fit</strong>: train stage:</p><ul><li>Data transformers call <strong>fit</strong> method to learn/fit their internal structure. For example, PCA transformer calculates principal components axes in initial feature space. Next, they call the <strong>transform </strong>method to immediately apply the transformation they’ve just learned to pass transformed data to the next stage of the pipeline.</li><li>Model transformer calls its regular <strong>fit</strong> method to fit ML model. For example, fit method of LogisticRegression estimator</li></ul><p><strong>Transform/Predict</strong>: inference stage:</p><ul><li>Data transformers call <strong>transform</strong> method only to apply transformation they’ve learned on train stage</li><li>Model transformer calls its regular <strong>predict</strong> method to fit ML model. For example, fit method of LogisticRegression estimator.</li></ul><p>During pipeline <strong>fit</strong> mode every data transformer calls <strong>fit</strong> that <strong>transform</strong> methods. As you can see on the picture, their calls are combined into a single <strong>fit</strong>_<strong>transform</strong> method. This is possible due to <strong>TransformerMixin</strong> class, that is a must part of all transformers to make them compatible with sklearn.Pipeline class, so you have to inherit from it when writing your custom transformer.</p><h3>Custom Scikit-Learn transformers</h3><p>As one mentioned above, Scikit-Learn transformers can be divided into two groups: data transformers and model transformers. For each of these groups you can create your own transformer according to your needs. Note, that some examples below lean on other custom libs: <a href="https://feature-engine.trainindata.com/en/latest/"><strong>Feature engine</strong></a> (that provides various sklearn-compatible transformers as well!) and <a href="https://gnpalencia.org/optbinning/"><strong>Optbinning</strong></a><strong>.</strong></p><p>All the code below is available on <a href="https://github.com/Alexkats87/sklearn-custom-pipelines/tree/main"><strong>GitHub</strong></a></p><h4>Data transformers: features generators and eliminators</h4><p>For data transformers, let’s start from the feature genegators and feature selectors/eliminators. The idea is simple: generate features and then drop obviously useless ones.</p><p><strong>FeatureEliminationTransformer</strong></p><pre>class FeatureEliminationTransformer(BaseEstimator, TransformerMixin):<br>    &quot;&quot;&quot;<br>    Dropping:<br>        - Duplicated features<br>        - Constant and quasi constant<br>        <br>    Input features detected by regex, for ex.:<br>     - fr&quot;^({NUM}|{CAT})\w+&quot;  -  to filter features that start &quot;num__&quot; and &quot;cat__&quot;<br>     - fr&quot;\w+__bin__woe$&quot;  -   to filter features that end with &quot;__bin&quot;<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, features_pattern=fr&quot;^({NUM}|{CAT})\w+&quot;, constant_share_thr=0.98):<br><br>        self.constant_share_thr = constant_share_thr<br>        self.features_pattern = re.compile(features_pattern)<br>        self.features_to_drop = set()<br><br>    def fit(self, X, y):<br>        <br>        self.features_set = set(<br>            filter(<br>                lambda x: re.match(<br>                    self.features_pattern, x<br>                    ), X.columns<br>            <br>                )<br>            )<br>            <br>        logger.info(f&quot;Feature elimination - initial features count:      {len(self.features_set)}&quot;)<br><br>        # 1. Drop duplicated features<br>        self.selector_dup = DropDuplicateFeatures(variables=list(self.features_set))<br>        self.selector_dup.fit(X)<br>        self.features_set = self.features_set - set(self.selector_dup.features_to_drop_)<br>        logger.info(f&quot;Feature elimination - after dups dropping:         {len(self.features_set)}&quot;)<br>        <br>        # 2. Drop quazi-constant features       <br>        self.selector_const = DropConstantFeatures(variables=list(self.features_set), tol=self.constant_share_thr)<br>        self.selector_const.fit(X)<br>        self.features_set = self.features_set - set(self.selector_const.features_to_drop_)<br>        <br>        logger.info(f&quot;Feature elimination - after constants dropping:     {len(self.features_set)}&quot;)<br>        logger.info(f&quot;Feature elimination - fit done.&quot;)<br>        <br>        return self<br><br>    def transform(self, X, y=None):<br><br>        features_set = set(<br>            filter(<br>                lambda x: re.match(<br>                    self.features_pattern, x<br>                    ), X.columns<br>                )<br>            )<br><br>        X = X.drop(list(features_set - self.features_set), axis=1)<br><br>        logger.info(f&quot;Feature elimination - transform done.&quot;)<br>        <br>        if y is not None:<br>            return pd.concat([X, y], axis=1)<br>        else:<br>            return X</pre><p>This transformer removes duplicated features and constant (generally speaking, quasi constant) ones. On the train stage, inside the fit method it memorizes features that should be excluded from dataset as they are constant ones or duplicate some other features. During inference stage it just removes features it “learned” using transform method. You also can set up a pattern to let the transformer know what is your features set- in the example it will look only at columns whose names start with <strong>cat__</strong> or <strong>num__</strong> prefixes. But you can use any pattern you like.</p><p><strong>DecorrelationTransformer</strong></p><pre>class DecorrelationTransformer(BaseEstimator, TransformerMixin):<br>    &quot;&quot;&quot;<br>    Detection and removing correlated features:<br>        - Detect groups of correlated features<br>        - From every group only one feature is selected based on mean target performance.<br>          Other features will be dropped<br>          <br>    Input features detected by regex, for ex.:<br>     - fr&quot;^({NUM}|{CAT})\w+&quot;  -  to filter features that start &quot;num__&quot; and &quot;cat__&quot;<br>     - fr&quot;\w+__bin$&quot;  -   to filter features that end with &quot;__bin&quot;<br>    <br>    &quot;&quot;&quot;<br>    <br>    def __init__(<br>        self, <br>        correlation_thr=0.8, <br>        corr_features_selector_bins=5, <br>        corr_features_selector_strategy=&#39;equal_width&#39;,<br>        features_pattern = fr&quot;\w+{BIN}{WOE}$&quot;<br>    ):<br>        self.correlation_thr = correlation_thr<br>        self.corr_features_selector_bins = corr_features_selector_bins<br>        self.corr_features_selector_strategy = corr_features_selector_strategy<br>        self.features_pattern = re.compile(features_pattern)<br>        self.features_to_drop = set()<br><br>    def fit(self, X, y):<br><br>        self.features_set = set(<br>            filter(<br>                lambda x: re.match(self.features_pattern, x), X.columns<br>            )<br>        )<br>        <br>        if len(self.features_set) &lt;=0:<br>            raise ValueError(&quot;Feature decorrelation - input features set is empty&quot;)<br>        <br>        logger.info(f&quot;Feature decorrelation - initial features count:      {len(self.features_set)}.&quot;)<br><br>        # Detect groups of corr features<br>        self.selector_corr = DropCorrelatedFeatures(variables=list(self.features_set), threshold=self.correlation_thr)   <br>        self.selector_corr.fit(X)<br>        correlated_feature_sets = self.selector_corr.correlated_feature_sets_<br>        logger.info(f&quot;Feature decorrelation - groups of corr features:      {len(correlated_feature_sets)}&quot;)<br><br>        # Select best features from groups of corr. features<br>        for feature_set in correlated_feature_sets:<br>            <br>            feature_lst = list(feature_set)<br><br>            logger.debug(f&quot;Group size:  {len(feature_lst)}&quot;)<br>            logger.debug(f&quot;Features:    {feature_lst}&quot;)<br>            <br>            mean_target_selector = SelectByTargetMeanPerformance(<br>                bins=self.corr_features_selector_bins, <br>                strategy=self.corr_features_selector_strategy<br>            )<br>            mean_target_selector.fit(X[feature_lst], y)<br>            <br>            feature_best = max(<br>                mean_target_selector.feature_performance_, <br>                key=lambda k: mean_target_selector.feature_performance_[k]<br>            )<br>            <br>            feature_lst.remove(feature_best)          <br><br>            logger.debug(f&quot;Best:        {feature_best}&quot;)<br>            <br>            self.features_set = self.features_set - set(feature_lst)<br><br>        logger.info(f&quot;Feature decorrelation - features count after:      {len(self.features_set)}.&quot;)<br>        logger.info(f&quot;Feature decorrelation - fit done.&quot;)<br>        return self</pre><p>The transformer detects and removes correlated features using the following logic:</p><ul><li>Detects groups of correlated features</li><li>From every group only one feature is selected based on mean target performance. Other features from the group will be dropped.</li></ul><p>If you have a massive dataset or a lot of features that were generated on previous stages, it’s better to filter out highly correlated features, even if your model is not a linear one. It will reduce a load (CPU and memory consumption) during next pipeline steps. Modifying this class you can set up a correlation coefficient threshold (or it can be optimized as a hyperparameter) or implement your own decorrelation method.</p><h4>Data transformers: encoders</h4><p>Encoders not just drop or add some columns/features, they apply some kind of transformations to columns in dataset.</p><p><strong>WoeEncoderTransformer</strong></p><pre>class WoeEncoderTransformer(BaseEstimator, TransformerMixin):<br>    &quot;&quot;&quot;<br>    Transforming categirical features/bins into weight of evidence (WOE)<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, zero_filler=0.01):<br>        self.zero_filler = zero_filler<br>        self.worst_bins_dct = {}<br>        self.fitting = False<br>        <br>    def _to_str(self, df):<br>        df[self.features_lst] = df[self.features_lst].astype(str)<br>        return df<br><br>    def fit(self, X, y):<br>        <br>        self.fitting = True<br><br>        self.features_lst = list(<br>            filter(<br>                lambda x: re.match(f&quot;.*{BIN}$&quot;, x), X.columns<br>            )<br>        )<br>        X = self._to_str(X)<br><br>        self.woe_encoder = WoEEncoder(<br>            variables=self.features_lst<br>        ).fit(<br>            X[self.features_lst],<br>            y<br>        )<br>        <br>        # Get the worst bin for every feature: highest WOE corresponds to worst bin<br>        # We fill features without bins by the worst bin during inference<br>        for f in self.features_lst:         <br>            self.worst_bins_dct[f] = max(<br>                self.woe_encoder.encoder_dict_[f],<br>                key=lambda k: self.woe_encoder.encoder_dict_[f][k]<br>            )<br>        <br>        logger.info(f&quot;WOE cat encoder - fit done.&quot;)<br>        <br>        return self<br><br>    def transform(self, X, y=None):<br>        <br>        X = X.copy()<br>        X = self._to_str(X)<br>        <br>        if not self.fitting:<br>            <br>            X_tmp = X[self.features_lst].copy()<br>            features_with_missings = (X_tmp[X_tmp!=&#39;nan&#39;]).isnull().sum()<br>            features_with_missings = features_with_missings[features_with_missings &gt; 0]<br>            <br>            for f in features_with_missings.index:<br>                X.loc[X[f] == &#39;nan&#39;, f] = self.worst_bins_dct[f]<br>                <br>        self.fitting = False<br>        <br>        X_orig = X[self.features_lst].copy()<br>        <br>        X = self.woe_encoder.transform(X[self.features_lst])<br>        X = X.rename(<br>            columns={c: c + WOE for c in self.features_lst}<br>        )<br>        <br>        X = pd.concat([X, X_orig], axis=1)<br><br>        logger.info(f&quot;WOE cat encoder - transform done.&quot;)<br>                <br>        if y is not None:<br>            return pd.concat([X, y], axis=1)<br>        else:<br>            return X</pre><p><a href="https://www.analyticsvidhya.com/blog/2021/06/understand-weight-of-evidence-and-information-value/">Weight of evidence</a> (WOE) encoder implements categorical features target encoding. In general it’s a wrapper for <a href="https://feature-engine.trainindata.com/en/latest/user_guide/encoding/WoEEncoder.html">Feature-engine WOE encoder</a> but with extra functionality that fill missing values by WOE that corresponds to the <strong>worst category during inference stage</strong>. It can be important for credit risk models, for example.</p><p><strong>BinningTransformers (</strong><a href="https://github.com/Alexkats87/sklearn-custom-pipelines/blob/d5135b604ba5b51b46e1673780cde7f8c3bfedba/transformers/encoders.py#L231"><strong>numerical</strong></a><strong> &amp; </strong><a href="https://github.com/Alexkats87/sklearn-custom-pipelines/blob/d5135b604ba5b51b46e1673780cde7f8c3bfedba/transformers/encoders.py#L176"><strong>categorical</strong></a><strong>)</strong></p><p>Provides a discretisation transformation for numerical features. Yet another type of target encoding. Uses <a href="https://gnpalencia.org/optbinning/">optbinning</a> under the hood. On a training stage it determines a borders for numerical features that split feature range into segments with different mean target values within.You can set up a lot of constraints here: bins amount, mean target minimal difference and other to pass them into HPO task. Similar transformer for categorical features is available as well.</p><h4>Model transformers</h4><p>Are the last steps in pipeline.</p><p><strong>CustomLogisticRegressionClassifier</strong></p><pre>class CustomLogisticRegressionClassifier(BaseEstimator, ClassifierMixin):<br>    <br>    &quot;&quot;&quot;<br>    Fit LogReg model (statsmodels), perform iterative feature selection<br>    excluding features with high p-values after every model fit<br>    <br>    Input features detected by regex, for ex.:<br>     - fr&quot;^({NUM}|{CAT})\w+&quot;  -  to filter features that start &quot;num__&quot; and &quot;cat__&quot;<br>     - fr&quot;\w+__bin$&quot;  -   to filter features that end with &quot;__bin&quot;<br>    &quot;&quot;&quot;<br>    <br>    p_value_max = 0.05<br><br>    def __init__(self, features_pattern=fr&quot;\w+{BIN}{WOE}$&quot;, features_lst=None): <br>        self.estimator = None  <br>        self.features_lst = features_lst<br>        self.features_pattern = re.compile(features_pattern)<br><br>    def fit(self, X, y):<br>        <br>        if self.features_lst:<br>            <br>            logger.info(f&quot;Modeling: LogisticRegression with fixed set of features.&quot;)<br>            <br>            self.estimator = sm.Logit(<br>                y, <br>                sm.add_constant(X[self.features_lst])<br>            ).fit(disp=0)<br><br>        else:<br>            <br>            logger.info(f&quot;Modeling: LogisticRegression with feature selection.&quot;)<br>            <br>            self.features_lst = list(<br>                filter(<br>                    lambda x: re.match(self.features_pattern, x), X.columns<br>                )<br>            )<br><br>            iter = 1<br>            while True:<br><br>                model = sm.Logit(<br>                    y,<br>                    sm.add_constant(X[self.features_lst])<br>                ).fit(disp=0)    <br>                <br>                model_stats = model.summary2().tables[1]<br>                <br>                worst = model_stats[&#39;P&gt;|z|&#39;].idxmax()<br>                worst_p = model_stats.loc[worst][&#39;P&gt;|z|&#39;]<br>                <br>                if worst_p &gt; self.p_value_max:<br>                    <br>                    model_stats = model_stats.drop(worst)<br>                    self.features_lst.remove(worst)<br>                <br>                    logger.debug(f&quot;==========================&quot;)<br>                    logger.debug(f&quot;Features cnt: {len(self.features_lst)}&quot;)<br>                    logger.debug(f&quot;Iter. {iter}, dropped:      {worst}&quot;)<br>                    logger.debug(f&quot;P-value:      {worst_p:0.4}&quot;)<br>                    <br>                else:<br>                    break<br>                <br>                iter += 1<br><br>        logger.info(f&quot;Modeling: LogisticRegression - features amount:{len(self.features_lst)}&quot;)<br>        logger.info(f&quot;Modeling: LogisticRegression - fit done.&quot;)<br>        logger.debug(model_stats)<br>        <br>        self.estimator = model<br>        return self<br><br>    def predict(self, X):<br>         <br>        prediction = self.estimator.predict(<br>            sm.add_constant(X[self.features_lst], has_constant=&#39;add&#39;)<br>        )<br>        <br>        logger.info(f&quot;Modeling: LogisticRegression - prediction done.&quot;)<br>        <br>        return prediction</pre><p>Implement <strong>Logistic Regression classifier </strong>from <a href="https://www.statsmodels.org/stable/index.html">statsmodels</a> that iteratively excludes features after every model fit until all features will have a p-value less than 0.05. You can implement your own feature elimination algorithm or pass the p-value threshold into HPO job. So, it allows to optimize not only a features set itself but also a way of how they will be selected using HPO.</p><p><strong>CustomCatBoostClassifier</strong></p><pre>class CustomCatBoostClassifier(BaseEstimator, ClassifierMixin):<br>    &quot;&quot;&quot;    <br>    Fit CatBoostClassifier model, perform iterative feature selection<br>    excluding features with low feature importance after every model fit.<br>    <br>    Uses evaluation set for early stopping.<br>    <br>    Input features detected by prefixes: <br>    - &quot;num__&quot; for numerical<br>    - &quot;cat__&quot; for categorical<br>    <br>    &quot;&quot;&quot;<br> <br>    importance_min = 0.01<br><br>    def __init__(self, **params):<br>        <br>        self.params = params<br>        self.estimator = CatBoostClassifier(**self.params)<br>            <br>        self.cat_features_set = None<br>        self.num_features_set = None<br><br>    def set_params(self, **params):<br>        for param, value in params.items():<br>            setattr(self.estimator, param, value)<br>        return self<br><br>    def fit(self, X, y, **params):<br><br>        self.cat_features_set = set(filter(lambda x: re.match(fr&quot;^({CAT})&quot;, x), X.columns))<br>        self.num_features_set = set(filter(lambda x: re.match(fr&quot;^({NUM})&quot;, x), X.columns))<br><br>        logger.info(f&quot;Modeling: Catboost - Initial features amount: {len(self.cat_features_set | self.num_features_set)}&quot;)<br><br>        iter = 1<br>        while True:<br>            <br>            self.estimator.fit(<br>                X=X[list(self.cat_features_set | self.num_features_set)],<br>                y=y,<br>                cat_features=list(self.cat_features_set),<br>                eval_set=(<br>                    params[&#39;eval_set&#39;][0][list(self.cat_features_set | self.num_features_set)],<br>                    params[&#39;eval_set&#39;][1]<br>                ),<br>                verbose=0,<br>            )<br>            <br>            importance_dct = dict(zip(<br>                self.estimator.feature_names_, <br>                self.estimator.get_feature_importance()<br>            ))<br>            <br>            features_to_drop_set = set([key for key, value in importance_dct.items() if value &lt;= self.importance_min])<br>            <br>            if not features_to_drop_set:           <br>                logger.info(f&quot;Modeling: Catboost - Selected features amount: {len(self.cat_features_set | self.num_features_set)}&quot;)               <br>                break<br>            else:<br>                self.cat_features_set = self.cat_features_set - set(features_to_drop_set)<br>                self.num_features_set = self.num_features_set - set(features_to_drop_set)<br>                logger.debug(f&quot;==========================&quot;)<br>                logger.debug(f&quot;Iter. {iter}, dropped features amt: {len(features_to_drop_set)}&quot;)<br><br>            iter += 1<br><br>        iterations_count = self.estimator.get_best_iteration() + 1<br>        logger.debug(f&quot;Iterations_count: {iterations_count}&quot;)<br>        <br>        self.estimator.fit(<br>            X=X[list(self.cat_features_set | self.num_features_set)],<br>            y=y,<br>            cat_features=list(self.cat_features_set),<br>            eval_set=(<br>                params[&#39;eval_set&#39;][0][list(self.cat_features_set | self.num_features_set)],<br>                params[&#39;eval_set&#39;][1]<br>            ),<br>            verbose=0,<br>        )<br><br>        logger.info(f&quot;Modeling: Catboost - fit done.&quot;)<br><br>        return self<br><br>    def predict(self, X):<br>        <br>        prediction = self.estimator.predict_proba(X[list(self.cat_features_set | self.num_features_set)])<br>        logger.info(f&quot;Modeling: Catboost - prediction done.&quot;)<br>        <br>        return prediction</pre><p>Runs a <strong>CatBoostClassifier</strong> iteratively excluding features with low importance. Note, that you can pass catboost parameters directly into a class constructor together with all other, “custom” parameters. It’s possible due to <strong>set_params </strong>method, inherited with the <strong>TransformerMixin</strong> class. It provides an interface to configure native CatBoostClassifier parameters. The second thing I would like to pay your attention to, is that we have to identify categorical features somehow as they should be specified as a parameter of CatBoostClassifier. To ensure that you can do that, you can use a name pattern like <strong>cat__</strong> prefix for them.</p><h3>Pipeline example</h3><p>Here is the example from a real ML project:</p><pre>model_ppl = Pipeline(steps=[<br>    (&quot;simple_features_tr&quot;, SimpleFeaturesTransformer(num_features_missings, cat_features_missings)),<br>    (&quot;feature_elimination_tr&quot;, FeatureEliminationTransformer()),<br>    (&quot;rare_encoder_tr&quot;, RareCategoriesTransformer()),<br>    (&quot;binning_num_tr&quot;, BinningNumericalTransformer()),<br>    (&quot;binning_cat_tr&quot;, BinningCategoriesTransformer()),<br>    (&quot;woe_tr&quot;, WoeEncoderTransformer()),<br>    (&quot;feature_elimination_tr2&quot;, FeatureEliminationTransformer(features_pattern=fr&quot;\w+{BIN}{WOE}$&quot;)),<br>    (&quot;decorr_tr&quot;, DecorrelationTransformer()),<br>    (&quot;model_tr&quot;, CustomLogisticRegressionClassifier()),<br><br>])<br><br># Fit pipeline<br>model_ppl.fit(X_train, y_train)<br>  <br># Make prediction<br>y_train_pred = model_ppl.predict(X_train)<br>y_test_pred = model_ppl.predict(X_test)<br><br>print(f&quot;ROC_AUC train: {roc_auc_score(y_train, y_train_pred)}&quot;)<br>print(f&quot;ROC_AUC test: {roc_auc_score(y_test, y_test_pred)}&quot;)<br><br># Save pipeline with model<br>with open(os.path.join(&quot;model_logreg.joblib&quot;), &#39;wb&#39;) as f:<br>    joblib.dump(model_ppl, f)</pre><p>Let me describe what’s going on at every stage of it:</p><ul><li><strong>FeatureEliminationTransformer</strong> — removes duplicated and constant features to reduce resources consumption at the upcoming stages</li><li><strong>RareCategoriesTransformer</strong> — merges rare values of categorical feature into a single value “OTHER” to reduce cardinality</li><li><strong>BinningNumericalTransformer &amp; BinningCategoriesTransformer </strong>— discretization for both types of features. Note, that this step comes after “RareCategoriesTransformer”</li><li><strong>WoeEncoderTransformer</strong> — implements WOE encoding. After the discretization stage all our features are already categorical, so here we can apply this transformation to all of them.</li><li><strong>FeatureEliminationTransformer</strong> — yes, we apply this transformation again, because after discretization with WOE we can end up with extra constant/duplicated features. For example, some feature is not too informative to predict our target, and due to this reason the discretization stage will put all its values into a single range/bin, then WOE transformation will convert it into a single float value.</li><li><strong>DecorrelationTransformer</strong> — final transformation step before LogisticRegressionClassifier to ensure that we will not get a singular matrix on a modeling stage</li><li><strong>CustomLogisticRegressionClassifier</strong> — modeling stage with stepwise feature elimination</li></ul><h3>Resources</h3><ol><li><strong>Pipelines in scikit-learn</strong> — <a href="https://medium.com/ai-made-simple/pipelines-in-scikit-learn-46c61c5c60b2">https://medium.com/ai-made-simple/pipelines-in-scikit-learn-46c61c5c60b2</a></li><li><strong>Feature-engine lib</strong> — <a href="https://feature-engine.trainindata.com/en/latest/index.html">https://feature-engine.trainindata.com/en/latest/index.html</a></li><li><strong>Optimal binning lib </strong>— <a href="https://gnpalencia.org/optbinning/">https://gnpalencia.org/optbinning/</a></li><li><a href="https://github.com/Alexkats87/sklearn-custom-pipelines/tree/main"><strong>Github</strong> <strong>repo</strong></a> with code examples from this article</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=776095db9074" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-value segments detection approaches in data analysis]]></title>
            <link>https://medium.com/@kacalap1/high-value-segments-detection-approaches-in-data-analysis-96f03266abd0?source=rss-6821a3ba8f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/96f03266abd0</guid>
            <dc:creator><![CDATA[Aleksandr Katsalap]]></dc:creator>
            <pubDate>Sun, 05 May 2024 17:20:21 GMT</pubDate>
            <atom:updated>2024-05-05T17:23:21.716Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In the context of binary classification tasks, a small group of objects with a very high mean target value is often called a <strong>“high-value cluster”</strong> or <strong>“high-value segment.” </strong>These are subsets of the dataset that have a strong positive correlation with the target variable, indicating that the objects within these clusters are more likely to belong to the positive class. Other words, within these groups mean target value is much higher than the overall one. Identifying and analyzing these high-value clusters can be crucial for understanding the factors that contribute to positive outcomes or high target values in the dataset.</blockquote><h3>High-value segments in business cases</h3><p>In bank credit scoring risk and business analysts usually want to <strong>manually</strong> add some extensions to a scoring model, that is a part of a decision making system, based on some policies or patterns they discovered during a data analysis. For example, they don’t want to disburse loans to some groups of applicants, who are from specific regions and/or younger than some age or/and have more than 3 past due loans for the last year. In our context these groups are nothing more than “<strong>high-value segments”</strong>. And rules are usually called <strong>“rejection rules” </strong>in the financial industry. So, according to examples above, rejection rules can be described as:</p><ul><li><strong>salary &lt; N</strong></li><li><strong>fraud score &gt; N AND age &lt; M</strong></li><li><strong>Past due amount last year &gt; N OR Jobless flag = True</strong></li></ul><p>A good rejection rules usually have the <strong>following requirements:</strong></p><ul><li>Rejection rule should detect a small group of applicants who have a very default rate (percent of applicants who have past due loans) within it. Group size and default rate within a group are defined by risk and business analysts. Example: group size 1–2% of population and default rate within a group &gt; 60%</li><li>Rejection rule applies before scoring models.</li><li>Rejection rule shouldn’t consist of more than 2–3 factors (variables) to ensure, that they are simple enough to be human readable and understandable</li><li>Applicants segment defined by a good rejection rule is stable in time, for example default rate is high and group size is constant from month to month</li><li>Factor are used in rejection rules should not be included in scoring models</li><li>This concept can be also applied in an opposite sense: we try to find a group of a very good applicants to approve their applications without scoring models</li></ul><h3>Why don’t we just use ML models?</h3><p>Why just don’t include factors these rules consist of into our scoring models? The are few reasons:</p><ul><li><strong>Business reason. </strong>If our scoring ML model is complex and contains dozens or hundreds of features, factors that are a base for rejection rules can be mitigated by other features with higher importance. It leads to approvement a set of applications that shouldn’t be approved according to business requirements</li><li><strong>Technical reason. </strong>Small size of a groups we are looking for is too small to make feature based on variables. For example, if we fit a tree-based algorithm, it will try to split our sample into 2 groups of more or less equal sizes because the entropy split criterion includes group sizes.</li></ul><h3>Classical high-value segments detection algorithm: decision trees</h3><p>One of the most popular ways is to fit a decision tree classifier, where features are 1–3 variables from our dataset and the target is whether a loan payment was past due or not. Fitted tree visualization helps to understand how rejection rules and detected segments will look like. As every leaf can be potentially splitted further, there is a high chance to get small groups as terminated leaves. This behavior is regulated by splitting criterias like <strong>min_impurity_decrease</strong>, <strong>min_samples_leaf</strong> and similar.</p><p>To provide a practical example let’s use a datasample with two variables/features and one binary target:</p><ul><li>Variables:<strong> fraud_score</strong> and <strong>phone_details_score</strong>, that are fraud indicators</li><li>Target: <strong>FPD_30 </strong>that equal to 1, if first credit payment has 30 days past due, and 0 otherwise</li></ul><p>Let’s try to find 2 rules here: one based on only one variable only and second one based on both two variables. To do that we fit 2 DecisionTreeClassifiers: the first with <strong>fraud_score </strong>variable<strong> </strong>only<strong>, </strong>the second one using both <strong>fraud_score</strong> and <strong>phone_details_score. </strong>Target will be the same in both experiments:</p><p>1-variable segments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vg9jr2cZruDowI9h" /></figure><p>2-variables segments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rHkPMD--ralmZcWU" /></figure><p>Easy to see that right part of the pictures is a set of a good candidates to be a high-value segments as well as appropriate rejection rules:</p><p>But here we see yet another problem: how is it possible to set up decision tree parameters to satisfy business requirements like group size and mean target value within groups? Of course, we can manually inspect the decision tree plot to understand which node or leaf is an optimal solution. We can even write some code that will check every node size and default rate whether it satisfies the requirements or not. Anyway, this way has the right to life and is actively used in real tasks.</p><h3>Alternative high-value segments detection algorithm: optimal binning</h3><p>This is a pretty popular <a href="https://github.com/guillermo-navas-palencia/optbinning?tab=readme-ov-file">Python package</a> that implements a <strong>binning algorithm</strong> — a technique to discretize the values of a continuous variable into bins (groups or buckets). From a modeling perspective, the binning technique may mitigate data issues such as the handling of missing values, the presence of outliers and statistical noise, and data scaling. <a href="https://arxiv.org/pdf/2001.08025.pdf">https://arxiv.org/pdf/2001.08025.pdf</a>.</p><p>One of the most popular application for optimal binning is numerical <a href="https://medium.com/@prasadmahamulkar/discretization-or-numerical-feature-encoding-b2544347c70b">features discretisation procedure</a>.</p><p>Well, how can we use it for high-value segments detection considering our requirements for group sizes and others? Optimal binning package allows to set up a series of constraints for bins sizes, bins amount and minimal mean target difference between resulting bins. So we can set up these parameters according to the requirements, for example:</p><ul><li>Minimal segment/group size is 2% of population</li><li>Mean target in the segment/group we are looking for is 30 percentage points higher than mean target in the whole dataset.</li></ul><p>Following these constraints, as it has been done with decision trees, let’s make this procedure for 1-variable segments using the following code:</p><pre>x = pd.to_numeric(<br>  df[&#39;fraud_score&#39;], <br>  errors=&#39;ignore&#39;<br>).astype(float).fillna(NAN)<br><br>y = df[TARGET].values<br><br>optb = OptimalBinning(    <br>    max_n_bins=2,              # we need only two bins: high-value group and others<br>    min_event_rate_diff=0.3,   # minimal difference in mean target<br>    divergence=&#39;iv&#39;,           # objective metric to maximize<br>    min_bin_size=0.02,         # minimal fraction for bin size: as high-value group is a minor group, this rule will be applied only for it<br>    dtype=&quot;numerical&quot;,         # type of task for OptimalBinning (there is also possible to fing optimal bin for categorical values)<br>    solver=&quot;cp&quot;, <br>    prebinning_method=&quot;cart&quot;,  # initial binning based on decision tree!<br>    max_pvalue=0.05,<br>    time_limit=10,<br>    min_prebin_size=0.0001,<br>    max_n_prebins=1000,<br>)<br><br>optb.fit(x, y)<br>optb.binning_table.build()</pre><p>Note that the <strong>prebinning_method</strong> parameter is responsible for an initial binning method. Setting up it with <strong>“cart”</strong> we ask optimal binning to use a decision tree for an initialization and it works very similar to the decision tree based method we just covered in the previous section! After initialization the algorithm tries to merge leafs to bigger ones (do you remember pruning?) to satisfy all the constraints set up.</p><p>As a result we will get the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*-XdFQsx6E3_HhR6x" /></figure><p><strong>“Bin”</strong> column shows how we should construct our rejection rule based on <strong>fraud_score </strong>to<strong> </strong>fit into our constraints:</p><ul><li><strong>fraud score &gt; 10.5</strong></li></ul><p>This rule will provide us with the required level of mean target (62%!) in a group whose size is 2.3% of the datasample, and this mean target is 35 percentage points higher than within rest data. From a business perspective, we can propose risk analysts to use this rule in a decision making system to reject all loan applicants, who have <strong>fraud_score</strong> value higher than 10.5 as this rule highlights a segment with very high risk of default.</p><p>You also can use this approach for categorical features as well just by specifying <strong>dtype=”numerical”</strong> when creating OptimalBinning object. As a result you will get a table with sets of categories, that your categorical feature can be represented by (instead of bins) you can use to describe your rejection rule.</p><p>But who said that there is the only segment with desired properties along the fraud_score<strong> </strong>axis? Other words, what if rules like</p><ul><li><strong>fraud score &lt; 3 AND fraud score &gt; 2</strong></li></ul><p>produce segments we are looking for as well? To catch these cases we can increase <strong>“max_n_bins”</strong> parameter up to 3 or higher and the resulting table will highlight these segments if they exist.</p><p>When it comes to 2-variables segments, optimal binning can help as well (see <strong>OptimalBinning2D</strong> <a href="https://gnpalencia.org/optbinning/tutorials/tutorial_binning_2d.htm">documentation</a> <a href="https://gnpalencia.org/optbinning/tutorials/tutorial_binning_2d.htm)">)</a> but setting up a constraints and results interpreting seems to be more complicated and it worth to be described separately.</p><h3>Yet another classical method: clusterization</h3><p>Well known way to investigate a multidimensional dataset is to apply one of the clusterization algorithms. Once clusters are built, we can calculate the mean target for every cluster and perhaps some of them will have the desired properties. Yes, we can change some settings of a clusterization algorithm towards high-value segment extraction. For example, in <strong>hierarchical</strong> and <strong>agglomerative</strong> clusterization we can restrict maximum and minimum cluster size, but as clusterization doesn’t consider target values, it can’t guarantee any stable results.</p><h3>Conclusions</h3><blockquote>While well-known approaches, decision trees and clusterization algorithms, have their undoubted advantages like interpretability and possibility to work with multidimensional datasets, optimal binning provides more precise settings for a target segment and works smoothly only with 1 dimension. My experience shows that it is better to start with classical methods for a high level analysis to highlight directions or variables that can be researched deeper with optimal binning on the next stage. So, the balanced combination of all discussed methods seems to be the most optimal approach.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96f03266abd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How and why run Jupyter notebooks in Docker: base set up]]></title>
            <link>https://medium.com/@kacalap1/how-and-why-run-jupyter-notebooks-in-docker-base-set-up-fd982f8beac1?source=rss-6821a3ba8f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd982f8beac1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jupyter]]></category>
            <dc:creator><![CDATA[Aleksandr Katsalap]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 02:00:29 GMT</pubDate>
            <atom:updated>2023-10-02T02:00:29.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Z--4uPPMKYXFelTt.png" /></figure><p>Docker became the most popular technology to isolate application environment from OS one. “Dockerizing” Jupyter server that allows to run Python scripts interactively is not an exception. It allows:</p><ul><li>To isolate Python environment that you are going to use to write a code from OS. Jupyter installation itself requires a lot of various packages that would installed directly into OS if you installed Jupyter directly. Even if your code is running is virtual environment, it won’t isolate Jupyter itself with its packages from OS.</li><li>To make you applications and experiments in Jupyter notebooks reproducible.</li><li>To easy automate Jupyter configuration process. Usually before using Jupyter just after installation you need to adjust its settings according to your requirements. When running Jupyter in Docker you can enumerate all these actions in a dockerfile and they will be set up automatically during a docker image building process.</li></ul><h4>Jupyter in Docker: files preparation</h4><ul><li>Install Docker application itself. Of course, you should have it installed on your machine to build and run Docker containers. Refer to <a href="https://www.docker.com/products/docker-desktop/">docker.com</a> to do it if you haven’t.</li><li>Find base Docker image. As Jupyter typically used for data science or data analytics routines, it’s better to choose a base Docker image with a minimal set of an appropriate Python packages preinstalled. The most popular one is <a href="https://hub.docker.com/r/jupyter/datascience-notebook/tags/">datascience-notebook</a> located at Docker hub. You can use search by tag to find a proper Python version which the image will be built on. In this example version 3.9.12 will be used:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*NF-HNuvjm17VWmw34wV4qw.png" /></figure><ul><li>Prepare your <strong><em>requirements.txt</em></strong> file for Python environment. Note that Docker image that you’ve just loaded already contains some versions of packages like pandas, numpy and others (you can check which ones in Docker image description). So, to have the proper versions of these packages in you Jupyter notebooks, please, specify them explicitly in <strong><em>requirements.txt </em></strong>as well:</li></ul><pre>psycopg2==2.9.3<br>sqlalchemy==1.4.32<br>pandas==1.3.5 # explicit specifying the proper pandas version<br>numpy==1.21.5 # explicit specifying the proper numpy version</pre><ul><li>Prepare <strong><em>Dockerfile</em></strong>. A minimal <strong><em>Dockerfile </em></strong>can be the following:</li></ul><pre># Take base image<br>FROM jupyter/datascience-notebook:python-3.9.12<br><br># Set current directory as a current one<br>WORKDIR .<br><br># Install Python packages<br>COPY requirements.txt requirements.txt<br>RUN python -m pip install --no-cache-dir -r requirements.txt<br><br># Instructions how to run a container built<br>ENTRYPOINT [&quot;python3&quot;, &quot;-m&quot;]<br>CMD [&quot;jupyter&quot;, &quot;notebook&quot;, &quot;--port=8888&quot;, &quot;--no-browser&quot;, &quot;--ip=0.0.0.0&quot;, &quot;--allow-root&quot;]</pre><h4>Build and run container</h4><p>Put both <strong><em>Dockerfile</em></strong> and <strong><em>requirements.txt</em></strong> files in the same directory, open terminal in that directory and run:</p><pre>docker build . -t jnb<br>docker run -p 8888:8888 -v /home/user/jupyter_in_docker:/home/jovyan/work jnb</pre><p>Here option <strong>-p </strong>maps internal port 8888 of the container into external port of your local machine. Option <strong>-v</strong> will map a directory on your “physical” machine on a directory inside the container. It means that all files in <strong>/home/user/jupyter_in_docker</strong> directory on local machine will be visible in directory <strong>/home/jovyan/work</strong> inside the container and vice versa.</p><p>In this case you will see logs in terminal that contain a link you should use to open a start page of running Jupyter server:</p><pre>[I 00:10:53.567 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).<br>[C 00:10:53.569 NotebookApp] <br>    <br>    To access the notebook, open this file in a browser:<br>        file:///home/jovyan/.local/share/jupyter/runtime/nbserver-1-open.html<br>    Or copy and paste one of these URLs:<br>        http://ab2eda332e7d:8888/?token=a40b859486884bbacb5199bbcc8e765fda4843b0ef8a6917<br>     or http://127.0.0.1:8888/?token=a40b859486884bbacb5199bbcc8e765fda4843b0ef8a6917</pre><p>Note, that to stop the container you can just press “Control-C” keyboard combination being in this terminal. And you can’t use this terminal while container is running.</p><h4>Run in detached mode</h4><p>You also can run Docker container <strong>in detached mode</strong>. It means that container runs in background and is not attached to your terminal. When you run a container in detached mode, you can continue to use your terminal to run other commands or interact with a container. To do that, add option <strong>-d </strong>to<strong> run </strong>command</p><pre>docker run -d -p 8888:8888 -v /home/user/jupyter_in_docker:/home/jovyan/work jnb</pre><p>But now you don’t have a direct link to open a Jupyter start page. If you open <a href="http://localhost:8888/">http://localhost:8888</a> or <a href="http://127.0.0.1:8888/">http://127.0.0.1:8888</a> in browser, you will end up with page asking token or password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Te6BxV_eAtzw90OMNTFsDw.png" /></figure><p>You can turn token or password off but it depends on your security requirements. To do that just modify the last command in <strong><em>Dockerfile </em></strong>by adding an appropriate options:</p><pre>CMD [&quot;jupyter&quot;, &quot;notebook&quot;, &quot;--port=8888&quot;, &quot;--no-browser&quot;, &quot;--ip=0.0.0.0&quot;, &quot;--allow-root&quot; ,&quot;--NotebookApp.token=&#39;&#39;&quot;,  &quot;--NotebookApp.password=&#39;&#39;&quot;]</pre><p>Now, you can go to <a href="http://localhost:8888/">http://localhost:8888</a> or <a href="http://127.0.0.1:8888/">http://127.0.0.1:8888</a> and Jupyter start page will be available directly.</p><h4>Stop in detached mode</h4><p>As terminal you used to run the container is not available in detached mode, you can’t stop in by pressing “Control-C” combination as described above. But you can stop the container directly by <strong>stop</strong> command, but you should know your container ID first:</p><pre> docker ps</pre><p>Find your container by image name and copy its ID from <strong>CONTAINER ID</strong> column. Then stop the container:</p><pre>docker stop &lt;container_id&gt;</pre><p>Here <strong>&lt;container_id&gt;</strong> is a container ID you’ve just copied.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd982f8beac1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install and configure JupyterHub on AWS EC2]]></title>
            <link>https://medium.com/@kacalap1/how-to-install-and-configure-jupyterhub-on-aws-ec2-edf8859cb07c?source=rss-6821a3ba8f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf8859cb07c</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[jupyterhub]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jupyterlab]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Aleksandr Katsalap]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 01:05:11 GMT</pubDate>
            <atom:updated>2023-09-22T15:54:56.433Z</atom:updated>
            <content:encoded><![CDATA[<p>JupyterHub allows multiple users to run their own, isolated Jupyter servers on one machine to create Jupyter notebooks. If your data science team has a big and powerful machine and you want to share its resources between a team members for working in Jupyter notebooks without interfering with each other, JupyterHub is the way to go.</p><p>To read more about JupyterHub you can refer to <a href="https://jupyterhub.readthedocs.io/en/stable/">official documentation</a></p><figure><img alt="JupyterHub logo" src="https://cdn-images-1.medium.com/max/342/1*NoMhkGpUkFmnKgv83ClIFg.png" /></figure><h3>Installation on AWS EC2</h3><p>The JupyterHub full installation process on EC2 is described in <a href="https://tljh.jupyter.org/en/latest/install/amazon.html">Installing on Amazon Web Services</a>. But basically, if you’ve already had a running EC2, you need the following command to install JupyterHub on it:</p><pre> curl -L https://tljh.jupyter.org/bootstrap.py \<br> | sudo python3 - \<br> --admin admin_user_name \<br> --show-progress-page</pre><p>where <strong><em>admin_user_name —</em></strong> name of a<strong><em> </em></strong>user with root (admin) access, that you have to use later during your first login to JupyterHub</p><h3>JupyterHub configuration</h3><p>The described process allows to set up an independent Jupyter server for each user.</p><h4>First JupyterHub login</h4><p>To get an access to JupyterHub web interface, you have to enter the address <strong><em>http://xxx.xxx.xxx.xxx/hub/admin</em></strong> in your browser, where xxx.xxx.xxx.xxx is the IP address of the EC2 server on which JupyterHub was installed. When you first log in, JupyterHub will ask you to enter the <strong><em>admin_user_name</em></strong> you entered during installation and to create and to enter a password for that user. During the next logins as <strong><em>admin_user_name </em></strong>you be asked to enter the password you’ve just entered, so it’s important to remember it. If the installation and first login were successful, the admin panel will be displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2saLXhjpqjkuw0d-294xcQ.png" /></figure><p>On the screenshot above there is yet another user with admin rights. Of course, if it is you first login to JupyterHub you will be the only displayed one, but if you add other users with admin rights later, they will be displayed here as well.</p><p>Admin panel has pretty simple functionality that allows you to add and delete users, to provide an admin rights to them, to start and to stop their Jupyter servers and to start and to stop JupyterHub itself.</p><h4>How to run bash commands on behalf of users</h4><p>Now, when you have an account on JupyterHub (with admin rights or not), you can start a configuration process to customize it. But the thing is that during the installation process JupyterHub creates a new user in OS of the server that JupyterHub is running on. And for every new JupyterHub user an appropriated OS user is created on server. For example, if you create new JupyterHub user <strong><em>admin_user_name</em></strong>, the user<strong><em> jupyterhub-admin_user_name </em></strong>will be created in OS of server. And all the commands to configure individual settings for a JupyterHub user (not global JupyterHub settings) should be run on behalf of <strong><em>jupyterhub-admin_user_name </em></strong>OS user. The simplest way to do that is to login as a JupyterHub user, to go to the Jupyter server home page and to run a new terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*bPydDP6P2gy0BJ8aoKaUsQ.png" /></figure><p>Probably it is not a perfect way but the simplest one. All the commands listed below should be run in this terminal.</p><h4>Timeouts</h4><p>By default, Jupyter server has a pretty small timeout (shutdown after a certain time of inactivity). As most of “classical” Jupyter notebooks don’t have any timeouts at all, it won’t a good surprise for JupyterHub based Jupyter servers if they would shutdowned unexpectedly with unsaved job lost.</p><p>So, to prevent these situations, you can increase or disable these timouts at all to prevent unexpected losses of your job. To perform the last, you have to run:</p><pre>sudo tljh-config set services.cull.enabled False<br>sudo tljh-config reload</pre><p>There a lot of different settings for timeouts, so it would be useful to read more about them at “<a href="https://tljh.jupyter.org/en/latest/topic/idle-culler.html">Culling idle notebook servers</a>”.</p><h4>Python virtual environments</h4><p>Each JupyterHub user can create his own independent environments that won’t affect environments of other users. For example, a user has a <strong><em>requirements.txt</em></strong> file with a set of Python packages that he wants to use to work in JupyterHub. It is important to note that JupyterHub allows to install Python environments that will be available for multiple users, but this way is not recommended because once some user modified such a “shared” environment, it will also be modified for other environment users. Of course, other environment users are unlikely to be happy with such unexpected changes.</p><p>So, to install a new Python environment <strong><em>my_env</em></strong> from <strong><em>requirements.txt</em></strong> file using, say, <strong>conda</strong> you can run:</p><pre>conda create --name my_env --file requirements.txt<br>сonda activate my_env</pre><p>Now, to be able to select this environment in Jupyter notebook, you need to install the <strong><em>ipykernel</em></strong> package</p><pre>conda install ipykernel</pre><p>and to enable its visibility in Jupyter server:</p><pre>python -m ipykernel install \<br>--user \<br>--name my_env_name \<br>--display-name &quot;Python 3.11 (base)&quot;</pre><p>where <strong><em>Python 3.11 (base) </em></strong>is just a name (or alias) of your environment that will be shown in kernels list in your Jupyter server. It doesn’t have to be equal to <strong><em>my_env </em></strong>and you can choose any alias for <strong><em>my_env. </em></strong>It’s possible to set these aliases in <strong>~/.local/share/jupyter/kernels/kernel.json </strong>configuration file.</p><p>Finally, you can choose one of your Python environments in a dropdown menu in Jupyter when you start creating a new notebook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DpeW_fZ2ic4asEdW" /></figure><h4>Jupyter notebook extensions and Jupyter Lab</h4><p>Just like in a regular Jupyter server that works without JupyterHub, each user can install and configure extensions he needs completely independently of other users (more details about what they are and how they are useful can be found, for example, here <a href="https://www.analyticsvidhya.com/blog/2022/02/11-extensions-to-power-up-your-jupyter-notebook/">11 Extensions to Power Up your Jupyter Notebook</a>.</p><p>And to switch from “classic” Jupyter notebook interface to Jupyter Lab the only thing you have to do is to replace the word “tree” with “lab” in URL address. For example:</p><p><a href="http://127.0.0.1:8888/tree">http://127.0.0.1:8888/tree</a> → <a href="http://127.0.0.1:8888/tree">http://127.0.0.1:8888/</a>lab</p><h4>Don’t forget about security</h4><p>If you follow this instruction, the connection to JupyterHub won’t be secure as it uses HTTP by default. There are several ways to enable HTTPS, so please refer to <a href="https://tljh.jupyter.org/en/latest/howto/admin/https.html#automatic-https-with-let-s-encrypt">Enable HTTPS page</a> to choose the most applicable way for your AWS configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf8859cb07c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>