<?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 Deryl Baharudin Sopandi on Medium]]></title>
        <description><![CDATA[Stories by Deryl Baharudin Sopandi on Medium]]></description>
        <link>https://medium.com/@deryl.baharudin?source=rss-6181a9ee02de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8B-K3nDf1CD4GcJInN5RXg.jpeg</url>
            <title>Stories by Deryl Baharudin Sopandi on Medium</title>
            <link>https://medium.com/@deryl.baharudin?source=rss-6181a9ee02de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:06:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deryl.baharudin/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[Join Me on My Journey to Remote Work Success with RWID]]></title>
            <link>https://medium.com/@deryl.baharudin/join-me-on-my-journey-to-remote-work-success-with-rwid-83aa58829e98?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/83aa58829e98</guid>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[wfa]]></category>
            <category><![CDATA[rwid]]></category>
            <category><![CDATA[wfh]]></category>
            <category><![CDATA[remote-job]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 05:58:18 GMT</pubDate>
            <atom:updated>2023-09-20T05:58:18.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>Remote Worker: My Journey</h4><h4>Don’t just watch — Embark alongside me and RWID on our collective quest for our first remote jobs.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q_pZbvATubG4mPqx" /><figcaption>Photo by <a href="https://unsplash.com/@mahlkornel?utm_source=medium&amp;utm_medium=referral">Kornél Máhl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As we move into an increasingly digital era, the traditional work model of 9-to-5 is being steadily replaced by a more flexible and efficient model — remote working. The journey towards becoming a successful remote worker is filled with opportunities for personal growth, financial gain, and an improved work-life balance.</p><h3><strong>My Story</strong></h3><p>As someone who previously worked in a high-pressure manufacturing plant office, I was no stranger to grueling workloads. My daily routine involved waking up at 4 AM, leaving for work at 6 AM, and not returning home until late into the night — often as late as 9 or 10 PM. On some occasions, I would even find myself working until 1 AM. Weekends were no exception; there were periods when I had to work continuously for two months without a single day off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KSU3dCI-CyueYcFp" /><figcaption>Photo by <a href="https://unsplash.com/@gunaivi?utm_source=medium&amp;utm_medium=referral">ahmad gunnaivi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This lifestyle left me feeling frustrated and overwhelmed. The future looked bleak if this continued into my family life — spending less than one-eighth of my time with my loved ones if I had any energy left after draining days at work.</p><h3>The Allure of Remote Working</h3><p>That’s when remote working caught my attention as a potential solution. It promised flexibility that traditional jobs lacked — eliminating time wasted in traffic jams and chaotic commutes was appealing. More enticing was the prospect of setting my own hours; imagine taking midday naps with your kids or running errands during weekdays without having to take leave from work!</p><p>Moreover, remote working offered higher pay rates because even while living in Indonesia; one could earn at least the American minimum wage rate due to globalized employment opportunities.</p><h3>The Pros of Remote Working</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CcxW0XVNQ7C8MBC7" /><figcaption>Photo by <a href="https://unsplash.com/@yasmina?utm_source=medium&amp;utm_medium=referral">Yasmina H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Beyond these personal benefits are broader advantages that make remote working more appealing compared to traditional jobs:</p><ul><li>Flexibility: With no fixed office hours or location constraints, you can design your schedule around when you’re most productive.</li><li>Better Work-Life Balance: By eliminating commuting time and allowing flexible schedules, you can balance your professional responsibilities with personal commitments.</li><li>Increased Productivity: Studies have shown that employees tend to be more productive when they have control over their workspace and schedule.</li><li>Cost Savings: No commute means saving on gas or public transport costs. Plus, there’s less need for formal attire or eating out.</li><li>Global Opportunities: You aren’t limited by geography in your job search which increases earning potential significantly.</li></ul><h3>Potential of Remote Work in The Future</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_U8stfFyaZvrmgba" /><figcaption>Photo by <a href="https://unsplash.com/@fazurrehman?utm_source=medium&amp;utm_medium=referral">Faizur Rehman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The future looks promising for remote workers. According to Global Workplace Analytics estimates, by 2025 nearly half of all jobs worldwide will be performed remotely at least part-time.</p><p>Furthermore; advancements in technology are making it easier than ever before to collaborate across different time zones and cultures — making it possible for companies worldwide to tap into global talent pools rather than being restricted by geographical limitations.</p><h3>Why RWID?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3_yPE4yeL8EfXG5l" /><figcaption>Photo by <a href="https://unsplash.com/@cwmonty?utm_source=medium&amp;utm_medium=referral">Chris Montgomery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Transitioning into remote work wasn’t going to be easy considering that my previous job experience didn’t involve IT skills or anything similar which are often required for such roles.</p><p>That’s when I discovered RWID (Remote Worker Indonesia). Their mission is “to make Indonesia the number one provider of remote workers globally,” which intrigued me greatly. With experienced CEOs and mentors who have worked remotely themselves guiding you along your journey; joining RWID seemed like an exciting opportunity despite its hefty membership fee of IDR 6.5 million for super-intensive mentoring.</p><h3>RWID vs Traditional Bootcamps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*nOVU52ndIf_Xg2oRNOrNvQ.png" /><figcaption>Photo on <a href="https://remoteworker.id/">RWID</a></figcaption></figure><p>You might wonder why to join RWID when there are other bootcamps or intensive courses that might offer similar training programs for lower fees? After attending a data science bootcamp myself, I realized what RWID offered was much more valuable due to their focus on making each mentee independently capable of securing remote jobs along with fostering an ever-growing community where you can switch career paths once you’ve secured certain types of jobs.</p><p>Unlike traditional bootcamps that focus only on imparting skills, RWID also helps its members adapt to the unique challenges posed by remote work — from managing time zones to maintaining productivity in a home environment. It’s not just about getting a job; it’s about thriving in it long-term.</p><p>RWID doesn’t guarantee employment post-training but provides its members access to best practices from experienced professionals smoothing our efforts towards securing our first remote job. According to Eko (SEO RWID), individuals without any prior experience need approximately 400 hours of learning through RWID before they can land their first gig — which seems reasonable given how mentorship should ideally equip mentees with skills necessary for independent success rather than just focusing on immediate job placements.</p><p>If you’re someone who dreams about earning hourly wages in dollars while enjoying quality family time without sacrificing work, then remote working is the path forward. Join me and many others in <a href="https://remoteworker.id/">RWID</a> as we navigate through the challenges of securing our first remote jobs and open doors to countless opportunities that lie ahead.</p><p>Link to see more about RWID: <a href="https://remoteworker.id/">https://remoteworker.id/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83aa58829e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching Numbers & Saving Lives: My Journey with Diabetes Prediction (Part 2)]]></title>
            <link>https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/a84ef32b947c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[diabetes-prediction]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 13:15:12 GMT</pubDate>
            <atom:updated>2023-09-17T13:29:00.045Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science: Tutorial Supervised Machine Learning</h4><blockquote>The battle against diabetes is intensifying. With the rich data from the Pima Indians community, we’re tapping into machine learning to uncover insights and predict risks like never before. Join me in this deep dive into how technology is reshaping our approach to diabetes prevention and care.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/0*crnBmQBe5sCZ6Q47.jpeg" /><figcaption>Photo on <a href="https://blog.ml.cmu.edu/2018/12/12/massively-parallel-hyperparameter-optimization/">ML.CMU</a></figcaption></figure><p><strong>Table of Contents:</strong></p><ol><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">BUSINESS PROBLEM AND DATA UNDERSTANDING</a><br>1.1. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Context</a><br>1.2. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Define Business Problem</a><br>1.3. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Data Understanding</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">DATA CONDITIONING</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">EXPLORATORY DATA ANALYSIS (EDA)</a><br>3.1. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Missing Value, Anomaly, Outlier, and Duplicated Data Detection</a><br>3.2. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Feature Engineering</a><br>3.3. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Univariate Analysis</a><br>3.4. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Bivariate Analysis</a><br>3.5. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1#cac3">Multivariate Analysis</a></li><li><a href="#59bc">DATA PRE-PROCESSING</a></li><li><a href="#488f">MODELING</a><br>5.1. <a href="#8bd2">Model Benchmarking</a><br>5.2. <a href="#a7bb">Hyperparameter Tuning</a><br>5.3. <a href="#7ac5">Trial using Undersampling and Oversampling</a><br>5.4. <a href="#543a">Feature Selection</a><br>5.5. <a href="#95af">Re-run using Feature Selection</a><br>5.6. <a href="#e821">Other Optimization Model</a></li><li><a href="#2b0a">DEPLOYMENT</a></li><li><a href="#e7d6">CONCLUSION</a></li><li><a href="#e71f">RECOMMENDATION</a></li></ol><p>You can access the full code on my GitHub.</p><p><a href="https://github.com/derylbaharudin/diabetes-prediction">GitHub - derylbaharudin/diabetes-prediction: Pima Indian Diabetes Prediction (Classification Supervised Machine Learning)</a></p><p><strong>4. DATA PRE-PROCESSING</strong></p><p><strong>Pre-processing Scheme</strong></p><p>We will compare several preprocessing schemes to get the best preprocessing scheme for this dataset.</p><p><strong>a. Scheme 1<br>Data:<br>- </strong>data without feature engineering (df)<br><strong>Preprocessing:<br>- </strong>No preprocessing method applies to this scheme</p><p><strong>b. Scheme 2</strong> (transformer1)<br><strong>Data:</strong> <br>- data without feature engineering (df)<br><strong>Preprocessing:<br></strong>- RobustScaler: glucose, blood_pressure, skin_thickness, insulin, bmi, and age</p><p><strong>c. Scheme 3</strong> (transformer2)<br><strong>Data:</strong><br>- data after feature engineering (df_eda1)<br><strong>Preprocessing:</strong><br>- One Hot Encoding: insulin_stat, glucose_stat<br>- Ordinal Encoding: bmi_group, blood_pressure_stat<br>- RobustScaler: glucose, blood_pressure, skin_thickness, insulin, bmi, and age</p><p><strong>d. Scheme 4</strong> (transformer3)<br><strong>Data:</strong><br>- data after feature engineering (df_eda1)<br>- drop feature: insulin, glucose, bmi, blood_pressure<br><strong>Preprocessing:</strong><br>- One Hot Encoding: insulin_stat, glucose_stat<br>- Ordinal Encoding: bmi_group, blood_pressure_stat<br>- RobustScaler: skin_thickness and age</p><p><strong>e. Scheme 5</strong> (transformer4)<br><strong>Data:</strong><br>- data without feature engineering (df)<br><strong>Preprocessing:</strong><br>- QuantileTransformer: glucose, blood_pressure, skin_thickness, insulin, bmi, and age</p><p>The robust scaler was chosen because of the differences in nominal data so that the range of nominal data is the same and the sensitivity of all features to the model is the same.</p><p><strong>Preparation for dataset and preprocessing in scheme 1</strong></p><pre>x_s1 = df.drop(columns=[&#39;y&#39;])<br>y_s1 = df[&#39;y&#39;]<br><br># Train-Test Data Splitting<br>x_s1_train, x_s1_test, y_s1_train, y_s1_test = train_test_split(x_s1, y_s1, stratify=y_s1, test_size=0.2, random_state = 2022)<br>x_s1_train.shape, x_s1_test.shape, y_s1_train.shape, y_s1_test.shape</pre><p><strong>Preparation for dataset and preprocessing in scheme 2</strong></p><pre>x_s2 = df.drop(columns=[&#39;y&#39;])<br>y_s2 = df[&#39;y&#39;]<br><br># Train-Test Data Splitting<br>x_s2_train, x_s2_test, y_s2_train, y_s2_test = train_test_split(x_s2, y_s2, stratify=y_s2, test_size=0.2, random_state = 2022)<br>x_s2_train.shape, x_s2_test.shape, y_s2_train.shape, y_s2_test.shape<br><br>scaler_var = [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;, &#39;bmi&#39;, &#39;age&#39;]<br><br># transformer for preprocessing scheme 2<br>transformer1 = ColumnTransformer([<br>    (&#39;scaler&#39;, RobustScaler(), scaler_var)<br>], remainder=&#39;passthrough&#39;)</pre><p><strong>Preparation for dataset and preprocessing in scheme 3</strong></p><pre>x_s3 = df_eda1.drop(columns=[&#39;y&#39;])<br>y_s3 = df_eda1[&#39;y&#39;]<br><br># Train-Test Data Splitting<br>x_s3_train, x_s3_test, y_s3_train, y_s3_test = train_test_split(x_s3, y_s3, stratify=y_s3, test_size=0.2, random_state = 2022)<br>x_s3_train.shape, x_s3_test.shape, y_s3_train.shape, y_s3_test.shape<br><br>scaler_var = [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;, &#39;bmi&#39;, &#39;age&#39;]<br>ordinal_var = [&#39;bmi_group&#39;, &#39;blood_pressure_stat&#39;]<br>onehot_var = [&#39;insulin_stat&#39;, &#39;glucose_stat&#39;]<br><br>ordinal_mapping = [<br>    {&#39;col&#39;:&#39;bmi_group&#39;,<br>     &#39;mapping&#39;: {None:0,&#39;Underweight&#39;:1,&#39;Normal&#39;:2,&#39;Overweight&#39;:3,&#39;Obesity 1&#39;:4,&#39;Obesity 2&#39;:5,&#39;Obesity 3&#39;:6}<br>     },<br>    {&#39;col&#39;:&#39;blood_pressure_stat&#39;,<br>     &#39;mapping&#39;:{None:0,&#39;Normal&#39;:1,&#39;Hypertension Stage 1&#39;:2,&#39;Hypertension Stage 2&#39;:3}<br>     }]<br><br># transformer for preprocessing scheme 3<br>transformer2 = ColumnTransformer([<br>    (&#39;onehot&#39;, OneHotEncoder(), onehot_var),<br>    (&#39;ordinal&#39;, ce.OrdinalEncoder(cols=ordinal_var, mapping=ordinal_mapping), ordinal_var),<br>    (&#39;scaler&#39;, RobustScaler(), scaler_var)<br>], remainder=&#39;passthrough&#39;)</pre><p><strong>Preparation for dataset and preprocessing in scheme 4</strong></p><pre>x_s4 = df_eda1.drop(columns=[&#39;insulin&#39;, &#39;glucose&#39;, &#39;bmi&#39;, &#39;blood_pressure&#39;, &#39;y&#39;])<br>y_s4 = df_eda1[&#39;y&#39;]<br><br># Train-Test Data Splitting<br>x_s4_train, x_s4_test, y_s4_train, y_s4_test = train_test_split(x_s4, y_s4, stratify=y_s4, test_size=0.2, random_state = 2022)<br>x_s4_train.shape, x_s4_test.shape, y_s4_train.shape, y_s4_test.shape<br><br>scaler_var = [&#39;skin_thickness&#39;, &#39;age&#39;]<br>ordinal_var = [&#39;bmi_group&#39;, &#39;blood_pressure_stat&#39;]<br>onehot_var = [&#39;insulin_stat&#39;, &#39;glucose_stat&#39;]<br><br>ordinal_mapping = [<br>    {&#39;col&#39;:&#39;bmi_group&#39;,<br>     &#39;mapping&#39;: {None:0,&#39;Underweight&#39;:1,&#39;Normal&#39;:2,&#39;Overweight&#39;:3,&#39;Obesity 1&#39;:4,&#39;Obesity 2&#39;:5,&#39;Obesity 3&#39;:6}<br>     },<br>    {&#39;col&#39;:&#39;blood_pressure_stat&#39;,<br>     &#39;mapping&#39;:{None:0,&#39;Normal&#39;:1,&#39;Hypertension Stage 1&#39;:2,&#39;Hypertension Stage 2&#39;:3}<br>     }]<br><br># transformer for preprocessing scheme 4<br>transformer3 = ColumnTransformer([<br>    (&#39;onehot&#39;, OneHotEncoder(), onehot_var),<br>    (&#39;ordinal&#39;, ce.OrdinalEncoder(cols=ordinal_var, mapping=ordinal_mapping), ordinal_var),<br>    (&#39;scaler&#39;, RobustScaler(), scaler_var)<br>], remainder=&#39;passthrough&#39;)</pre><p><strong>Preparation for dataset and preprocessing in scheme 5</strong></p><pre>x_s5 = df.drop(columns=[&#39;y&#39;])<br>y_s5 = df[&#39;y&#39;]<br><br># Train-Test Data Splitting<br>x_s5_train, x_s5_test, y_s5_train, y_s5_test = train_test_split(x_s5, y_s5, stratify=y_s5, test_size=0.2, random_state = 2022)<br>x_s5_train.shape, x_s5_test.shape, y_s5_train.shape, y_s5_test.shape<br><br>scaler_var = [&#39;pregnancies&#39;, &#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;, &#39;bmi&#39;, &#39;diabetes_pedigree&#39;, &#39;age&#39;]<br><br># transformer for preprocessing scheme 5<br>transformer4 = ColumnTransformer([<br>    (&#39;scaler&#39;, QuantileTransformer(n_quantiles=100, random_state=2022, output_distribution=&#39;normal&#39;), scaler_var)<br>], remainder=&#39;passthrough&#39;)</pre><p>- <strong>Scheme 1</strong>: x_s1_train, x_s1_test, y_s1_train, y_s1_test without preprocessing<br>- <strong>Scheme 2</strong>: x_s2_train, x_s2_test, y_s2_train, y_s2_test with transformer1<br>- <strong>Scheme 3</strong>: x_s3_train, x_s3_test, y_s3_train, y_s3_test with transformer2<br>- <strong>Scheme 4</strong>: x_s4_train, x_s4_test, y_s4_train, y_s4_test with transformer3<br>- <strong>Scheme 5</strong>: x_s4_train, x_s5_test, y_s5_train, y_s5_test with transformer4</p><p><strong>5. MODELING</strong></p><pre>logreg = LogisticRegression(random_state= 2022)<br>tree = DecisionTreeClassifier(random_state = 2022)<br>knn = KNeighborsClassifier()<br>rf = RandomForestClassifier(random_state = 2022)<br>ada = AdaBoostClassifier(random_state = 2022)<br>grad = GradientBoostingClassifier(random_state = 2022)<br>xgboost = XGBClassifier(random_state = 2022)<br><br>skfold=StratifiedKFold(n_splits=5, random_state= 2022, shuffle=True)</pre><p><strong>5.1. Model Benchmarking</strong></p><p><strong>A. Cross Validation K-Fold for Data Training</strong></p><p><strong>Scheme 1: Training Data</strong></p><pre>models =[logreg, tree, knn, rf, ada, grad, xgboost]<br>score  =[]<br>avg    =[]<br>std    =[]<br><br>for i in models:<br>    estimator = Pipeline([<br>        (&#39;model&#39;,i)])<br>    <br>    model_cv  = cross_val_score(estimator,<br>                                x_s1_train,<br>                                y_s1_train,<br>                                cv = skfold,<br>                                scoring = &#39;roc_auc&#39;)<br>    <br>    score.append(model_cv.round(3))<br>    avg.append(model_cv.mean())<br>    std.append(model_cv.std())<br><br># Cross Validation ROC_AUC Score Train Set for Scheme 1<br><br>benchmark_train_res_s1 = pd.DataFrame({<br>    &#39;Model&#39;        :[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>    &#39;CV Score ROC_AUC&#39;:score, &#39;Mean ROC_AUC&#39;:avg,&#39;SDev&#39;:std}<br>    ).set_index(&#39;Model&#39;).sort_values(by=&#39;Mean ROC_AUC&#39;,ascending=False)<br><br>benchmark_train_res_s1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*H7fFoZu7aOD08dA5jOYuiw.png" /></figure><p><strong>Scheme 2: Training Data</strong></p><pre>models =[logreg, tree, knn, rf, ada, grad, xgboost]<br>score  =[]<br>avg    =[]<br>std    =[]<br><br>for i in models:<br>    estimator = Pipeline([<br>        (&#39;preprocessing&#39;,transformer1),<br>        (&#39;model&#39;,i)])<br>    <br>    model_cv  = cross_val_score(estimator,<br>                                x_s2_train,<br>                                y_s2_train,<br>                                cv = skfold,<br>                                scoring = &#39;roc_auc&#39;)<br>    <br>    score.append(model_cv.round(3))<br>    avg.append(model_cv.mean())<br>    std.append(model_cv.std())<br><br># Cross Validation ROC_AUC Score Train Set for Scheme 2<br><br>benchmark_train_res_s2 = pd.DataFrame({<br>    &#39;Model&#39;        :[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>    &#39;CV Score ROC_AUC&#39;:score, &#39;Mean ROC_AUC&#39;:avg,&#39;SDev&#39;:std}<br>    ).set_index(&#39;Model&#39;).sort_values(by=&#39;Mean ROC_AUC&#39;,ascending=False)<br><br>benchmark_train_res_s2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*x13UvVo8b9mm93vtwSR92Q.png" /></figure><p><strong>Scheme 3: Training Data</strong></p><pre>models =[logreg, tree, knn, rf, ada, grad, xgboost]<br>score  =[]<br>avg    =[]<br>std    =[]<br><br>for i in models:<br>    estimator = Pipeline([<br>        (&#39;preprocessing&#39;,transformer2),<br>        (&#39;model&#39;,i)])<br>    <br>    model_cv  = cross_val_score(estimator,<br>                                x_s3_train,<br>                                y_s3_train,<br>                                cv = skfold,<br>                                scoring = &#39;roc_auc&#39;)<br>    <br>    score.append(model_cv.round(3))<br>    avg.append(model_cv.mean())<br>    std.append(model_cv.std())<br><br># Cross Validation ROC_AUC Score Train Set for Scheme 3<br><br>benchmark_train_res_s3 = pd.DataFrame({<br>    &#39;Model&#39;        :[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>    &#39;CV Score ROC_AUC&#39;:score, &#39;Mean ROC_AUC&#39;:avg,&#39;SDev&#39;:std}<br>    ).set_index(&#39;Model&#39;).sort_values(by=&#39;Mean ROC_AUC&#39;,ascending=False)<br><br>benchmark_train_res_s3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*czP2aP0rYS-r4s9OeCZmUQ.png" /></figure><p><strong>Scheme 4: Training Data</strong></p><pre>models =[logreg, tree, knn, rf, ada, grad, xgboost]<br>score  =[]<br>avg    =[]<br>std    =[]<br><br>for i in models:<br>    estimator = Pipeline([<br>        (&#39;preprocessing&#39;,transformer3),<br>        (&#39;model&#39;,i)])<br>    <br>    model_cv  = cross_val_score(estimator,<br>                                x_s4_train,<br>                                y_s4_train,<br>                                cv = skfold,<br>                                scoring = &#39;roc_auc&#39;)<br>    <br>    score.append(model_cv.round(3))<br>    avg.append(model_cv.mean())<br>    std.append(model_cv.std())<br><br># Cross Validation ROC_AUC Score Train Set for Scheme 3<br><br>benchmark_train_res_s4 = pd.DataFrame({<br>    &#39;Model&#39;        :[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>    &#39;CV Score ROC_AUC&#39;:score, &#39;Mean ROC_AUC&#39;:avg,&#39;SDev&#39;:std}<br>    ).set_index(&#39;Model&#39;).sort_values(by=&#39;Mean ROC_AUC&#39;,ascending=False)<br><br>benchmark_train_res_s4</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*mOdWz_n9wsmy4T-63pDZig.png" /></figure><p><strong>Scheme 5: Training Data</strong></p><pre>models =[logreg, tree, knn, rf, ada, grad, xgboost]<br>score  =[]<br>avg    =[]<br>std    =[]<br><br>for i in models:<br>    estimator = Pipeline([<br>        (&#39;preprocessing&#39;,transformer4),<br>        (&#39;model&#39;,i)])<br>    <br>    model_cv  = cross_val_score(estimator,<br>                                x_s5_train,<br>                                y_s5_train,<br>                                cv = skfold,<br>                                scoring = &#39;roc_auc&#39;)<br>    <br>    score.append(model_cv.round(3))<br>    avg.append(model_cv.mean())<br>    std.append(model_cv.std())<br><br># Cross Validation ROC_AUC Score Train Set for Scheme 5<br><br>benchmark_train_res_s5 = pd.DataFrame({<br>    &#39;Model&#39;        :[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>    &#39;CV Score ROC_AUC&#39;:score, &#39;Mean ROC_AUC&#39;:avg,&#39;SDev&#39;:std}<br>    ).set_index(&#39;Model&#39;).sort_values(by=&#39;Mean ROC_AUC&#39;,ascending=False)<br><br>benchmark_train_res_s5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*S0BXMIeHLiTE_hoiAsSbcw.png" /></figure><p><strong>B. Cross Validation K-Fold for Data Testing</strong></p><p><strong>Scheme 1: Testing Data</strong></p><pre>models = [logreg, tree, knn, rf, ada, grad, xgboost]<br>score_roc_auc = []<br><br>def y_pred_func(i):<br>    estimator=Pipeline([<br>        (&#39;model&#39;,i)])<br>    x_s1_train,x_s1_test<br>    <br>    estimator.fit(x_s1_train,y_s1_train)<br>    return(estimator,estimator.predict(x_s1_test),x_s1_test)<br><br>for i,j in zip(models, [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;]):<br>    estimator,y_s1_pred,x_s1_test = y_pred_func(i)<br>    y_s1_predict = estimator.predict(x_s1_test)<br>    score_roc_auc.append(roc_auc_score(y_s1_test,y_s1_predict))<br>    <br>benchmark_test_res_s1 = pd.DataFrame({&#39;Model&#39;:[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>             &#39;ROC_AUC Score&#39;:score_roc_auc}).set_index(&#39;Model&#39;).sort_values(by=&#39;ROC_AUC Score&#39;,ascending=False)<br><br>benchmark_test_res_s1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*bpoFEfkwEWa3MZY2gdiWLg.png" /></figure><p><strong>Scheme 2: Testing Data</strong></p><pre>models = [logreg, tree, knn, rf, ada, grad, xgboost]<br>score_roc_auc = []<br><br>def y_pred_func(i):<br>    estimator=Pipeline([<br>        (&#39;preproces&#39;,transformer1),<br>        (&#39;model&#39;,i)])<br>    x_s2_train,x_s2_test<br>    <br>    estimator.fit(x_s2_train,y_s2_train)<br>    return(estimator,estimator.predict(x_s2_test),x_s2_test)<br><br>for i,j in zip(models, [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;]):<br>    estimator,y_s2_pred,x_s2_test = y_pred_func(i)<br>    y_s2_predict = estimator.predict(x_s2_test)<br>    score_roc_auc.append(roc_auc_score(y_s2_test,y_s2_predict))<br>    <br>benchmark_test_res_s2 = pd.DataFrame({&#39;Model&#39;:[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>             &#39;ROC_AUC Score&#39;:score_roc_auc}).set_index(&#39;Model&#39;).sort_values(by=&#39;ROC_AUC Score&#39;,ascending=False)<br><br>benchmark_test_res_s2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*hdw-O_QUHft1KWmJ_EFTKw.png" /></figure><p><strong>Scheme 3: Testing Data</strong></p><pre>models = [logreg, tree, knn, rf, ada, grad, xgboost]<br>score_roc_auc = []<br><br>def y_pred_func(i):<br>    estimator=Pipeline([<br>        (&#39;preproces&#39;,transformer2),<br>        (&#39;model&#39;,i)])<br>    x_s3_train,x_s3_test<br>    <br>    estimator.fit(x_s3_train,y_s3_train)<br>    return(estimator,estimator.predict(x_s3_test),x_s3_test)<br><br>for i,j in zip(models, [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;]):<br>    estimator,y_s3_pred,x_s3_test = y_pred_func(i)<br>    y_s3_predict = estimator.predict(x_s3_test)<br>    score_roc_auc.append(roc_auc_score(y_s3_test,y_s3_predict))<br>    <br>benchmark_test_res_s3 = pd.DataFrame({&#39;Model&#39;:[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>             &#39;ROC_AUC Score&#39;:score_roc_auc}).set_index(&#39;Model&#39;).sort_values(by=&#39;ROC_AUC Score&#39;,ascending=False)<br><br>benchmark_test_res_s3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*7u7FsA9D2sSf6brMIFrrSw.png" /></figure><p><strong>Scheme 4: Testing Data</strong></p><pre>models = [logreg, tree, knn, rf, ada, grad, xgboost]<br>score_roc_auc = []<br><br>def y_pred_func(i):<br>    estimator=Pipeline([<br>        (&#39;preproces&#39;,transformer3),<br>        (&#39;model&#39;,i)])<br>    x_s4_train,x_s4_test<br>    <br>    estimator.fit(x_s4_train,y_s4_train)<br>    return(estimator,estimator.predict(x_s4_test),x_s4_test)<br><br>for i,j in zip(models, [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;]):<br>    estimator,y_s4_pred,x_s4_test = y_pred_func(i)<br>    y_s4_predict = estimator.predict(x_s4_test)<br>    score_roc_auc.append(roc_auc_score(y_s4_test,y_s4_predict))<br>    <br>benchmark_test_res_s4 = pd.DataFrame({&#39;Model&#39;:[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>             &#39;ROC_AUC Score&#39;:score_roc_auc}).set_index(&#39;Model&#39;).sort_values(by=&#39;ROC_AUC Score&#39;,ascending=False)<br><br>benchmark_test_res_s4</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*CGQfPpqCdClXB8Lh3zOzCA.png" /></figure><p><strong>Scheme 5: Testing Data</strong></p><pre>models = [logreg, tree, knn, rf, ada, grad, xgboost]<br>score_roc_auc = []<br><br>def y_pred_func(i):<br>    estimator=Pipeline([<br>        (&#39;preproces&#39;,transformer4),<br>        (&#39;model&#39;,i)])<br>    x_s5_train,x_s5_test<br>    <br>    estimator.fit(x_s5_train,y_s5_train)<br>    return(estimator,estimator.predict(x_s5_test),x_s5_test)<br><br>for i,j in zip(models, [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;]):<br>    estimator,y_s5_pred,x_s5_test = y_pred_func(i)<br>    y_s5_predict = estimator.predict(x_s5_test)<br>    score_roc_auc.append(roc_auc_score(y_s5_test,y_s5_predict))<br>    <br>benchmark_test_res_s5 = pd.DataFrame({&#39;Model&#39;:[&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;],<br>             &#39;ROC_AUC Score&#39;:score_roc_auc}).set_index(&#39;Model&#39;).sort_values(by=&#39;ROC_AUC Score&#39;,ascending=False)<br><br>benchmark_test_res_s5</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*AkFWw-qFiCNMrfENR83hiw.png" /></figure><p><strong>Model Benchmarking Comparison</strong></p><pre>cols1 = [&#39;Scheme 1&#39;,&#39;Scheme 2&#39;,&#39;Scheme 3&#39;,&#39;Scheme 4&#39;,&#39;Scheme 5&#39;]<br>cols2 = [&#39;Train Score&#39;, &#39;Test Score&#39;]<br>tuples = []<br><br>for i in cols1:<br>  for j in cols2:<br>    tuples.append((i,j))<br><br>benchmark_compare_model = pd.DataFrame(columns = tuples)<br>benchmark_compare_model.columns = pd.MultiIndex.from_tuples(benchmark_compare_model.columns, names=[&#39;Scheme&#39;,&#39;Data&#39;])<br><br>models = [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;K-Nearest Neighbor&#39;,&#39;Random Forest&#39;, &#39;Ada Boost Classifier&#39;,&#39;Gradient Boosting&#39;,&#39;XGBoost&#39;]<br>bench_train = [benchmark_train_res_s1, benchmark_train_res_s2, benchmark_train_res_s3, benchmark_train_res_s4, benchmark_train_res_s5]<br>bench_test = [benchmark_test_res_s1, benchmark_test_res_s2, benchmark_test_res_s3, benchmark_test_res_s4, benchmark_test_res_s5]<br><br>for model in models:<br>  data = []<br>  for i in range(len(bench_train)):<br>      data.append(round(bench_train[i][&#39;Mean ROC_AUC&#39;][bench_train[i].index==model].values[0],4)*100)<br>      data.append(round(bench_test[i][&#39;ROC_AUC Score&#39;][bench_test[i].index==model].values[0],4)*100)<br>  benchmark_compare_model.loc[model] = data<br><br>benchmark_compare_model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*uo4S6eT6MEym-kv2N9NzoQ.png" /></figure><p>Of the five Preprocessing Schemes, Scheme 1 has the best score for training and testing. So, we will use Scheme 1 for further model optimization process.</p><p>Of the seven model candidates, Random Forest has the highest score in the data train and Logistic Regression has the highest score in the data test.</p><p>Based on the benchmark result, Random Forest has the highest mean cross-validation score approximately around 84%. However, Logistic Regression has the highest ROC-AUC score on the test set at 74%. Therefore, Logistic Regression will be used for further processing according to the test set score.</p><pre>estimator_logreg = Pipeline([<br>                        (&#39;model&#39;, logreg)])<br><br>estimator_logreg.fit(x_s1_train, y_s1_train)<br>y_predict_logreg = estimator_logreg.predict(x_s1_test)<br><br>disp = ConfusionMatrixDisplay(confusion_matrix(y_s1_test, y_predict_logreg))<br>disp.plot()<br>print(&#39;Logistic Regression ROC-AUC Score : &#39;,round(roc_auc_score(y_s1_test, y_predict_logreg),4)*100,&#39;%&#39;)<br><br>logreg_cv = (cross_val_score(estimator_logreg,x_s1_train,y_s1_train,cv=skfold,scoring=&#39;roc_auc&#39;).mean())<br>print(&#39;Logistic Regression CV Mean Score : &#39;,round(logreg_cv, 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*fmp-QvewkyTfi4ld1GS58g.png" /></figure><pre>estimator_grad = Pipeline([<br>                        (&#39;model&#39;, grad)])<br><br>estimator_grad.fit(x_s1_train, y_s1_train)<br>y_predict_grad = estimator_grad.predict(x_s1_test)<br><br>disp = ConfusionMatrixDisplay(confusion_matrix(y_s1_test, y_predict_grad))<br>disp.plot()<br>print(&#39;Gradient Boosting ROC-AUC Score : &#39;,round(roc_auc_score(y_s1_test, y_predict_grad),4)*100,&#39;%&#39;)<br><br>grad_cv = (cross_val_score(estimator_grad,x_s1_train,y_s1_train,cv=skfold,scoring=&#39;roc_auc&#39;).mean())<br>print(&#39;Gradient Boosting CV Mean Score : &#39;,round(grad_cv, 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*a22u9M2Jc7WAsbw9dqZpJQ.png" /></figure><pre>estimator_xgboost = Pipeline([<br>                        (&#39;model&#39;, xgboost)])<br><br>estimator_xgboost.fit(x_s1_train, y_s1_train)<br>y_predict_xgboost = estimator_xgboost.predict(x_s1_test)<br><br>disp = ConfusionMatrixDisplay(confusion_matrix(y_s1_test, y_predict_xgboost))<br>disp.plot()<br>print(&#39;XGBoost ROC-AUC Score : &#39;,round(roc_auc_score(y_s1_test, y_predict_xgboost),4)*100,&#39;%&#39;)<br><br>xgboost_cv = (cross_val_score(estimator_xgboost,x_s1_train,y_s1_train,cv=skfold,scoring=&#39;roc_auc&#39;).mean())<br>print(&#39;XGBoost CV Mean Score : &#39;,round(xgboost_cv, 3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*HRtVomCbfh2_kOcbGVKoOQ.png" /></figure><p><strong>5.2. Hyperparameter Tuning</strong></p><p>Since we obtain ROC-AUC ~74% from the Logistic Regression model, we would like to increase the model’s performance by using hyperparameter tuning. If the score improves, then the best parameters from this tuning will be used in the final model.</p><p><strong>Hyperparameter Tuning: Logistic Regression</strong></p><pre>lr_estimator = Pipeline([<br>    (&#39;model&#39;, logreg)])<br><br>hyperparam_space = {<br>    &#39;model__penalty&#39;: [&#39;l1&#39;, &#39;l2&#39;, &#39;elasticnet&#39;, &#39;none&#39;],<br>    &#39;model__C&#39;: [ 1, 0.5, 0.1, 0.05, 0.01],<br>    &#39;model__solver&#39;: [&#39;newton-cg&#39;, &#39;lbfgs&#39;, &#39;liblinear&#39;],<br>    &#39;model__class_weight&#39;: [None, &#39;balanced&#39;],<br>    &#39;model__max_iter&#39;: [100, 200, 300],<br>    &#39;model__multi_class&#39;: [&#39;auto&#39;, &#39;ovr&#39;, &#39;multinomial&#39;],<br>    &#39;model__random_state&#39;: [2022]<br>}<br><br>grid_lr = GridSearchCV(<br>                lr_estimator,<br>                param_grid = hyperparam_space,<br>                cv = StratifiedKFold(n_splits = 5),<br>                scoring = &#39;roc_auc&#39;,<br>                n_jobs = -1)<br><br>grid_lr.fit(x_s1_train, y_s1_train)<br><br>print(&#39;best score&#39;, grid_lr.best_score_)<br>print(&#39;best param&#39;, grid_lr.best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Jtf531-810ZXu6ZbSmAZPw.png" /></figure><p>best score 0.8398698781838316<br>best param {‘model__C’: 0.05, ‘model__class_weight’: ‘balanced’, ‘model__max_iter’: 100, ‘model__multi_class’: ‘multinomial’, ‘model__penalty’: ‘l2’, ‘model__random_state’: 2022, ‘model__solver’: ‘lbfgs’}</p><p>Here are the logistic regression’s best parameters for this case:<br>- C score is 0.05.<br>- The solver is lbfgs.<br>- The class_weight is balanced.<br>- The max_iter is 100.<br>- The multi_class is multinomial.<br>- The random_state is 2022.<br>- The model penalty is l2</p><pre>lr_estimator.fit(x_s1_train, y_s1_train)<br>roc_auc_logreg = (roc_auc_score(y_s1_test, lr_estimator.predict(x_s1_test)))<br><br>grid_lr.best_estimator_.fit(x_s1_train, y_s1_train)<br>roc_auc_grid = (roc_auc_score(y_s1_test, grid_lr.predict(x_s1_test)))<br><br>score_list = [roc_auc_logreg, roc_auc_grid]<br>method_name = [&#39;Logistic Regression Before Tuning&#39;, &#39;Logistic Regression After Tuning&#39;]<br>best_summary = pd.DataFrame({<br>    &#39;method&#39;: method_name,<br>    &#39;score&#39;: score_list<br>})<br>best_summary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*6uXQ4ATbX5CqG5GfSzrENw.png" /></figure><p>This is the comparison between the before-tuning score and the after-tuning score using Logistic Regression. There is no improvement in ROC AUC Score between the model results before and after hyperparameter tuning. We choose to use Logistic Regression before tuning the score in this section.</p><p><strong>Hyperparameter Tuning: Gradient Boosting</strong></p><pre>grad_estimator = Pipeline([<br>    (&#39;model&#39;, grad)])<br><br>hyperparam_space = {<br>    &#39;model__learning_rate&#39;: [1, 0.5, 0.1, 0.05, 0.01],<br>    &#39;model__n_estimators&#39;: [1, 16, 64, 200],<br>    &#39;model__max_depth&#39;: [int(x) for x in np.linspace(1,5,5,endpoint=True)],<br>    &#39;model__min_samples_split&#39;: np.linspace(0.1,1,5,endpoint=True),<br>    &#39;model__min_samples_leaf&#39;: np.linspace(0.1,0.5,5,endpoint=True),<br>    &#39;model__random_state&#39;: [2022]<br>}<br><br>grid_grad = GridSearchCV(<br>                grad_estimator,<br>                param_grid = hyperparam_space,<br>                cv = StratifiedKFold(n_splits = 5),<br>                scoring = &#39;roc_auc&#39;,<br>                n_jobs = -1)<br><br>grid_grad.fit(x_s1_train, y_s1_train)<br><br>print(&#39;best score&#39;, grid_grad.best_score_)<br>print(&#39;best param&#39;, grid_grad.best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*k4BF8QQOSlqLRLcBPTJEBA.png" /></figure><p>best score 0.8553979789590255<br>best param {‘model__learning_rate’: 0.1, ‘model__max_depth’: 2, ‘model__min_samples_leaf’: 0.1, ‘model__min_samples_split’: 0.325, ‘model__n_estimators’: 64, ‘model__random_state’: 2022}</p><p>Here’s Gradient Boosting’s best parameters for this case:<br>- learning_rate: 0.1<br>- max_depth: 2.0<br>- min_samples_leaf: 0.1<br>- min_samples_split: 0.325<br>- n_estimators: 64<br>- random_state’: 2022</p><pre>grad_estimator.fit(x_s1_train, y_s1_train)<br>roc_auc_grad = (roc_auc_score(y_s1_test, grad_estimator.predict(x_s1_test)))<br><br>grid_grad.best_estimator_.fit(x_s1_train, y_s1_train)<br>roc_auc_grid = (roc_auc_score(y_s1_test, grid_grad.predict(x_s1_test)))<br><br>score_list = [roc_auc_grad, roc_auc_grid]<br>method_name = [&#39;Gradient Boosting Before Tuning&#39;, &#39;Bradient Boosting After Tuning&#39;]<br>best_summary = pd.DataFrame({<br>    &#39;method&#39;: method_name,<br>    &#39;score&#39;: score_list<br>})<br>best_summary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*7BdLZ7qrv4xXEpoFgKm7QA.png" /></figure><p><strong>Hyperparameter Tuning: XGBoosting</strong></p><pre>xgb_estimator = Pipeline([<br>    (&#39;model&#39;, xgboost)])<br><br>hyperparam_space = {<br>    &#39;model__gamma&#39;: [0,0.1,1,10,100],<br>    &#39;model__learning_rate&#39;: [0.01, 0.1, 0.5, 0.7],<br>    &#39;model__max_depth&#39;: [5,10,14],<br>    &#39;model__n_estimators&#39;: [50,100,150],<br>    &#39;model__reg_alpha&#39;: [0,0.1,1,10,100],<br>    &#39;model__reg_lambda&#39;: [0,0.1,1,10,100]<br>}<br><br>grid_xgb = GridSearchCV(<br>                xgb_estimator,<br>                param_grid = hyperparam_space,<br>                cv = StratifiedKFold(n_splits = 5),<br>                scoring = &#39;roc_auc&#39;,<br>                n_jobs = -1)<br><br>grid_xgb.fit(x_s1_train, y_s1_train)<br><br>print(&#39;best score&#39;, grid_xgb.best_score_)<br>print(&#39;best param&#39;, grid_xgb.best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*7Me_nOmE6j-Ya4xOzlvZ_g.png" /></figure><p>best score 0.8528543743078627<br>best param {‘model__gamma’: 0, ‘model__learning_rate’: 0.1, ‘model__max_depth’: 5, ‘model__n_estimators’: 50, ‘model__reg_alpha’: 0, ‘model__reg_lambda’: 0.1}</p><p>Here are XGBoost’s best parameters for this case:<br>- gamma: 0<br>- learning_rate: 0.1<br>- max_depth: 5<br>- n_estimators: 50<br>- reg_alpha: 0<br>- reg_lambda: 0.1</p><pre>xgb_estimator.fit(x_s1_train, y_s1_train)<br>roc_auc_xgb = (roc_auc_score(y_s1_test, xgb_estimator.predict(x_s1_test)))<br><br>grid_xgb.best_estimator_.fit(x_s1_train, y_s1_train)<br>roc_auc_grid = (roc_auc_score(y_s1_test, grid_xgb.predict(x_s1_test)))<br><br>score_list = [roc_auc_xgb, roc_auc_grid]<br>method_name = [&#39;XGBoost Before Tuning&#39;, &#39;XGBoost After Tuning&#39;]<br>best_summary = pd.DataFrame({<br>    &#39;method&#39;: method_name,<br>    &#39;score&#39;: score_list<br>})<br>best_summary</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*uNB_OU1P_iLSemT4z9ggDg.png" /></figure><p><strong>5.3. Trial using Undersampling and Oversampling</strong></p><pre>def calc_train_error(x_train, y_train, model):<br>#     &#39;&#39;&#39;returns in-sample error for already fit model.&#39;&#39;&#39;<br>    predictions = model.predict(x_train)<br>    roc_auc = roc_auc_score(y_train, predictions)<br>    return { <br>        &#39;roc&#39;: roc_auc, <br>    }<br>    <br>def calc_validation_error(x_test, y_test, model):<br>#     &#39;&#39;&#39;returns out-of-sample error for already fit model.&#39;&#39;&#39;<br>    predictions = model.predict(x_test)<br>    roc_auc = roc_auc_score(y_test, predictions)<br>    return { <br>        &#39;roc&#39;: roc_auc, <br>    }<br>    <br>def calc_metrics(x_train, y_train, x_test, y_test, model):<br>#     &#39;&#39;&#39;fits model and returns the in-sample error and out-of-sample error&#39;&#39;&#39;<br>    model.fit(x_train, y_train)<br>    train_error = calc_train_error(x_train, y_train, model)<br>    validation_error = calc_validation_error(x_test, y_test, model)<br>    return train_error, validation_error</pre><pre>data = x_s1_train<br>target = y_s1_train<br><br>train_errors_without_oversampling = []<br>validation_errors_without_oversampling = []<br><br>train_errors_with_oversampling = []<br>validation_errors_with_oversampling = []<br><br>train_errors_with_undersampling = []<br>validation_errors_with_undersampling = []<br><br>train_errors_with_smote = []<br>validation_errors_with_smote = []<br><br># print(len(x_val), (len(x_train) + len(x_val)))<br>ros = RandomOverSampler(random_state=2022)<br>rus = RandomUnderSampler(random_state=2022)<br><br>    <br>for train_index, val_index in skfold.split(data, target):<br>    <br>    # split data<br>    x_train, x_val = data.iloc[train_index], data.iloc[val_index]<br>    y_train, y_val = target.iloc[train_index], target.iloc[val_index]<br><br>    X_ros, Y_ros = ros.fit_resample(x_s1_train, y_s1_train)<br>    X_rus, Y_rus = rus.fit_resample(x_s1_train, y_s1_train)<br><br>    # instantiate model ros<br>    ros_estimator = Pipeline([<br>        (&#39;balancing&#39;,ros),<br>        (&#39;model&#39;,logreg)])<br><br>    # instantiate model rus<br>    rus_estimator = Pipeline([<br>        (&#39;balancing&#39;,rus),<br>        (&#39;model&#39;,logreg)])<br><br>    #calculate errors<br>    train_error_without_oversampling, val_error_without_oversampling = calc_metrics(x_train, y_train, x_val, y_val, lr_estimator)<br>    train_error_with_oversampling, val_error_with_oversampling = calc_metrics(X_ros, Y_ros, x_val, y_val, ros_estimator)<br>    train_error_with_undersampling, val_error_with_undersampling = calc_metrics(X_rus, Y_rus, x_val, y_val, rus_estimator)<br><br>    # append to appropriate list<br>    train_errors_without_oversampling.append(train_error_without_oversampling)<br>    validation_errors_without_oversampling.append(val_error_without_oversampling)<br>    <br>    train_errors_with_oversampling.append(train_error_with_oversampling)<br>    validation_errors_with_oversampling.append(val_error_with_oversampling)<br><br>    train_errors_with_undersampling.append(train_error_with_undersampling)<br>    validation_errors_with_undersampling.append(val_error_with_undersampling)</pre><p><strong>No Treatment</strong></p><pre>listItem_notreat = []<br><br>for tr,val in zip(train_errors_without_oversampling,validation_errors_without_oversampling) :<br>    listItem_notreat.append([tr[&#39;roc&#39;],val[&#39;roc&#39;]])<br><br>listItem_notreat.append(list(np.mean(listItem_notreat,axis=0)))<br>listItem_notreat.append(list(np.std(listItem_notreat,axis=0)))<br>    <br>dfEvaluate_notreat = pd.DataFrame(listItem_notreat, <br>                     columns=[&#39;Train ROC AUC&#39;, <br>                              &#39;Test ROC AUC&#39;, <br>                             ])<br><br>listIndex = list(dfEvaluate_notreat.index)<br>listIndex[-2] = &#39;Average&#39;<br>listIndex[-1] = &#39;Std&#39;<br>dfEvaluate_notreat.index = listIndex</pre><p><strong>Undersampling</strong></p><pre>listItem_rus = []<br><br>for tr,val in zip(train_errors_with_undersampling,validation_errors_with_undersampling) :<br>    listItem_rus.append([tr[&#39;roc&#39;],val[&#39;roc&#39;]])<br><br>listItem_rus.append(list(np.mean(listItem_rus,axis=0)))<br>listItem_rus.append(list(np.std(listItem_rus,axis=0)))<br>    <br>dfEvaluate_rus = pd.DataFrame(listItem_rus, <br>                    columns=[<br>                            &#39;Train ROC AUC&#39;, <br>                            &#39;Test ROC AUC&#39;, <br>                            ])<br><br>listIndex = list(dfEvaluate_rus.index)<br>listIndex[-2] = &#39;Average&#39;<br>listIndex[-1] = &#39;Std&#39;<br>dfEvaluate_rus.index = listIndex<br><br>rus_estimator.fit(X_rus, Y_rus)<br>y_predict_rus = rus_estimator.predict(x_s1_test)</pre><p><strong>Oversampling</strong></p><pre>listItem_ros = []<br><br>for tr,val in zip(train_errors_with_oversampling,validation_errors_with_oversampling) :<br>    listItem_ros.append([tr[&#39;roc&#39;],val[&#39;roc&#39;]])<br><br>listItem_ros.append(list(np.mean(listItem_ros,axis=0)))<br>listItem_ros.append(list(np.std(listItem_ros,axis=0)))<br>    <br>dfEvaluate_ros = pd.DataFrame(listItem_ros, <br>                    columns=[<br>                            &#39;Train ROC AUC&#39;, <br>                            &#39;Test ROC AUC&#39;, <br>                            ])<br><br>listIndex = list(dfEvaluate_ros.index)<br>listIndex[-2] = &#39;Average&#39;<br>listIndex[-1] = &#39;Std&#39;<br>dfEvaluate_ros.index = listIndex<br><br>ros_estimator.fit(X_ros, Y_ros)<br>y_predict_ros = ros_estimator.predict(x_s1_test)</pre><p><strong>Comparison</strong></p><pre>print(&#39;No Treatment&#39;)<br>print(confusion_matrix(y_s1_test, lr_estimator.predict(x_s1_test)))<br>print(&#39;Logistic Regression_NoTreat ROC-AUC Score : &#39;, round(roc_auc_score(y_s1_test, lr_estimator.predict(x_s1_test)),3)*100,&#39;%&#39;)<br><br>lr_cv = (cross_val_score(lr_estimator,x_train,y_train,cv=skfold,scoring=&#39;roc_auc&#39;).mean())<br>print(&#39;Logistic Regression_NoTreat CV Mean Score : &#39;, round(lr_cv,3))<br><br>print(&#39;\n\nRandom Over Sampling&#39;)<br>print(confusion_matrix(y_s1_test, y_predict_ros))<br>print(&#39;Logistic Regression_ROS ROC-AUC Score     : &#39;, round(roc_auc_score(y_s1_test, y_predict_ros),3)*100,&#39;%&#39;)<br>print(&#39;Logistic Regression_ROS CV Mean Score     : &#39;, round(lr_cv_ros,3))<br><br>print(&#39;\n\nRandom Under Sampling&#39;)<br>print(confusion_matrix(y_s1_test, y_predict_rus))<br>print(&#39;Logistic Regression_RUS ROC-AUC Score     : &#39;, round(roc_auc_score(y_s1_test, y_predict_rus),3)*100,&#39;%&#39;)<br>print(&#39;Logistic Regression_RUS CV Mean Score     : &#39;, round(lr_cv_rus,3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*gUka314cqEyVivLZS5BSNw.png" /></figure><p><strong>5.4. Feature Selection</strong></p><pre>features = x_s1_train.columns<br>coef_table = pd.DataFrame({&#39;coef&#39;: grid_lr.best_estimator_[0].coef_.flatten()}, index = features)<br>grid_logreg = abs(coef_table).sort_values(&#39;coef&#39;, ascending = False)<br><br>grid_logreg<br><br>plt.figure(figsize=(10,8))<br>sns.barplot(x=grid_logreg[&#39;coef&#39;], y=grid_logreg.index[0:], palette=&quot;rocket&quot;)<br>sns.despine()<br>plt.xlabel(&quot;Feature Importances&quot;)<br>plt.ylabel(&quot;Features&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*OOS-NKSOj15ldStSTgo6dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*iJRJYvMTa_QgRF5VVvTxBA.png" /></figure><p>Based on selecting features through the coefficient score, We decided to drop 2 features manually and get a score under 0.1 for all answer choices for every feature. There are insulin and skin_thickness.</p><p><strong>5.5. Re-run using feature selection</strong></p><p>Preprocessing Scheme<br>- RobustScaler: pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree, age.<br>- Target: y</p><pre>df_tuning = df.copy()<br>df_tuning.drop(columns = [&#39;insulin&#39;, &#39;skin_thickness&#39;], inplace = True)<br><br>x_select = df_tuning.drop(&#39;y&#39;, axis = 1)<br>y_select = df_tuning[&#39;y&#39;]<br><br>x_select_train, x_select_test, y_select_train, y_select_test = train_test_split(x_select,y_select, stratify = y_select, test_size = 0.2, random_state = 2022)<br><br>logreg_tuning = LogisticRegression(C = 0.05, class_weight = &#39;balanced&#39;, max_iter = 100, multi_class = &#39;multinomial&#39;, random_state = 2022, solver = &#39;lbfgs&#39;, penalty=&#39;l2&#39;)<br>logreg_select_pipe = Pipeline([(&#39;model&#39;, logreg_tuning)])<br>logreg_select_pipe.fit(x_select_train, y_select_train)<br>print(&#39;After Feature Selection Process, the score is &#39;, roc_auc_score(y_select_test, logreg_select_pipe.predict(x_select_test)))</pre><p>After the Feature Selection Process, the score is 0.7438888888888888</p><p>The score used as a reference for predicting is 0.7439, which is larger than the tuning score before (0.7433).</p><p><strong>5.6. Other Optimization Model</strong></p><p>Logistic Threshold Optimization</p><pre>df_th = df.copy()<br>x_th = df_th.drop([&#39;insulin&#39;, &#39;skin_thickness&#39;,&#39;y&#39;], axis = 1)<br>y_th = df_th[&#39;y&#39;]<br>x_th_train, x_th_test, y_th_train, y_th_test = train_test_split(x_th, y_th,<br>                                                   stratify = y_th,<br>                                                    test_size = 0.2,<br>                                                   random_state = 2022)</pre><p>best score 0.8399889258028793<br>best param {‘model__C’: 0.05, ‘model__class_weight’: ‘balanced’, ‘model__max_iter’: 100, ‘model__multi_class’: ‘multinomial’, ‘model__penalty’: ‘l2’, ‘model__random_state’: 2022, ‘model__solver’: ‘lbfgs’}</p><pre>logreg_treshold = LogisticRegression(C = 0.05, class_weight = &#39;balanced&#39;, max_iter = 100,<br>                                   multi_class = &#39;multinomial&#39;, random_state = 2022, solver = &#39;lbfgs&#39;, penalty=&#39;l2&#39;)<br>logreg_pipe_treshold = Pipeline([(&#39;model&#39;, logreg)])<br>model = logreg_pipe_treshold.fit(x_th_train, y_th_train)<br><br>th_value = [i/100 for i in range(20,61)]<br>score = 0<br>score_list = []<br><br>for i in th_value:<br>    # perhitungan score<br>    y_prob = model.predict_proba(x_th_test)[:,1]<br>    y_pred = np.where(y_prob&gt;i, 1, 0)<br>    score_temp = roc_auc_score(y_th_test, y_pred)<br>    <br>    # penyimpanan hasil score<br>    score_list.append(score_temp)<br>    <br>    # comparasi: penentuan score terbaik<br>    if score_temp &gt; score:<br>        score = score_temp<br>        best_th = i<br><br>print(&#39;best score = &#39;,score)<br>print(&#39;best threshold = &#39;,best_th)</pre><p>best score = 0.7483333333333332<br>best threshold = 0.47</p><pre>sns.lineplot(x=th_value, y=score_list)<br>plt.xlabel(&#39;Treshold&#39;)<br>plt.ylabel(&#39;roc_auc&#39;)<br>plt.title(&#39;Optimasi Treshold&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*VlGGnSFMmXil2yX03apwLA.png" /></figure><pre>logreg_final = LogisticRegression(C = 0.05, class_weight = &#39;balanced&#39;, max_iter = 100,<br>                                   multi_class = &#39;multinomial&#39;, random_state = 2022, solver = &#39;lbfgs&#39;, penalty=&#39;l2&#39;)<br>logreg_final_pipe = Pipeline([(&#39;model&#39;, logreg_final)])<br>logreg_final_pipe.fit(x_select_train, y_select_train)<br>print(&#39;After Feature Selection Process, the score is &#39;, roc_auc_score(y_select_test, logreg_final_pipe.predict(x_select_test)))</pre><p>After the Feature Selection Process, the score is 0.7438888888888888</p><pre>evaluation_metrics = [&#39;Accuracy&#39;,&#39;precision&#39;,&#39;recall&#39;,&#39;F1 Score&#39;,&#39;ROC-AUC&#39;]<br>evaluation_value = [<br>    round(accuracy_score(y_select_test, logreg_final_pipe.predict(x_select_test))*100,2),<br>    round(precision_score(y_select_test, logreg_final_pipe.predict(x_select_test))*100,2),<br>    round(recall_score(y_select_test, logreg_final_pipe.predict(x_select_test))*100,2),<br>    round(f1_score(y_select_test, logreg_final_pipe.predict(x_select_test))*100,2),<br>    round(roc_auc_score(y_select_test, logreg_final_pipe.predict(x_select_test))*100,2)<br>]<br><br>final_score = pd.DataFrame(index=evaluation_metrics, data=evaluation_value, columns=[&#39;Score&#39;]).T<br>final_score<br><br>disp = ConfusionMatrixDisplay(confusion_matrix(y_select_test, logreg_final_pipe.predict(x_select_test)))<br>disp.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*QVehCS_Wpg6eTbL9LsaC2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*B1qOO_K8oy7LLOepke9m0A.png" /></figure><p><strong>Overall Performance:</strong><br>The accuracy of 73.38% means that out of every 100 predictions made by the model, approximately 73 of them are correct. This indicates a reasonably good classifier, especially if it’s an initial or baseline model.</p><p><strong>Precision vs. Recall:</strong><br>Precision of 59.15%: Out of all the cases where the model predicted diabetes, about 59% of them were true positives, while the rest were false positives. It’s a moderate value, implying there might be a noticeable number of false alarms.<br>Recall of 77.78%: Out of all the actual diabetes cases, the model was able to identify nearly 78% of them. This is a fairly high recall, indicating that the model is well-tuned to not miss out on actual positive cases.</p><p><strong>F1 Score:</strong><br>An F1 score of 67.2% is the harmonic mean of precision and recall. It provides a single metric that balances the trade-off between precision and recall. This value is decent and indicates a somewhat balanced classifier in terms of false positives and false negatives.</p><p><strong>ROC-AUC Score:</strong><br>The ROC-AUC Score of 74.39% is a metric that evaluates the classifier’s ability to distinguish between the positive and negative classes. A value of 74.39% indicates a good capability to differentiate between the two classes, especially given that a score of 50% would be no better than random guessing.</p><pre>#define metrics<br>y_pred_proba = logreg_final_pipe.predict_proba(x_select_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_select_test,  y_pred_proba)<br><br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*wOMKVKeQS-2i6WNh3CPAMg.png" /></figure><p><strong>6. DEPLOYMENT</strong></p><p>I’m deploying this model using Streamlit, I’ll write the detailed tutorial for this part in a different article. Just stick around!</p><p><strong>7. CONCLUSION</strong></p><p>Based on this project, we can conclude that:<br>1. The best model that can be created to predict whether someone will develop diabetes is a logistic regression model with the following hyperparameters:<br>- C score is 0.05.<br>- The solver is lbfgs.<br>- The class_weight is balanced.<br>- The max_iter is 100.<br>- The multi_class is multinomial.<br>- The random_state is 2022.<br>- The model penalty l2<br>The score result is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*QVehCS_Wpg6eTbL9LsaC2Q.png" /></figure><p>The model is fairly good at identifying true diabetes cases (as indicated by the high recall) but at the cost of producing a moderate number of false alarms (as seen by the precision value). The ROC-AUC score above 70% is promising and suggests the model has a good understanding of the underlying patterns in the data.<br>2. The features chosen to make this prediction are: Pregnancies , Glucose, BloodPressure, SkinThickness, Insulin, BMI, DiabetesPedigreeFunction, andAge.<br>3. Deployment this model using Streamlit.</p><p><strong>8. RECOMMENDATION</strong></p><p>1. <strong>Feature Engineering</strong>: Besides our feature engineering in BMI, Blood Pressure, Insulin, and Glucose class, Consider adding new features or transforming other existing ones to improve the model’s performance.<br>2. <strong>Model Complexity</strong>: While logistic regression is a simple and interpretable model, it might not be able to capture all the patterns in the data. Consider trying more complex models like Random Forest or Gradient Boosting, but remember to always use logistic regression as a baseline for comparison.<br>3. Resampling: Although we tried using undersampling and oversampling methods which did not significantly affect to model result, we need to try to use another method like the Synthetic Minority Over-sampling Technique (SMOTE) to handle imbalance even though the outcome proporsion actually fairly balanced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a84ef32b947c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why We Need to Do Regularization in Decision Tree Machine Learning?]]></title>
            <link>https://medium.com/@deryl.baharudin/why-we-need-to-do-regularization-in-decision-tree-machine-learning-70e77ac48b79?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e77ac48b79</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 16:57:06 GMT</pubDate>
            <atom:updated>2023-09-14T16:57:06.764Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science: Machine Learning</h4><p>Enhancing Model Stability and Performance with Scikit-learn Techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9eTkaFohYSgAsC5PFyIpQ.png" /><figcaption>Photo on <a href="https://scikit-learn.org/stable/auto_examples/neural_networks/plot_mlp_alpha.html">scikit-learn</a></figcaption></figure><h4><strong>1. Overfitting and Decision Trees</strong></h4><p>Decision trees, by their very nature, are prone to overfitting, especially when they are deep. Overfitting occurs when a model captures noise or fluctuations in the training data that do not represent the underlying data distribution. In the context of decision trees, overfitting can mean creating too many branches based on outliers or anomalies in the training data.</p><p><strong>Why is this problematic?</strong></p><p>A tree that is too complex might achieve a perfect accuracy score on the training data but perform poorly on new, unseen data. Such a tree has low bias but high variance, and its predictions can be unstable.</p><h4><strong>2. Regularization as a Solution</strong></h4><p>Regularization techniques add constraints to the learning algorithm, reducing its freedom and, hence, its capacity to overfit. For decision trees, regularization is achieved by controlling the tree’s depth and complexity.</p><p><strong>Key regularization techniques for decision trees include:</strong></p><ul><li>Maximum Depth (max_depth): Setting a limit on how deep the tree can grow. This is one of the most straightforward regularization methods. A shallow tree will likely underfit, and a very deep tree will likely overfit, so finding a balanced depth is crucial.</li><li>Minimum Samples Split (min_samples_split): This hyperparameter ensures that a node must have a minimum number of samples before it can be split. This can prevent tiny splits that capture noise.</li><li>Minimum Samples Leaf (min_samples_leaf): This ensures that a terminal node (leaf) has a minimum number of samples. This can be particularly useful to prevent the final class decisions from relying on a tiny subset of the data.</li><li>Maximum Features (max_features): By setting a limit on the number of features considered for splitting, you can add a form of feature regularization.</li><li>Pruning: Some algorithms, like cost complexity pruning, allow for the removal of parts of the tree that do not provide power in predicting the target values.</li></ul><h4><strong>3. Striking the Right Balance</strong></h4><p>The key challenge in regularization is striking a balance between underfitting and overfitting. Under-regularized trees might be too deep and capture noise (overfit), while over-regularized trees might be too shallow and miss important patterns (underfit).</p><p>Regularization parameters should ideally be determined using cross-validation or a separate validation dataset, ensuring that the settings generalize well to new data.</p><h3><strong>Study Case: The Significance of Regularization</strong></h3><h4><strong>A Decision Tree Study Case with the UCI Adult Dataset</strong></h4><h4>Introduction:</h4><p>In our endeavor to demystify the power of regularization in decision trees, we dive deep into the “Adult” dataset from UCI’s Machine Learning Repository. This dataset, rich with over 32,000 instances and 14 attributes, predicts whether an individual’s income exceeds $50k annually, given attributes like age, education, and work status.</p><h4>Why this Dataset?</h4><p>The complexity and size of the Adult dataset make it an ideal candidate to demonstrate the tangible benefits of regularization. Unlike smaller datasets, like iris or wine, the Adult dataset gives our model ample opportunity to overfit - to capture noise instead of just the underlying patterns.</p><pre>import pandas as pd<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.model_selection import train_test_split<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.metrics import accuracy_score<br><br># Load the Adult dataset<br>url = &quot;https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data&quot;<br>column_names = [&#39;age&#39;, &#39;workclass&#39;, &#39;fnlwgt&#39;, &#39;education&#39;, &#39;education-num&#39;, &#39;marital-status&#39;, &#39;occupation&#39;,<br>                &#39;relationship&#39;, &#39;race&#39;, &#39;sex&#39;, &#39;capital-gain&#39;, &#39;capital-loss&#39;, &#39;hours-per-week&#39;, &#39;native-country&#39;, &#39;income&#39;]<br>data = pd.read_csv(url, names=column_names, sep=&quot;\s*,\s*&quot;, engine=&quot;python&quot;)<br><br># Preprocess: Convert categorical variables into numeric<br>le = LabelEncoder()<br>for column in data.columns:<br>    if data[column].dtype == &#39;object&#39;:<br>        data[column] = le.fit_transform(data[column])<br><br>X = data.drop(&#39;income&#39;, axis=1)<br>y = data[&#39;income&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><h4>Regularization in Action:</h4><p>Without Regularization: We first trained a decision tree without any constraints. The model is free to grow, fit every minutiae of the training data, and, as we often find, risk overfitting.</p><pre># Train a decision tree without regularization<br>clf = DecisionTreeClassifier(random_state=42)<br>clf.fit(X_train, y_train)<br><br># Predict and calculate accuracy<br>y_pred = clf.predict(X_test)<br>print(&quot;Accuracy without regularization:&quot;, accuracy_score(y_test, y_pred))</pre><p>Accuracy without regularization: 0.8131845634148838</p><p>With Regularization: We then constrained our decision tree with regularization, setting parameters like max_depth, min_samples_split, and min_samples_leaf. These constraints intentionally limit the tree&#39;s growth, preventing it from fitting to every detail (and noise) in the training data.</p><pre># Train a decision tree with regularization<br>clf_reg = DecisionTreeClassifier(max_depth=10, min_samples_split=100, min_samples_leaf=50, random_state=42)<br>clf_reg.fit(X_train, y_train)<br><br># Predict and calculate accuracy<br>y_pred_reg = clf_reg.predict(X_test)<br>print(&quot;Accuracy with regularization:&quot;, accuracy_score(y_test, y_pred_reg))</pre><p>Accuracy with regularization: 0.8554611526256526</p><h4>Results:</h4><p>Our non-regularized model, while achieving commendable accuracy on the training set, faltered on the unseen test data. The model, without constraints, had become a victim of its enthusiasm, fitting more to the noise than the actual data patterns.</p><p>In contrast, our regularized model, even with its constrained growth, performed noticeably better on the test data. It’s a testament to the power of regularization — by curbing the tree’s growth, we enhanced its ability to generalize to new, unseen data.</p><h4><strong>Concluding Thoughts:</strong></h4><p>The Adult dataset serves as a reminder that machine learning&#39;s goal isn&#39;t solely about achieving high training accuracy. It&#39;s about creating models that can generalize well to new scenarios. While regularization might feel like we&#39;re holding our model back, it&#39;s often the difference between a model that&#39;s narrowly accurate and one that&#39;s broadly effective. Regularization ensures that our models are not just learners, but wise generalists, making them more resilient and robust in real-world applications.</p><h4><strong>Conclusion</strong></h4><p>Regularization is essential for decision tree models due to their natural propensity to overfit. By understanding and appropriately tuning regularization hyperparameters, one can develop more robust and generalizable decision tree models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e77ac48b79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Root to Leaves: Mastering Decision Trees in Machine Learning]]></title>
            <link>https://medium.com/@deryl.baharudin/from-root-to-leaves-mastering-decision-trees-in-machine-learning-175167282a3b?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/175167282a3b</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 16:26:15 GMT</pubDate>
            <atom:updated>2023-09-14T16:58:49.257Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science: Machine Learning</h4><p><em>A Journey through Hierarchical Decision-Making and Model Interpretability with Scikit-learn</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrKXTZV1XKRFVFYBemt01g.jpeg" /><figcaption>Photo on <a href="https://www.xoriant.com/blog/decision-trees-for-classification-a-machine-learning-algorithm">xoriant.com</a></figcaption></figure><p><strong>Introduction</strong></p><p>Decision trees are one of the most intuitive and versatile machine learning algorithms. They mimic human decision-making processes, making them not only effective but also interpretable. With Scikit-learn, implementing a decision tree becomes an effortless task. In this article, we will dive deep into decision tree classification using Scikit-learn.</p><p><strong>1. What is a Decision Tree?</strong></p><p>At its core, a decision tree is a flowchart-like structure in which each internal node represents a feature, each branch represents a decision rule, and each leaf node represents an outcome. It works in a top-down manner, making decisions based on asking a series of questions.</p><p><strong>2. Implementing with Scikit-learn</strong></p><p><strong>a. Installation &amp; Setup</strong></p><p>Before diving into the code, make sure you have Scikit-learn installed:</p><pre>pip install scikit-learn</pre><p><strong>b. Code Basics</strong></p><p>To get started with decision tree classification:</p><pre>from sklearn.tree import DecisionTreeClassifier</pre><p><strong>3. Training a Decision Tree Classifier</strong></p><p>Using the famous Iris dataset, here’s a simple implementation:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br><br># Load the dataset<br>data = load_iris()<br>X = data.data<br>y = data.target<br><br># Splitting the dataset<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)<br><br># Training the classifier<br>clf = DecisionTreeClassifier()<br>clf.fit(X_train, y_train)</pre><p><strong>4. Making Predictions</strong></p><p>Once trained, the model can predict the class labels of new data:</p><pre>y_pred = clf.predict(X_test)</pre><p><strong>5. Evaluating the Model</strong></p><p>Scikit-learn also provides tools to evaluate your classifier, such as accuracy score:</p><pre>from sklearn.metrics import accuracy_score<br>print(accuracy_score(y_test, y_pred))</pre><p><strong>6. Visualizing the Decision Tree</strong></p><p>Scikit-learn integrates seamlessly with the Graphviz library to visualize the trained decision tree.</p><pre>from sklearn.tree import export_graphviz<br>import graphviz<br><br>dot_data = export_graphviz(clf, out_file=None, feature_names=data.feature_names,  <br>                           class_names=data.target_names, filled=True)<br>graph = graphviz.Source(dot_data)<br>graph.view()</pre><p><strong>7. Hyperparameters Tuning</strong></p><p>In the context of machine learning, hyperparameters are parameters whose values are set before training a model. They are not updated during training. Hyperparameter tuning, then, is the process of systematically searching for the best combination of hyperparameters that produces the optimal model.</p><p>Scikit-learn’s decision tree classifier comes with various hyperparameters like criterion (to specify the measure for quality of a split), max_depth (maximum depth of the tree), min_samples_split (minimum samples required to split an internal node), and more. Exploring these can help optimize the model.</p><p><strong>Key Hyperparameters for Decision Trees</strong></p><ul><li>criterion: This determines the function to measure the quality of a split. For classification, it can be “gini” (Gini impurity) or “entropy” (information gain). For regression, it can be “mse” (mean squared error), “friedman_mse”, or “mae” (mean absolute error).</li><li>splitter: Defines the strategy to choose the split at each node. Choices are “best” (best split) or “random” (best random split).</li><li>max_depth: The maximum depth of the tree. It can be used to control overfitting. Deeper trees capture more specific patterns which might only be noise.</li><li>min_samples_split: The minimum number of samples required to split an internal node. Increasing this can reduce overfitting.</li><li>min_samples_leaf: The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf samples in each of the left and right branches.</li><li>max_features: The number of features to consider when looking for the best split.</li></ul><p><strong>Methods for Hyperparameter Tuning</strong></p><ul><li>Grid Search: This method involves exhaustively searching through a specified subset of hyperparameters. Using Scikit-learn, the GridSearchCV function can be employed to perform this search.</li></ul><pre>from sklearn.model_selection import GridSearchCV<br><br>parameters = {<br>    &#39;criterion&#39;: [&#39;gini&#39;, &#39;entropy&#39;],<br>    &#39;max_depth&#39;: [None, 10, 20, 30, 40, 50],<br>    &#39;min_samples_split&#39;: [2, 5, 10],<br>    &#39;min_samples_leaf&#39;: [1, 2, 4]<br>}<br><br>grid_search = GridSearchCV(DecisionTreeClassifier(), parameters, cv=5)<br>grid_search.fit(X_train, y_train)<br>best_params = grid_search.best_params_</pre><ul><li>Random Search: Instead of trying out every possible combination of hyperparameters, random search selects random combinations to train the model and score. This strategy can be more efficient. Scikit-learn provides the RandomizedSearchCV function for this purpose.</li><li>Bayesian Optimization: A probabilistic model-based optimization technique, Bayesian optimization chooses the next hyperparameters in a way that exploits the already sampled hyperparameters to spend more time where the model might perform better.</li></ul><p><strong>Importance of Cross-validation</strong></p><p>While tuning hyperparameters, it’s crucial to use cross-validation. This ensures that the chosen hyperparameters generalize well to unseen data. Typically, k-fold cross-validation is used, where the training data is split into k subsets, and the model is trained on k-1 of those subsets and validated on the remaining subset. This process is repeated k times, and the model’s performance is averaged.</p><p><strong>Overfitting and Regularization</strong></p><p>While tuning, it’s essential to be cautious of overfitting, where the model performs exceptionally well on the training data but poorly on unseen data. Regularizing hyperparameters like max_depth, min_samples_split, and min_samples_leaf can help in reducing overfitting.</p><p>Hyperparameter tuning is crucial for deriving the maximum performance from decision trees and most machine learning models. The key lies in understanding the role of each hyperparameter and efficiently searching the hyperparameter space to find the best combination.</p><p><strong>8. Advantages of Decision Trees in Scikit-learn</strong></p><ul><li>Intuitive and Visual: Easily visualized and interpreted.</li><li>Minimal Data Preprocessing: This doesn’t require data normalization or dummy variables.</li><li>Handles Both Numerical and Categorical Data: Although in Scikit-learn, you’d need to convert categorical data into numerical form first.</li></ul><p><strong>9. Limitations</strong></p><ul><li>Overfitting: Without proper tuning, decision trees can become overly complex and overfit to the training data.</li><li>Sensitive to Data Variations: Small changes in the data can result in a different tree structure.</li></ul><p><strong>10. Practical Tips</strong></p><ul><li>Regularization: Use parameters like max_depth, min_samples_split to regularize the tree and prevent overfitting. (Read more about <a href="https://medium.com/@deryl.baharudin/why-we-need-to-do-regularization-in-decision-tree-machine-learning-70e77ac48b79">why it is important to consider using regularization in decision tree</a>)</li><li>Cross-validation: Essential for hyperparameter tuning and getting a generalized model.</li></ul><p><strong>Conclusion</strong></p><p>Decision tree classifiers are a foundational algorithm in the machine learning toolkit. With Scikit-learn, the process of training, evaluating, and visualizing decision trees is streamlined. Whether you’re tackling a simple binary classification problem or a multi-class problem, Scikit-learn’s decision tree classifier is a powerful tool to have in your arsenal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=175167282a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching Numbers & Saving Lives: My Journey with Diabetes Prediction (Part 1)]]></title>
            <link>https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-1-41b6bafd13f1?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b6bafd13f1</guid>
            <category><![CDATA[pima-indians]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[diabetes]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 13:29:09 GMT</pubDate>
            <atom:updated>2023-10-12T05:36:35.955Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science: Tutorial Supervised Machine Learning</h4><blockquote>The battle against diabetes is intensifying. With the rich data from the Pima Indians community, we’re tapping into machine learning to uncover insights and predict risks like never before. Join me in this deep dive into how technology is reshaping our approach to diabetes prevention and care.</blockquote><p>Check out my YouTube video on the project “Diabetes Prediction using the Pima Indian Dataset” below if you’re interested.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdlYicY9Rqxo%3Fstart%3D1231%26feature%3Doembed%26start%3D1231&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdlYicY9Rqxo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdlYicY9Rqxo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc46d533c5c9f6ee76e7e480494c2cb7/href">https://medium.com/media/fc46d533c5c9f6ee76e7e480494c2cb7/href</a></iframe><p><strong>Table of Contents:</strong></p><ol><li><a href="#f05a">BUSINESS PROBLEM AND DATA UNDERSTANDING</a><br>1.1. <a href="#96ad">Context</a><br>1.2. <a href="#ab9d">Define Business Problem</a><br>1.3. <a href="#11f2">Data Understanding</a></li><li><a href="#e30e">DATA CONDITIONING</a></li><li><a href="#1c46">EXPLORATORY DATA ANALYSIS (EDA)</a><br>3.1. <a href="#405c">Missing Value, Anomaly, Outlier, and Duplicated Data Detection</a><br>3.2. <a href="#cf81">Feature Engineering</a><br>3.3. <a href="#b66b">Univariate Analysis</a><br>3.4. <a href="#4ba8">Bivariate Analysis</a><br>3.5. <a href="#cac3">Multivariate Analysis</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">DATA PRE-PROCESSING</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">MODELING</a><br>5.1. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Model Benchmarking</a><br>5.2. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Hyperparameter Tuning</a><br>5.3. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Trial using Undersampling and Oversampling</a><br>5.3. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Feature Selection</a><br>5.4. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Re-run using Feature Selection</a><br>5.5. <a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Other Optimization Model</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">DEPLOYMENT</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">CONCLUSION</a></li><li><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">RECOMMENDATION</a></li></ol><p>You can access the full code on my GitHub.</p><p><a href="https://github.com/derylbaharudin/diabetes-prediction">GitHub - derylbaharudin/diabetes-prediction: Pima Indian Diabetes Prediction (Classification Supervised Machine Learning)</a></p><p><strong>1. BUSINESS PROBLEM AND DATA UNDERSTANDING</strong></p><p><strong>1.1. Context</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*HTTj-FXAcQL-IURweac13Q.jpeg" /><figcaption>Photo on <a href="https://en.wikipedia.org/wiki/Akimel_O%27odham#/media/File:Pima.jpg">Wikipedia</a></figcaption></figure><p>This dataset is provided by Digital Skola which is taken from the original version of the National Institute of Diabetes and Digestive and Kidney Diseases. The objective is to predict based on diagnostic measurements whether a patient has diabetes. Several constraints were placed on the selection of these instances from a larger database. In particular, all patients here are females at least 21 years old of Pima Indian heritage.</p><p><strong>1.2. Define Business Problem</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*qfo5hwgH6dXOT1gyFsb9vw.jpeg" /><figcaption>Photo on <a href="https://www.alodokter.com/kondisi-darurat-pada-diabetes-dan-gejalanya">Alodokter</a></figcaption></figure><p><strong>Problem</strong></p><p>The Pima Indians have the highest rate of type 2 diabetes in the world. While biomedical studies have identified a genetic variable associated with the high prevalence of diabetes among Pima Indians, genetics is only one factor that encompasses an individual’s risk for developing a disease. Information on the social factors relating to the development of type 2 diabetes in this population is necessary. While genetic factors have been shown to be important predictors of diabetes incidence, the historical and social factors that changed US Pima Indians’ lifestyles are significant factors that have contributed to the high prevalence of diabetes among this group. The dataset gives some characteristics (pregnancies, blood pressure, insulin level, etc.) related to people who either have diabetes or do not.<br>Source: <a href="https://core.ac.uk/">CORE UK</a></p><p>Based on this background, this problem is classified as a classification problem. We will create a predictive model for this classification problem using machine learning. In machine learning, there are two classes, Supervised learning and unsupervised learning. For this classification problem, we use supervised learning because this dataset has binary diabetes labels.</p><p><strong>Goals</strong></p><p>It would be better and more effective if each patient knew whether have diabetes or not, so they can maximize the treatment for better conditions in the future.</p><p>The goals are:<br>1. Create a machine learning model to predict patients who most likely have diabetes, so they can maximize treatment for diabetics thus that their health condition is better in the future. Our target is to create machine learning with good performance to predict a patient’s diabetic diagnosis.<br>2. Find out which factors that can influence a diabetic diagnosis, so that patient can determine more effective future handling based on their condition.<br>3. Deploy the model that has been made into a website-based system to make predictions.</p><p><strong>Analytics Approach</strong></p><p>These are the following steps that will be performed to complete the task:<br>1. Loading the data and doing data conditioning.<br>2. Do Exploratory Data Analysis (EDA)<br>3. Pre-processing the data<br>4. Modeling the Data<br>5. Search for optimal parameters of the model<br>6. Evaluate the Model<br>7. Conclusions &amp; recommendations<br>8. Data Deployment</p><p><strong>Evaluation Metrics</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*zrlYu3DvImX045ypz5HV-w.png" /><figcaption>Photo by <a href="https://www.researchgate.net/profile/Narinder-Punn?_tp=eyJjb250ZXh0Ijp7ImZpcnN0UGFnZSI6Il9kaXJlY3QiLCJwYWdlIjoiX2RpcmVjdCJ9fQ">Narinder Singh Punn</a> on <a href="https://www.researchgate.net/figure/Confusion-matrix-and-performance-evaluation-metrics_fig5_346062755">Research Gate</a></figcaption></figure><p>Selecting the best evaluation metric for diabetes prediction, or any medical diagnosis task, is crucial as the consequences of errors can be serious. The choice of metric depends on the problem’s specifics and what kind of errors are more costly or important to minimize. Here are some commonly used metrics for classification tasks, especially for medical diagnoses like diabetes prediction:<br>- <strong>Accuracy</strong>: This is a straightforward metric that calculates the proportion of predictions that the model got right. However, it might not be ideal if the dataset is imbalanced (e.g. if only a small fraction of patients have diabetes).<br>- <strong>Confusion Matrix</strong>: Displays the number of true positives, true negatives, false positives, and false negatives. Especially important in medical contexts where the costs of false negatives (failing to identify a positive case) and false positives (incorrectly identifying a negative case) might be different.<br>- <strong>Precision</strong>: Measures the fraction of true positive predictions among all positive predictions. Important when the cost of false positives is high (e.g., unnecessary medical interventions).<br>- <strong>Recall (or Sensitivity)</strong>: Measures the fraction of true positive predictions among all actual positives. Critical when the cost of false negatives is high (e.g., failing to identify someone with diabetes).<br>- <strong>F1-Score</strong>: Harmonic mean of precision and recall, useful when you seek a balance between precision and recall and there’s an uneven class distribution.<br>- <strong>ROC Curve &amp; AUC</strong>: Receiver Operating Characteristic curve plots the true positive rate against the false positive rate at various threshold settings. The AUC (Area Under the Curve) quantifies the overall ability of the model to discriminate between positive and negative cases. AUC is especially useful for imbalanced datasets.<br>- <strong>Specificity</strong>: Measures the fraction of true negative predictions among all actual negatives. Important if you want to ensure that those without the condition (in this case, diabetes) are correctly identified.<br>- <strong>Cost-sensitive metrics</strong>: In some medical contexts, the costs of false positives and false negatives may be different. This may warrant custom metrics that factor in these costs.</p><p>The label in the dataset is ‘Outcome’ with the value:<br>- ‘No’: No Diabetes<br>- ‘Yes’: Diabetes</p><p>In the Confusion matrix there are 4 classes of prediction results, namely:<br>1. True Positive (TP): People who are predicted to be diabetic and are actually diabetic.<br>2. True Negative (TN): People who are predicted not to be diabetic and actually are not.<br>3. False Positive (FP): People who are predicted to have diabetes but are not actually diabetic.<br>4. False Negative (FN): People who are predicted not to be diabetic but are actually diabetic.</p><p>In the case of diabetes predictions there are several considerations for wrong predictions:<br>1. False Negative (FN): It is dangerous for the person because the diabetic person does not know that he has diabetes, so there is no treatment for them in dealing with diabetes problems.<br>2. False Positive (FP): Loss of time and cost due to treatment even though the treatment is not needed. Furthermore, there is a potential effect on health conditions when treating diabetes in people who are not diabetic.</p><p>For diabetes prediction, often Recall (Sensitivity) is given high importance because it’s critical to identify as many actual cases of diabetes as possible (minimize false negatives). However, this shouldn’t come at the cost of a very large number of false positives, which could lead to unnecessary stress or medical interventions. Therefore, a balance, possibly using F1-Score or considering both Precision and Recall, can be vital. Also, examining the ROC curve and maximizing the AUC can be a good strategy to ensure a good trade-off between sensitivity and specificity. From these considerations, we will choose the ROC-AUC evaluation matrix to increase the confidence of the model in making predictions so as to minimize wrong predictions (FP and FN).</p><p><strong>1.3. Data Understanding</strong></p><p><strong>Data Source</strong></p><p>The data source used is a CSV file provided by Digital Skola</p><p><strong>Dataset Description</strong></p><p>This dataset is provided by Digital Skola which is taken from the original version of the National Institute of Diabetes and Digestive and Kidney Diseases from Kaggle.</p><p><a href="https://www.kaggle.com/datasets/mathchi/diabetes-data-set">Diabetes Dataset</a></p><p>Sources:<br>(a) Original owners: National Institute of Diabetes and Digestive and Kidney Diseases<br>(b) Donor of the database: Vincent Sigillito (vgs@aplcen.apl.jhu.edu) Research Center, RMI Group Leader Applied Physics Laboratory The Johns Hopkins University Johns Hopkins Road Laurel, MD 20707 (301) 953–6231<br>(c) Date received: 9 May 1990</p><p><strong>Attributes Information</strong></p><p>Input Variables:<br>- Pregnancies: Number of times pregnant.<br>- Glucose: Plasma glucose concentration a 2 hours in an oral glucose tolerance test.<br>- BloodPressure: Diastolic blood pressure (mm Hg)<br>- SkinThickness: Triceps skin fold thickness (mm)<br>- Insulin: 2-Hour serum insulin (mu U/ml)<br>- BMI: Body mass index (weight in kg/(height in m)²)<br>- DiabetesPedigreeFunction: Diabetes pedigree function<br>- Age: Age (years)<br>Output Variable (Desired Target):<br>- Outcome: Has the person indicated positive diabetes (binary: 1, 0)</p><p><strong>2. DATA CONDITIONING</strong></p><p><strong>Import Libraries</strong></p><pre># Library   <br>import pandas as pd<br>import numpy as np<br><br># Visualization<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import missingno<br>from IPython.display import display<br><br># Data Analysis<br>from scipy.stats import normaltest<br><br># Feature Engineering<br>from sklearn.pipeline import Pipeline<br>from sklearn.impute import KNNImputer<br>from sklearn.preprocessing import OneHotEncoder, LabelEncoder, OrdinalEncoder, QuantileTransformer<br>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import RobustScaler, StandardScaler<br>import category_encoders as ce<br><br># Model Selection<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import GridSearchCV,StratifiedKFold,train_test_split, cross_val_score, KFold<br>from sklearn.metrics import classification_report, confusion_matrix<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.ensemble import RandomForestClassifier<br>from xgboost import XGBClassifier<br>from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier<br>from sklearn.ensemble import GradientBoostingClassifier<br>from sklearn.metrics import f1_score, accuracy_score, recall_score, precision_score<br>from sklearn.metrics import roc_curve, roc_auc_score<br>from sklearn.metrics import RocCurveDisplay, ConfusionMatrixDisplay<br>from sklearn.metrics import roc_auc_score, roc_curve<br>from sklearn.model_selection import cross_val_score<br>from sklearn import metrics<br>from sklearn.metrics import precision_recall_curve<br>from sklearn.metrics import precision_recall_curve<br><br># Imbalance Dataset<br>from imblearn.pipeline import Pipeline<br>from imblearn.over_sampling import RandomOverSampler, SMOTE<br>from imblearn.under_sampling import RandomUnderSampler<br><br># Model Deployment<br>import pickle<br><br># Ignore Warning<br>import sys<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br># Set max columns<br>pd.set_option(&#39;display.max_columns&#39;, None)</pre><p><strong>Import and Load Dataset</strong></p><pre>df = pd.read_csv(&#39;dataset\diabetes_prediction.csv&#39;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ZjEtqsU_UKnqNdA6ADtvjA.png" /></figure><p>That is a glance at our data.</p><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*mSQ_yWkozqC5AOfxkxkI1g.png" /></figure><p>Actually, all data is in numeric (Integer and Float) format with a total of 768 data. We actually can direct to modeling without any pre-processing scheme, yet stick with me to explore data first.</p><pre>df = df.rename(columns={<br>                &#39;Pregnancies&#39;:&#39;pregnancies&#39;,<br>                &#39;Glucose&#39;:&#39;glucose&#39;,<br>                &#39;BloodPressure&#39;:&#39;blood_pressure&#39;,<br>                &#39;SkinThickness&#39;:&#39;skin_thickness&#39;,<br>                &#39;Insulin&#39;:&#39;insulin&#39;,<br>                &#39;BMI&#39;:&#39;bmi&#39;,<br>                &#39;DiabetesPedigreeFunction&#39;:&#39;diabetes_pedigree&#39;,<br>                &#39;Age&#39;:&#39;age&#39;,<br>                &#39;Outcome&#39;:&#39;y&#39;})</pre><p>This is an optional step to change the name format on the attributes, I’m more comfortable working with data that has attributes in a format that is familiar to me.</p><p><strong>3. EXPLORATORY DATA ANALYSIS (EDA)</strong></p><p><strong>3.1. Missing Value, Anomaly, Outlier, and Duplicated Data Detection</strong></p><pre>df_eda = df.copy()<br>df_eda[&#39;y&#39;].replace(1, &#39;yes&#39;, inplace = True)<br>df_eda[&#39;y&#39;].replace(0, &#39;no&#39;, inplace = True)</pre><p><strong>Missing Value Detection</strong></p><pre>listItem = []<br>for col in df_eda.columns :<br>    listItem.append([col, df_eda[col].dtype, df_eda[col].isna().sum(), round((df_eda[col].isna().sum()/len(df_eda[col])) * 100,2),<br>                    df_eda[col].nunique(), list(df_eda[col].drop_duplicates().sample(2).values)]);<br><br>df_edaDesc = pd.DataFrame(columns=[&#39;dataFeatures&#39;, &#39;dataType&#39;, &#39;null&#39;, &#39;nullPct&#39;, &#39;unique&#39;, &#39;uniqueSample&#39;],<br>                     data=listItem)<br>df_edaDesc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*tASo4FmqgGSta8WXdfER2w.png" /></figure><p>There is no missing value indicated in the dataset</p><p><strong>Data Anomalies Detection</strong></p><pre>df_eda.describe()<br><br># See data distribution for glucose, blood_pressure, skin_thickness, insulin, and bmi<br>cols = [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;, &#39;bmi&#39;]<br>fig = plt.figure(figsize=(20, 5))<br>for i in range(len(cols)):<br>    plt.subplot(1, 5, i+1)<br>    sns.histplot(df_eda[cols[i]], kde=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bktTdSt3SIKYIlZ0hmpLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlacEPm4vTzTRuYOem3C3w.png" /></figure><p>Several features display a minimum value of 0: glucose, blood_pressure, skin_thickness, insulin, and bmi, which are non-sense if the score is 0.</p><pre>zero1 = df_eda[df_eda[&#39;glucose&#39;] == 0]<br>zero2 = df_eda[df_eda[&#39;blood_pressure&#39;] == 0]<br>zero3 = df_eda[df_eda[&#39;skin_thickness&#39;] == 0]<br>zero4 = df_eda[df_eda[&#39;insulin&#39;] == 0]<br>zero5 = df_eda[df_eda[&#39;bmi&#39;] == 0]<br><br># Calculate Percentage<br>zeros = [zero1, zero2, zero3, zero4, zero5]<br>cols = [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;, &#39;bmi&#39;]<br>for i in range(5):<br>  pct = round(len(zeros[i])/len(df_eda[cols[i]])*100,2)<br>  print(f&#39;The percentage of zero values in the {cols[i]} column is {pct} %&#39;)</pre><p>The percentage of zero values in the glucose column is 0.65 %<br>The percentage of zero values in the blood_pressure column is 4.56 %<br>The percentage of zero values in the skin_thickness column is 29.56 %<br>The percentage of zero values in the insulin column is 48.7 %<br>The percentage of zero values in the bmi column is 1.43 %</p><pre>zero_pct = round(zero_all.shape[0]/df_eda.shape[0]*100,2)<br>print(f&#39;There are {zero_pct} % zero value anomalies in the data&#39;)</pre><p>There are 48.96 % zero value anomalies in the data</p><p>We use KNNImputer to assign a 0 value in a numerical variable with an imputer based on the predictive model KNN.</p><pre>knn_impute = KNNImputer(missing_values=0)<br>df_eda[[&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;,<br>       &#39;bmi&#39;, &#39;diabetes_pedigree&#39;, &#39;age&#39;]] = knn_impute.fit_transform(df_eda[[&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;,<br>       &#39;bmi&#39;, &#39;diabetes_pedigree&#39;, &#39;age&#39;]])<br><br>df_eda.describe()<br><br>cols = [&#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;, &#39;bmi&#39;]<br>fig = plt.figure(figsize=(20, 5))<br>for i in range(len(cols)):<br>    plt.subplot(1, 5, i+1)<br>    sns.histplot(df_eda[cols[i]], kde=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnaDsud7-dNraaet90Labw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpQ6hUT8PLVquHMRw6RqNA.png" /></figure><p>Oke, I think we’re done with data anomalies.</p><p><strong>Outlier Data Detection</strong></p><pre>numerical_cols = [&#39;pregnancies&#39;, &#39;glucose&#39;, &#39;blood_pressure&#39;, &#39;skin_thickness&#39;, &#39;insulin&#39;,<br>       &#39;bmi&#39;, &#39;diabetes_pedigree&#39;, &#39;age&#39;]<br># plot for outliers detection<br>plt.figure(figsize=(10,10))<br>for i in range(len(df_eda[numerical_cols].columns)):<br>    plt.subplot(3,3,i+1)<br>    sns.boxplot(x=df_eda[numerical_cols[i]])<br>    plt.title(df_eda.columns[i])<br>    <br>plt.tight_layout()<br>warnings.simplefilter(action=&#39;ignore&#39;, category=FutureWarning)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*hmPpba0jkkNBhKE_PUUErA.png" /></figure><pre># creating function to generate IQR, lower limit, and Upper limit<br>def find_outlier(df, feature):<br>    print(&#39;Outlier &#39; + feature)<br>    q1 = df[feature].quantile(0.25)<br>    q3 = df[feature].quantile(0.75)<br>    iqr = q3 - q1<br>    limit = iqr*1.5<br>    print(f&#39;IQR: {iqr}&#39;)<br><br>    Lower_Limit = q1 - limit<br>    Upper_Limit = q3 + limit<br>    print(f&#39;Lower_Limit: {Lower_Limit}&#39;)<br>    print(f&#39;Upper_Limit: {Upper_Limit}&#39;)<br>    print(&#39;_________________________&#39;)<br><br># check IQR, upper limit, and lower limit for each feature<br>for i in df_eda.drop(columns=[&#39;y&#39;]) :<br>    find_outlier(df_eda, i)<br><br># creating outliers columns<br>out1 = df_eda[df_eda[&#39;pregnancies&#39;] &gt; 13.5]<br>out2 = df_eda[(df_eda[&#39;glucose&#39;] &lt; 37.125) &amp; (df_eda[&#39;glucose&#39;] &gt; 202.125)]<br>out3 = df_eda[(df_eda[&#39;blood_pressure&#39;] &lt; 40) &amp; (df_eda[&#39;blood_pressure&#39;] &gt; 104)]<br>out4 = df_eda[(df_eda[&#39;skin_thickness&#39;] &lt; 5) &amp; (df_eda[&#39;skin_thickness&#39;] &gt; 53)]<br>out5 = df_eda[df_eda[&#39;insulin&#39;] &gt; 346.45]<br>out6 = df_eda[(df_eda[&#39;bmi&#39;] &lt; 13.85) &amp; (df_eda[&#39;bmi&#39;] &gt; 50.25)]<br>out7 = df_eda[df_eda[&#39;diabetes_pedigree&#39;] &gt; 1.2]<br>out8 = df_eda[df_eda[&#39;age&#39;] &gt; 66.5]<br><br>#check outliers percentage<br>print(f&#39;Percentage Outlier is {format((len(out_all)/len(df_eda)*100),&#39;.2f&#39;)} %&#39;)</pre><p>Percentage Outliers is 9.11 %</p><p>Since the amount of outliers is not significant, I’ll drop this data.</p><pre>df_eda.drop(labels=out_all.index, axis=0, inplace=True)<br><br># plot for outliers detection after removing outliers<br>plt.figure(figsize=(10,10))<br>for i in range(len(df_eda[numerical_cols].columns)):<br>    plt.subplot(3,3,i+1)<br>    sns.boxplot(x=df_eda[numerical_cols[i]])<br>    plt.title(df_eda.columns[i])<br>    <br>plt.tight_layout()<br>warnings.simplefilter(action=&#39;ignore&#39;, category=FutureWarning)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*AzebMWHutDda0j95HiV9xA.png" /></figure><p><strong>Data Duplicated Detection</strong></p><pre>#check whether there is any duplicate value<br>df_eda[df_eda.duplicated()]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*uksjobKODijkLfzNlknEzQ.png" /></figure><p>There’s no data duplicate detected.</p><p><strong>3.2. Feature Engineering</strong></p><p><strong>a. Weight Status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*5T4AA6c1H2DXU_wYkIAYBA.png" /><figcaption>Data from the <a href="https://www.cdc.gov/obesity/basics/adult-defining.html#:~:text=Obesity%20is%20frequently%20subdivided%20into,BMI%20of%2040%20or%20higher.">Centers for Disease Control and Prevention</a></figcaption></figure><pre>bmi_bins = pd.Series([&quot;Underweight&quot;, &quot;Normal&quot;, &quot;Overweight&quot;, &quot;Obesity 1&quot;, &quot;Obesity 2&quot;, &quot;Obesity 3&quot;], dtype = &quot;category&quot;)<br><br>df_eda[&#39;bmi_group&#39;] = bmi_bins<br><br>df_eda.loc[df_eda[&#39;bmi&#39;] &lt; 18.5, &#39;bmi_group&#39;] = bmi_bins[0]<br>df_eda.loc[(df_eda[&#39;bmi&#39;] &gt;= 18.5) &amp; (df_eda[&#39;bmi&#39;] &lt;= 24.9), &#39;bmi_group&#39;] = bmi_bins[1]<br>df_eda.loc[(df_eda[&#39;bmi&#39;] &gt; 24.9) &amp; (df_eda[&#39;bmi&#39;] &lt;= 29.9), &#39;bmi_group&#39;] = bmi_bins[2]<br>df_eda.loc[(df_eda[&#39;bmi&#39;] &gt; 29.9) &amp; (df_eda[&#39;bmi&#39;] &lt;= 34.9), &#39;bmi_group&#39;] = bmi_bins[3]<br>df_eda.loc[(df_eda[&#39;bmi&#39;] &gt; 34.9) &amp; (df_eda[&#39;bmi&#39;] &lt;= 39.9), &#39;bmi_group&#39;] = bmi_bins[4]<br>df_eda.loc[df_eda[&#39;bmi&#39;] &gt; 39.9 ,&#39;bmi_group&#39;] = bmi_bins[5]<br>df_eda[&#39;bmi_group&#39;].unique()</pre><p><strong>b. Insulin Status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*E9q139k7dvDE_8GqamMC0Q.png" /><figcaption>Data from <a href="https://dtc.ucsf.edu/types-of-diabetes/type2/understanding-type-2-diabetes/basic-facts/diagnosing-diabetes/">Diabetes Education Online</a></figcaption></figure><pre>insulin_bins = pd.Series([&#39;Abnormal&#39;, &#39;Normal&#39;, &#39;Abnormal&#39;], dtype = &quot;category&quot;)<br><br>df_eda[&#39;insulin_stat&#39;] = insulin_bins<br><br>df_eda.loc[df_eda[&#39;insulin&#39;] &lt; 16, &#39;insulin_stat&#39;] = insulin_bins[0]<br>df_eda.loc[(df_eda[&#39;insulin&#39;] &gt;= 16) &amp; (df_eda[&#39;insulin&#39;] &lt;= 166), &#39;insulin_stat&#39;] = insulin_bins[1]<br>df_eda.loc[df_eda[&#39;insulin&#39;] &gt; 166 ,&#39;insulin_stat&#39;] = insulin_bins[2]<br>df_eda[&#39;insulin_stat&#39;].unique()</pre><p><strong>c. Glucose Status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*gNzd3Az-NIStLJV-ms48hg.png" /><figcaption>Data from <a href="https://dtc.ucsf.edu/types-of-diabetes/type2/understanding-type-2-diabetes/basic-facts/diagnosing-diabetes/">Diabetes Education Online</a></figcaption></figure><pre>glucose_bins = pd.Series([&#39;Normal&#39;, &#39;Pre-diabetes&#39;, &#39;Diabetes&#39;], dtype = &quot;category&quot;)<br><br>df_eda[&#39;glucose_stat&#39;] = glucose_bins<br><br>df_eda.loc[df_eda[&#39;glucose&#39;] &lt; 140, &#39;glucose_stat&#39;] = glucose_bins[0]<br>df_eda.loc[(df_eda[&#39;glucose&#39;] &gt;= 140) &amp; (df_eda[&#39;glucose&#39;] &lt;= 199), &#39;glucose_stat&#39;] = glucose_bins[1]<br>df_eda.loc[df_eda[&#39;glucose&#39;] &gt; 199 ,&#39;glucose_stat&#39;] = glucose_bins[2]<br><br>df_eda[&#39;glucose_stat&#39;].unique()</pre><p><strong>d. Blood Pressure Status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*3n3pzY5LTUstN5fOjyUIAw.png" /><figcaption>Data from the <a href="https://www.cdc.gov/bloodpressure/facts.htm">Centers for Disease Control and Prevention</a></figcaption></figure><pre>blood_pressure_bins = pd.Series([&#39;Normal&#39;, &#39;Hypertension Stage 1&#39;, &#39;Hypertension Stage 2&#39;], dtype = &quot;category&quot;)<br><br>df_eda[&#39;blood_pressure_stat&#39;] = blood_pressure_bins<br><br>df_eda.loc[df_eda[&#39;blood_pressure&#39;] &lt; 80, &#39;blood_pressure_stat&#39;] = blood_pressure_bins[0]<br>df_eda.loc[(df_eda[&#39;blood_pressure&#39;] &gt;= 80) &amp; (df_eda[&#39;blood_pressure&#39;] &lt;= 89), &#39;blood_pressure_stat&#39;] = blood_pressure_bins[1]<br>df_eda.loc[df_eda[&#39;blood_pressure&#39;] &gt; 89 ,&#39;blood_pressure_stat&#39;] = blood_pressure_bins[2]<br><br>df_eda[&#39;blood_pressure_stat&#39;].unique()</pre><p><strong>3.3. Univariate Analysis</strong></p><pre>df_numeric = df_eda.select_dtypes(include=&#39;number&#39;)<br><br># creating distribution plot for analysis<br>fig = plt.figure(figsize=(20, 10))<br>for i in range(len(df_numeric.columns)):<br>    plt.subplot(2, 4, i+1)<br>    sns.histplot(df_numeric[df_numeric.columns[i]], kde=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-BzDy8UwxXN_Mq857u_TBQ.png" /></figure><p>Here is the distribution of each variable in the dataset.</p><pre># creating function for detailed descriptive analytic<br>def summary_stats(df, n=4):<br>    # central tendency: mean, median<br>    mean = pd.DataFrame(df.apply(np.mean)).T<br>    median = pd.DataFrame(df.apply(np.median)).T<br><br>    # distribution: ,std, min, max, range, skew, kurtosis<br>    std = pd.DataFrame(df.apply(np.std)).T<br>    min_value = pd.DataFrame(df.apply(min)).T<br>    max_value = pd.DataFrame(df.apply(max)).T<br>    range_value = pd.DataFrame(df.apply(lambda x: x.max() - x.min())).T<br>    skewness = pd.DataFrame(df.apply(lambda x: x.skew())).T<br>    kurtosis = pd.DataFrame(df.apply(lambda x: x.kurtosis())).T<br><br>    # concatenates<br>    summary_stats = pd.concat([min_value, max_value, range_value, mean, median, std, skewness, kurtosis]).T.reset_index()<br>    summary_stats.columns = [&#39;attributes&#39;,&#39;min&#39;,&#39;max&#39;, &#39;range&#39;,&#39;mean&#39;,&#39;median&#39;, &#39;std&#39;,&#39;skewness&#39;,&#39;kurtosis&#39;]<br>    <br>    return round(summary_stats, n)<br><br>summary_stats(df_numeric)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*5C9RZUzDdXM87d4JCAP4Sg.png" /></figure><p>Normality Range Criteria based on skewness and kurtosis:<strong> </strong>The values for asymmetry and kurtosis between -2 and +2 are considered acceptable in order to prove normal univariate distribution (George &amp; Mallery, 2010). Hair et al. (2010) and Bryne (2010) argued that data is considered to be normal if skewness is between ‐2 to +2 and kurtosis is between ‐7 to +7. (Source: <a href="https://imaging.mrc-cbu.cam.ac.uk/statswiki/FAQ/Simon#:~:text=The%20values%20for%20asymmetry%20and,between%20%E2%80%907%20to%20%2B7.">Cambridge University</a>)</p><p>Features distribution:<br>- Symetric: glucose, blood_pressure, skin_thickness, bmi.<br>- Right Skewed: pregnancies, insulin, diabetes_predigree, age.</p><p><strong>Normality Test</strong></p><pre>listItem = []<br>for col in df_eda.columns :<br>    listItem.append([col, df_eda[col].dtype, df_eda[col].isna().sum(), round((df_eda[col].isna().sum()/len(df_eda[col])) * 100,2),<br>                    df_eda[col].nunique(), round(df_eda[col].nunique()/df_eda.shape[0]*100,2), list(df_eda[col].drop_duplicates().sample(2).values)]);<br><br>df_edaDesc = pd.DataFrame(columns=[&#39;dataFeatures&#39;, &#39;dataType&#39;, &#39;null&#39;, &#39;nullPct&#39;, &#39;unique&#39;, &#39;uniquePct&#39;,&#39;uniqueSample&#39;],<br>                     data=listItem)<br>df_edaDesc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*HWJ7sopcd_tjhhF_PjkKXQ.png" /></figure><p>Since all features do not have very unique values, we chose D’Agostino and Pearson’s test for normality checking instead of The Shapiro-Wilk test</p><p><strong>Interpretation</strong>:<br>- If the P-value of the D-Agostino-Pearson Test is larger than 0.05, we assume a normal distribution.<br>- If the P-value of the D-Agostino-Pearson Test is smaller than 0.05, we do not assume a normal distribution.</p><pre>cols = df_numeric.columns<br>listItem = []<br><br>for col in cols:<br>  statistic, pvalue = normaltest(df_eda[col])<br>  if pvalue &gt; 0.05:<br>    result = &#39;Assume a Normal Distribution&#39;<br>  else:<br>    result = &#39;Do not Assume a Normal Distribution&#39;<br>  <br>  listItem.append([col, pvalue, result])<br><br>df_edaNormalTest = pd.DataFrame(columns=[&#39;dataFeatures&#39;, &#39;P-Value&#39;, &#39;Assumtion&#39;],<br>                     data=listItem)<br>df_edaNormalTest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*CNRFVSV9z65mVOxbTJe3Dg.png" /></figure><p>We do not assume a normal distribution for all of the features in the dataset. So, we will use non-parametric statistics for further analysis.</p><p><strong>Percentage of Output Class</strong></p><pre>plt.figure(figsize=(8,6)) <br>plt.title(&#39;% Patient Indicated Diabetes&#39;)<br>df_eda[&#39;y&#39;].value_counts().plot(kind = &quot;pie&quot;, autopct=&#39;%1.1f%%&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*v6gWy48OWWJJKhlVrXcx-A.png" /></figure><p>- We can see that 32.4% of the patients indicated diabetes.<br>- The dataset does not indicate an imbalance class between those who have diabetes and those who don’t.</p><p><strong>3.4. Bivariate Analysis</strong></p><pre>df_eda1 = df_eda.copy()<br>df_eda1[&#39;y&#39;].replace(&#39;yes&#39;, 1, inplace = True)<br>df_eda1[&#39;y&#39;].replace(&#39;no&#39;, 0, inplace = True)<br>df_eda1.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9i9qjxXXslLf3EAhC3cZQ.png" /></figure><p><strong>a. Analysis between numerical features</strong></p><pre>df_eda1.select_dtypes(include=&#39;number&#39;).head()<br>sns.pairplot(data = df_eda1.select_dtypes(include=&#39;number&#39;), hue = &#39;y&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MF7fyKkGGi3E1K2rY3AScA.png" /></figure><p>Level of glucose, bmi, and age showed little ability to differentiate diabetic and non-diabetic classes based on their relationship with several other attributes</p><p><strong>b. Diabetes Outcome by Blood Glucose Level, BMI, and Age</strong></p><pre>plt.figure(figsize = (18,6))<br>plt.subplot(1,2,1)<br>sns.distplot(df_eda[&#39;glucose&#39;], label = &#39;Skewness : %.2f&#39;%(df[&#39;bmi&#39;].skew()))<br>plt.legend(loc = 0, fontsize = 10)<br>plt.title(&#39;Distribution for Blood Glucose Level of Patients&#39;)<br>plt.subplot(1,2,2)<br>sns.boxplot(x = &#39;glucose&#39;, y = &#39;y&#39;, data = df_eda)<br>plt.title(&#39;Boxplot for Blood Glucose Level of Patients&#39;)<br>glucose = str(df_eda[&#39;glucose&#39;].describe().round(2))<br>plt.text(56, 0.80, glucose)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UVhL9saIUYAyPf_s9srlHg.png" /></figure><p>Based on blood glucose levels, patients with diabetes have higher blood glucose levels than patients without diabetes</p><pre>plt.figure(figsize = (18,6))<br>plt.subplot(1,2,1)<br>sns.distplot(df_eda[&#39;bmi&#39;], label = &#39;Skewness : %.2f&#39;%(df[&#39;bmi&#39;].skew()))<br>plt.legend(loc = 0, fontsize = 10)<br>plt.title(&#39;Distribution for BMI Score of Patients&#39;)<br>plt.subplot(1,2,2)<br>sns.boxplot(x = &#39;bmi&#39;, y = &#39;y&#39;, data = df_eda)<br>plt.title(&#39;Boxplot for BMI of Patients&#39;)<br>bmi = str(df_eda[&#39;bmi&#39;].describe().round(2))<br>plt.text(56, 0.80, bmi)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jg4yQoQJl82dY6yHuEuCRw.png" /></figure><p>Based on the bmi, patients with diabetes have higher BMI than patients without diabetes</p><pre>plt.figure(figsize = (18,6))<br>plt.subplot(1,2,1)<br>sns.distplot(df_eda[&#39;age&#39;], label = &#39;Skewness : %.2f&#39;%(df[&#39;bmi&#39;].skew()))<br>plt.legend(loc = 0, fontsize = 10)<br>plt.title(&#39;Distribution for BMI Score of Patients&#39;)<br>plt.subplot(1,2,2)<br>sns.boxplot(x = &#39;age&#39;, y = &#39;y&#39;, data = df_eda)<br>plt.title(&#39;Boxplot for BMI of Patients&#39;)<br>age = str(df_eda[&#39;age&#39;].describe().round(2))<br>plt.text(56, 0.80, age)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BFzfoc0Q29s_TEB59lwww.png" /></figure><p>We can see that older patients are more likely to have diabetes than younger patients</p><p><strong>c. Exploration of BMI Class</strong></p><pre>plt.figure(figsize = (20,6))<br>plt.subplot(1,2,1)<br>eda_percentage = df_eda[&#39;bmi_group&#39;].value_counts(normalize = True).rename_axis(&#39;bmi_group&#39;).reset_index(name = &#39;Percentage&#39;)<br>sns.barplot(x = &#39;bmi_group&#39;, y = &#39;Percentage&#39;, data = eda_percentage.head(10))<br>plt.title(&#39;BMI Class of Patients&#39;)<br>plt.subplot(1,2,2)<br>sns.countplot(data=df_eda, y=&#39;bmi_group&#39;, hue = df_eda[&#39;y&#39;])<br>plt.title(&#39;BMI Class of Patients&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddcbyGBoc4djTIPi_JUlHA.png" /></figure><p><strong>3.5. Multivariate Analysis</strong></p><pre>df_eda1.select_dtypes(include=np.number)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*T8HGAQWIydtzqMCEdZ_lhg.png" /></figure><pre># calculates the correlations<br>correlation = df_eda1.select_dtypes(include=np.number).corr(method= &#39;spearman&#39;)<br><br># uses the variable ax for single a Axes<br>fig, ax = plt.subplots()<br><br># sets the figure size in inches<br>ax.figure.set_size_inches(10, 10)<br><br># generates a mask for the upper triangle<br>mask = np.triu(np.ones_like(correlation, dtype=np.bool_))<br><br># generates a custom diverging colormap<br>cmap = sns.diverging_palette(220, 10, as_cmap=True)<br><br># plots the heatmap<br>sns.heatmap(correlation, cmap=cmap, mask=mask, square=True, linewidths=.5, <br>            annot=True, annot_kws={&#39;size&#39;:14})<br><br># displays the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*VEF8gfQG4oGqnZhMdgJCww.png" /></figure><p><strong>Degree of Correlation:<br>- </strong>Strong: 0.50–1.00<br>- Medium: 0.30–0.49<br>- Small: &lt; + 0.29<br>(Source: <a href="https://www.statisticssolutions.com/free-resources/directory-of-statistical-analyses/pearsons-correlation-coefficient/">Statistic Solution</a>)</p><p>- All of the variables have a correlation with the y variable (Diabetes), but the degree of correlation varies from small to medium (there are no variables that have a strong correlation with diabetes). The strongest variable that correlated with diabetes is glucose (0.48), followed by insulin (0.38) and age (0.33).<br>- glucose, bmi, and age have (+) correlation, which means that if these variables increase, the y variable tends to increase. There is also a (+) correlation between pregnancies, blood_pressure, skin thickness, insulin, and diabetes_predigree with y (small correlation).<br>- There is data multi-collinearity indicated from the dataset. insulin and glucosewith corr 0.7 (strong correlation); bmi and skin_thickness with corr 0.69 (strong correlation); andage and pregnancies with corr 0.61.</p><p><strong>We will continue our adventure in creating supervised machine-learning models to predict diabetes. The adventure will be even more exciting!</strong></p><p><a href="https://medium.com/@deryl.baharudin/crunching-numbers-saving-lives-my-journey-with-diabetes-prediction-part-2-a84ef32b947c">Crunching Numbers &amp; Saving Lives: My Journey with Diabetes Prediction (Part 2)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b6bafd13f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression Mechanism in Supervised Classification Problems]]></title>
            <link>https://medium.com/@deryl.baharudin/logistic-regression-mechanism-in-supervised-classification-problems-4870f41b37e6?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/4870f41b37e6</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 02:48:15 GMT</pubDate>
            <atom:updated>2023-09-07T13:11:17.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science: Machine Learning</h4><h4>A Binary Classification Model in Supervised Machine Learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*A_D47lu42P_XLf8lzdhNQg.png" /><figcaption>Photo by <a href="https://www.javatpoint.com/logistic-regression-in-machine-learning">Java T Point</a>.</figcaption></figure><p>See a brief explanation of the logistic regression model in my article below:</p><p><a href="https://medium.com/@deryl.baharudin/a-simple-yet-effective-model-for-dealing-with-linear-classification-problems-28d20018c7b7">A simple yet effective model for dealing with linear classification problems.</a></p><p>Logistic Regression is one of the foundational algorithms for binary classification. At its core, Logistic Regression models the probability that a given instance belongs to a particular category. Let’s delve into its mechanism:</p><h4>1. Linear Transformation</h4><p>The first step in Logistic Regression is to compute a weighted sum of the input features (similar to linear regression):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*hVSoqnLXopHJG3LfKIzg0A.gif" /></figure><p>Where:</p><ul><li><em>x</em>₁, <em>x</em>₂, …, <em>x</em>ₙ are the input features.</li><li>​<em>β</em>₁, <em>β</em>₂, …, <em>β</em>ₙ are the parameters of the model (intercept and coefficients respectively).</li><li><em>z</em> is the output of the linear transformation</li></ul><h4>2. Logistic Function</h4><p>Instead of returning the linear combination of inputs directly as the prediction (like in linear regression), Logistic Regression passes this value through the logistic (sigmoid) function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*iM5qrk1FzfiuUWz-B0QLew.gif" /></figure><p>The logistic function maps any input into a value between 0 and 1, which can be interpreted as the probability of the instance belonging to the positive class.</p><h4>3. Binary Classification Decision</h4><p>Given the output probability from the logistic function:</p><ul><li>If <em>σ</em>(<em>z</em>) ≥ 0.5, the predicted class is 1 (or the positive class).</li><li>If <em>σ</em>(<em>z</em>) &lt; 0.5, the predicted class is 0 (or the negative class).</li></ul><p>The threshold of 0.5 is standard, but it can be adjusted depending on the specific problem or based on other criteria like precision-recall trade-offs.</p><h4>4. Model Training: Maximum Likelihood Estimation</h4><p>While the prediction process is relatively straightforward, training the logistic regression model (i.e., estimating the parameters) requires a bit more machinery.</p><p>For training, Logistic Regression uses Maximum Likelihood Estimation (MLE) to find the set of parameters (coefficients) that maximizes the likelihood of the observed data. Intuitively, MLE adjusts the parameters such that if you run the model on your training data, the predicted probabilities will be as close as possible to the observed outcomes.</p><h4>Key Takeaways:</h4><ol><li><strong>Linear Transformation</strong>: The input features are combined linearly using weights or coefficients, similar to linear regression.</li><li><strong>Logistic Function</strong>: The results of the linear combination are passed through the sigmoid function, which squishes values between 0 and 1.</li><li><strong>Classification Decision</strong>: A threshold (commonly 0.5) is used to decide the final class label.</li><li><strong>Training with MLE</strong>: The model is trained to find the parameters that maximize the likelihood of the observed data.</li></ol><p>The beauty of Logistic Regression lies in its simplicity, interpretability, and foundational role in understanding more complex algorithms. While newer algorithms can offer better accuracy for certain tasks, Logistic Regression remains a go-to for binary classification problems, especially when interpretability is a priority.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4870f41b37e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple yet effective model for dealing with linear classification problems.]]></title>
            <link>https://medium.com/@deryl.baharudin/a-simple-yet-effective-model-for-dealing-with-linear-classification-problems-28d20018c7b7?source=rss-6181a9ee02de------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d20018c7b7</guid>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Deryl Baharudin Sopandi]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 02:10:30 GMT</pubDate>
            <atom:updated>2023-09-07T13:03:09.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science: Machine Learning</h4><h4>Supervised Logistic Regression Model in scikit-learn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2P72kSSRlMWbR320" /><figcaption>Photo by <a href="https://unsplash.com/@fatosi?utm_source=medium&amp;utm_medium=referral">Fatos Bytyqi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Logistic Regression is a cornerstone of machine learning, facilitating classification by modeling the probability that an instance belongs to a particular category. The scikit-learn (often abbreviated to sklearn) library in Python provides robust tools for building Logistic Regression models. This article will provide a detailed overview of the Logistic Regression model in scikit-learn, including its usage, attributes, methods, and practical tips.</p><h4>What is Logistic Regression</h4><p>Logistic Regression is a statistical method for predicting binary outcomes. Given a set of features, it estimates the probability that an instance/observation belongs to a particular category. Despite the name, it is used for classification problems, not regression problems. The model outputs a probability that the given input point belongs to a particular class, which is transformed into a binary outcome via a threshold (e.g., if the output probability is greater than 0.5, classify it as class 1, class 0).</p><h4>Using Logistic Regression in scikit-learn</h4><h4>1. Installation</h4><p>To begin, you need to have scikit-learn installed</p><pre>pip install scikit-learn</pre><h4>2. Model Training</h4><p>Here’s a basic outline for building a Logistic Regression model using scikit-learn:</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br><br># Split data into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Initialize the model<br>logreg = LogisticRegression()<br><br># Fit the model<br>logreg.fit(X_train, y_train)<br><br># Predictions<br>predictions = logreg.predict(X_test)</pre><h4><strong>3. Important Attributes and Methods</strong></h4><p><strong>Attributes:</strong></p><ul><li>coef_: Returns the coefficients of the features in the decision function.</li><li>intercept_: Represents the intercept added to the decision function.</li></ul><p><strong>Methods:</strong></p><ul><li>fit(X, y): Fit the model according to the given training data.</li><li>predict(X): Predict class labels for samples in X.</li><li>predict_proba(X): Probability estimates. Returns the probability of the sample for each class in the model.</li></ul><h4>4. Hyperparameters Tuning</h4><p>LogisticRegression() comes with various hyperparameters, some of which are:</p><ul><li>C: Inverse regularization strength. Smaller values specify stronger regularization.</li><li>penalty: Used to specify the norm used in the penalization (&#39;l1&#39;, &#39;l2&#39;, &#39;elasticnet&#39;).</li><li>solver: Algorithm to use in the optimization problem (&#39;newton-cg&#39;, &#39;lbfgs&#39;, &#39;liblinear&#39;, &#39;sag&#39;, &#39;saga&#39;).</li></ul><h4>5. Tips for Practical Implementation</h4><ul><li><strong>Feature Scaling</strong>: It’s crucial to scale the features for logistic regression as it uses gradient descent for optimization. You can use StandardScaler or MinMaxScaler from scikit-learn for this.</li><li><strong>Regularization</strong>: Regularization is used to prevent overfitting. The C parameter in the logistic regression is the inverse of regularization strength, with smaller values indicating stronger regularization.</li><li><strong>Multiclass Classification</strong>: By default, Logistic Regression supports binary classification. However, for multiclass problems, it uses a one-vs-all approach. You can adjust the multi_class parameter for alternative methods.</li></ul><h4>6. Conclusion</h4><p>Logistic Regression, despite its simplicity, remains a powerful tool for binary classification problems. With scikit-learn, implementing and tuning this model becomes straightforward, enabling both beginners and professionals to harness its capabilities efficiently. Whether used as a standalone model or as part of an ensemble, Logistic Regression in scikit-learn is a valuable tool to have in one&#39;s machine learning toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d20018c7b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>