<?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 Guptamansi on Medium]]></title>
        <description><![CDATA[Stories by Guptamansi on Medium]]></description>
        <link>https://medium.com/@guptamansi403?source=rss-8d6d5c0b5c76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_waHgemOWCVvDur1</url>
            <title>Stories by Guptamansi on Medium</title>
            <link>https://medium.com/@guptamansi403?source=rss-8d6d5c0b5c76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:00:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guptamansi403/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[Predicting Personalized Health Insurance Premiums with Machine Learning: From EDA to Deployment]]></title>
            <link>https://medium.com/@guptamansi403/predicting-personalized-health-insurance-premiums-with-machine-learning-from-eda-to-deployment-9f7b09544b7e?source=rss-8d6d5c0b5c76------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7b09544b7e</guid>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Guptamansi]]></dc:creator>
            <pubDate>Sat, 17 May 2025 13:28:22 GMT</pubDate>
            <atom:updated>2025-05-18T05:50:27.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>💡 Predicting Personalized Health Insurance Premiums with Machine Learning: From EDA to Deployment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*4qIDqZPO3pPiQrjJR4opzQ.png" /><figcaption>Source: <a href="https://www.comparepolicy.com/blogs/top-10-health-insurance-companies-in-india-2023/">https://www.comparepolicy.com/blogs/top-10-health-insurance-companies-in-india-2023/</a></figcaption></figure><h3>Contents</h3><ol><li>Introduction</li><li>Problem Statement, Impact &amp; Objective</li><li>Data Description</li><li>Exploratory Data Analysis</li><li>Hypothesis Testing</li><li>Modelling</li><li>Comparison of model performance and conclusions</li><li>GitHub Repository and LinkedIn</li></ol><h3><strong>Introduction</strong></h3><p>There’s a pressing challenge in health insurance: <strong>how do we set fair, individualized premiums</strong> that accurately reflect each policyholder’s risk? Relying on broad actuarial tables often leads to losses for insurers and unfair pricing for customers. In this post, I’ll walk you through my end-to-end solution — starting from <strong>Exploratory Data Analysis</strong>, moving through <strong>hypothesis testing</strong>, <strong>modeling</strong>, and finally <strong>deployment</strong> — to predict personalized insurance premiums using machine learning. I’ll share key observations, code snippets, plot examples, and links to the full code.</p><h3>🎯 1. Problem Statement, Impact &amp; Objective</h3><p><strong>Problem</strong>: Traditional pricing methods use aggregate statistics, failing to capture individual nuances (age, health history, surgeries, BMI, etc.).</p><p><strong>Impact</strong>:</p><ul><li>Personalize pricing using ML models</li><li>Improve insurer competitiveness</li><li>Reduce risk of mispricing</li><li>Increase transparency for policyholders</li></ul><p><strong>Objective: </strong>Build a transparent pipeline that ingests customer data and outputs a premium estimate, backed by statistical validation and robust model deployment.</p><h3>1.1 Concepts used:</h3><ul><li>Data Cleaning and pre-processing</li><li>EDA</li><li>Hypothesis testing (<em>using scipy library for statistical test</em>)</li><li>Predictions using Tree based models (<em>using sklearn library</em>)</li><li>Deployment using Streamlit</li></ul><h3>2. Data Description</h3><p>The dataset comprises the following 11 attributes:</p><ol><li>Age: Numeric, ranging from 18 to 66 years.</li><li>Diabetes: Binary (0 or 1), where 1 indicates the presence of diabetes.</li><li>BloodPressureProblems: Binary (0 or 1), indicating the presence of blood pressure-related issues.</li><li>AnyTransplants: Binary (0 or 1), where 1 indicates the person has had a transplant.</li><li>AnyChronicDiseases: Binary (0 or 1), indicating the presence of any chronic diseases.</li><li>Height: Numeric, measured in centimeters, ranging from 145 cm to 188 cm.</li><li>Weight: Numeric, measured in kilograms, ranging from 51 kg to 132 kg.</li><li>KnownAllergies: Binary (0 or 1), where 1 indicates known allergies.</li><li>HistoryOfCancerInFamily: Binary (0 or 1), indicating a family history of cancer.</li><li>NumberOfMajorSurgeries: Numeric, counting the number of major surgeries, ranging from 0 to 3 surgeries.</li><li>PremiumPrice: Numeric, representing the premium price in currency, ranging from 15,000 to 40,000.</li></ol><h3>3. Exploratory Data Analysis (EDA)</h3><p>For the Insurance Cost Prediction project, EDA will involve visualizing distributions, identifying outliers, and exploring correlations between different variables like age, diabetes status, weight, and premium costs. This analysis aims to unearth significant predictors of insurance costs and understand the demographic and health-related characteristics that most influence premium pricing.</p><p>Before moving ahead with EDA we will first, import some libraries like pandas, numpy, matplotlib etc.</p><p>Inspecting the dataframe</p><pre>df = pd.read_csv(r&#39;insurance.csv&#39;)<br>df.info()</pre><figure><img alt="Inspecting the dataframe" src="https://cdn-images-1.medium.com/max/1024/1*r9BiTcpPg_CSJ8vpKZQ1nA.png" /></figure><pre><br>df.info()&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 986 entries, 0 to 985<br>Data columns (total 11 columns):<br> #   Column                   Non-Null Count  Dtype<br>---  ------                   --------------  -----<br> 0   Age                      986 non-null    int64<br> 1   Diabetes                 986 non-null    int64<br> 2   BloodPressureProblems    986 non-null    int64<br> 3   AnyTransplants           986 non-null    int64<br> 4   AnyChronicDiseases       986 non-null    int64<br> 5   Height                   986 non-null    int64<br> 6   Weight                   986 non-null    int64<br> 7   KnownAllergies           986 non-null    int64<br> 8   HistoryOfCancerInFamily  986 non-null    int64<br> 9   NumberOfMajorSurgeries   986 non-null    int64<br> 10  PremiumPrice             986 non-null    int64<br>dtypes: int64(11)<br>memory usage: 84.9 KB</pre><p>Since there is 986 rows and 13 columns which is a moderate‐sized dataset ideal for our tree‐based and linear models and Non‐null counts show every record is present — no rows were dropped or truncated.</p><p>Next, we explicitly verify there are no missing values in any column:</p><pre>missing_counts  = df.isnull().sum()<br>missing_percent = df.isnull().mean() * 100<br>missing_df = pd.DataFrame({<br>    &#39;MissingCount&#39;: missing_counts,<br>    &#39;MissingPercent&#39;: missing_percent<br>})<br>print(&quot;Missing Values Summary:&quot;)<br>print(missing_df)</pre><p>Having confirmed data integrity, we’re now ready for our next steps: outlier detection, feature engineering, and hypothesis testing.</p><p><strong>2.1 Feature Engineering: Calculating BMI</strong></p><p>One important health indicator not directly provided in the raw data is <strong>Body Mass Index (BMI)</strong>, which normalizes weight by height. Including BMI as a feature helps our model capture the impact of a person’s body composition on their insurance cost. High BMI is often associated with increased health risk (e.g., diabetes, hypertension) which can drive up premiums.</p><pre>df[&#39;Height_m&#39;] = df[&#39;Height&#39;] / 100<br>df[&#39;BMI&#39;]      = df[&#39;Weight&#39;] / (df[&#39;Height_m&#39;] ** 2)</pre><p>Let’s identify extreme values that could disproportionately influence our models. We apply the Interquartile Range (IQR) rule to every numeric column</p><pre>binary_cols = [<br>    &#39;Diabetes&#39;,<br>    &#39;BloodPressureProblems&#39;,<br>    &#39;AnyTransplants&#39;,<br>    &#39;AnyChronicDiseases&#39;,<br>    &#39;KnownAllergies&#39;,<br>    &#39;HistoryOfCancerInFamily&#39;<br>]<br><br>numeric_cols = [<br>    &#39;Age&#39;,<br>    &#39;BMI&#39;,<br>    &#39;NumberOfMajorSurgeries&#39;,<br>    &#39;PremiumPrice&#39;<br>]<br><br><br># Outlier detection using IQR for all numeric columns<br>numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()<br>outlier_summary = []<br>n = len(df)<br>for col in numeric_cols:<br>    Q1 = df[col].quantile(0.25)<br>    Q3 = df[col].quantile(0.75)<br>    IQR = Q3 - Q1<br>    lb = Q1 - 1.5 * IQR<br>    ub = Q3 + 1.5 * IQR<br>    count = ((df[col] &lt; lb) | (df[col] &gt; ub)).sum()<br>    percent = (count / n) * 100<br>    outlier_summary.append({<br>        &#39;Feature&#39;: col,<br>        &#39;LowerBound&#39;: lb,<br>        &#39;UpperBound&#39;: ub,<br>        &#39;OutlierCount&#39;: int(count),<br>        &#39;OutlierPercent&#39;: percent<br>    })<br><br>outlier_df = pd.DataFrame(outlier_summary).set_index(&#39;Feature&#39;)<br>print(&quot;\nOutlier Detection Summary (IQR Method):&quot;)<br>print(outlier_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*b4Hg_g1kOwvpnIsskDB0YQ.png" /></figure><p>During our outlier analysis, we encountered a few interesting patterns. First, several binary features — such as Any Transplants, Any Chronic Diseases, Known Allergies, and History Of Cancer In Family—were flagged as outliers by default. This happened because their values are strictly 0 or 1, making their interquartile range (IQR) effectively zero. In such cases, every instance with a value of 1 was technically marked as an outlier, even though it&#39;s a valid and important signal. To maintain the integrity of the analysis, we excluded these binary columns from further outlier treatment and focused on the continuous variables instead.</p><p>Looking at the continuous features, we found that about 1.6% of the dataset had weight values outside the range of 37 kg to 117 kg. Similarly, approximately 2.2% of BMI values fell outside the healthy range of 12.34 to 41.81, indicating a small but noteworthy number of extreme underweight or overweight cases.</p><p>In terms of surgeries, 16 individuals had undergone three major surgeries — the highest value recorded — making up another 1.6% of the data. While rare, these entries represent high-risk profiles and were retained in the dataset for their predictive value.</p><p>Finally, when analyzing PremiumPrice, we noticed that six entries (around 0.6% of the total) exceeded ₹38,500 or fell below ₹10,500. These high and low premiums added noticeable skew to the distribution and were considered for capping to reduce distortion in our models.</p><p>Here’s how you can smoothly transition from outlier detection into your visual analysis phases in the blog, with <strong>clear guidance on where to insert graphs and observations</strong> to keep the narrative flowing naturally:</p><p>With the outliers identified and treated, the dataset is now clean and ready for deeper exploration. This brings us to the next crucial step in the data analysis process: <strong>univariate, bivariate, and multivariate analysis</strong>. These methods help us extract meaningful patterns, validate assumptions, and prepare for robust feature selection in our machine learning models.</p><h3>🔍 Univariate Analysis: Looking at Each Variable Individually</h3><p>In univariate analysis, we explore the distribution, central tendencies, and spread of each feature — particularly the continuous ones like Age, BMI, Weight, and PremiumPrice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SY7L1Y2MJh3Hlk7-0f97pQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECm6KjaqiThlXzPZT0lFAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*8N_keAMkA0IA8Hn55SyYVw.png" /></figure><p>The age distribution is fairly even across 18 to 66, with small peaks in the early 30s and late 40s. About 18% of people report a chronic disease, meaning it’s a minority class but still a key risk factor. Transplants are rare — only 5–6% — but they carry high clinical significance and shouldn’t be ignored. Premium prices are skewed to the right, mostly falling between ₹15,000 and ₹30,000, with a few stretching up to ₹40,000. To handle this skew, a log transformation or a robust model like Random Forest is recommended.</p><h3>🔗 Bivariate Analysis: Comparing Predictors to the Target</h3><p>This phase focuses on understanding how individual features relate to our target variable, PremiumPrice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*5L-T6-OxQjJj3ZFPqZFr4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*RNJ_BIcPFnyD_I2etXKNmA.png" /></figure><p>When looking at premiums by age, a clear upward trend emerges. Younger adults between 18 and 30 typically pay between ₹15,000 and ₹25,000. As age increases, so do premiums — rising steadily to the ₹25,000–₹35,000 range for those in their 40s to 60s. A few seniors over 60 even reach the upper limit of ₹40,000. Age stands out as the strongest continuous predictor in our dataset — older applicants almost always face higher costs.</p><p>In contrast, the relationship between BMI and premium is more scattered. There’s a subtle upward tilt: extremely low BMI (under 18) and very high BMI (over 40) are sometimes linked to higher premiums, but the pattern isn’t tight. Most applicants with a BMI between 20 and 35 see premiums clustering between ₹20,000 and ₹30,000. So while BMI isn’t as predictive as age or chronic conditions, extreme values can still signal elevated risk.</p><h3>📊 Correlation Matrix: Identifying Key Relationships</h3><p>To quantify how features relate to one another — especially to our target, PremiumPrice—we use a correlation matrix. This heatmap gives us a clear visual of the strength and direction of linear relationships between numerical variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*FjpNx_mHzo9YbQ9yLGiNiQ.png" /></figure><p>The standout feature is <strong>Age</strong>, showing a strong positive correlation (r = 0.70) with PremiumPrice. As expected, older applicants tend to pay significantly higher premiums, making age a crucial variable in our modeling process.</p><p><strong>Transplant history</strong> comes next, with a moderate correlation of 0.29. Though transplants are rare, they’re strongly associated with elevated premiums and serve as a red flag for risk.</p><p>The <strong>number of major surgeries</strong> also plays a meaningful role (r = 0.26). Each additional surgery tends to raise the premium, acting as a proxy for more complex health profiles.</p><p>Other features like <strong>Diabetes</strong> and <strong>Family History of Cancer</strong> show only weak individual correlations (r = 0.08 each), indicating their impact might emerge in combination with other variables or through non-linear relationships.</p><p>On the other hand, <strong>Known Allergies</strong> and <strong>Height</strong> have near-zero correlations with price, suggesting they offer little predictive power in isolation.</p><h3>5. Hypothesis Testing: Validating Observed Patterns</h3><p>With visual and statistical associations identified, it’s time to formally test our assumptions using hypothesis testing. These tests help confirm whether differences we observe in premiums across health groups are statistically significant or just due to random chance.</p><h4>✅ One-Sided T-Test: Chronic Disease Impact on Premiums</h4><p>We test whether individuals with chronic diseases pay significantly more than those without.</p><p><strong>Hypotheses</strong>:</p><ul><li><strong>H₀</strong>: The mean premium for both groups is equal</li><li><strong>H₁</strong>: Premiums are higher for individuals with chronic diseases</li></ul><pre>group_chronic    = df.loc[df[&#39;AnyChronicDiseases&#39;] == 1, &#39;PremiumPrice&#39;]<br>group_no_chronic = df.loc[df[&#39;AnyChronicDiseases&#39;] == 0, &#39;PremiumPrice&#39;]<br><br>t_stat, p_val = ttest_ind(group_chronic, group_no_chronic, equal_var=False)<br>print(f&quot;Chronic vs. No Chronic: t = {t_stat:.3f}, p = {p_val:.3e}&quot;)<br>if p_val/2 &lt; 0.05 and t_stat &gt; 0:<br>    print(&quot;Reject H₀: premiums are significantly higher when chronic diseases are present.&quot;)<br>else:<br>    print(&quot;Fail to reject H₀.&quot;)</pre><p><strong>🔍 Observation</strong>:<br> The t-value was 7.708 with a p-value of 1.728e-13.<br> ✅ We <strong>reject the null hypothesis</strong>: premiums are significantly higher for individuals with chronic conditions.</p><h4>🩺 One-Way ANOVA: Surgeries and Premium Differences</h4><p>Next, we assess whether the number of major surgeries (0, 1, 2, or 3) affects average premium cost.</p><p><strong>Hypotheses</strong>:</p><ul><li><strong>H₀</strong>: All group means are equal</li><li><strong>H₁</strong>: At least one group differs</li></ul><pre>surgery_groups = [<br>    df.loc[df[&#39;NumberOfMajorSurgeries&#39;] == i, &#39;PremiumPrice&#39;]<br>    for i in sorted(df[&#39;NumberOfMajorSurgeries&#39;].unique())<br>]<br><br>f_stat, p_val = f_oneway(*surgery_groups)<br>print(f&quot;\nANOVA across surgery counts: F = {f_stat:.3f}, p = {p_val:.3e}&quot;)<br>if p_val &lt; 0.05:<br>    print(&quot;Reject H₀: at least one surgery-count group differs in mean premium.&quot;)<br>else:<br>    print(&quot;Fail to reject H₀.&quot;)</pre><p><strong>🔍 Observation</strong>:<br> F = 26.135, p = 2.871e-16<br> ✅ We <strong>reject the null hypothesis</strong>: at least one surgery group has a significantly different mean premium.</p><h4>🔬 Chi-Square Test: Chronic Disease vs. Family History of Cancer</h4><p>To check for association between two binary features, we use the chi-square test.</p><p><strong>Hypotheses</strong>:</p><ul><li><strong>H₀</strong>: No association</li><li><strong>H₁</strong>: There is an association</li></ul><pre># Create a contingency table<br>contingency_table = pd.crosstab(df[&#39;AnyChronicDiseases&#39;], df[&#39;HistoryOfCancerInFamily&#39;])<br><br># Chi-Square test<br>chi2_stat, p_val, dof, expected = chi2_contingency(contingency_table)<br><br>print(&quot;=== Chi-Square Test: Chronic Disease vs. Family History of Cancer ===&quot;)<br>print(&quot;Contingency Table:&quot;)<br>print(contingency_table)<br>print(&quot;\nExpected Frequencies:&quot;)<br>print(pd.DataFrame(expected, <br>                   index=contingency_table.index, <br>                   columns=contingency_table.columns))<br>print(f&quot;\nChi-Square Statistic: {chi2_stat:.4f}&quot;)<br>print(f&quot;P-Value: {p_val:.4f}&quot;)<br>print(f&quot;Degrees of Freedom: {dof}&quot;)<br>if p_val &lt; 0.05:<br>    print(&quot;Result: Reject Null Hypothesis – Significant association found.&quot;)<br>else:<br>    print(&quot;Result: Fail to Reject Null – No significant association.&quot;)</pre><p><strong>🔍 Observation</strong>:<br> Chi² = 0.0206, p = 0.8858<br> ❌ We <strong>fail to reject the null hypothesis</strong>: there’s no significant association between chronic disease status and a family history of cancer.</p><p>We performed several more hypothesis tests to validate our assumptions, and here’s what we found:</p><ul><li><strong>T-tests</strong> confirmed that most health flags — like diabetes, blood pressure issues, transplants, chronic diseases, and family cancer history — are linked to significantly higher premiums. The only exception was <strong>KnownAllergies</strong>, which showed no significant impact (p ≈ 0.71).</li><li><strong>ANOVA results</strong> reinforced that the number of major surgeries strongly affects premium costs (F = 26.14, p &lt; 0.001), making it a key ordinal risk factor.</li><li>From <strong>chi-square tests</strong>, we found strong associations between diabetes and other conditions like BP problems, chronic disease, and allergies. Similarly, KnownAllergies were linked to a family history of cancer.</li><li>However, <strong>no significant relationship</strong> was found between chronic disease status and family cancer history (χ² = 0.02, p = 0.89), confirming they represent distinct health risk dimensions and can be modeled separately.</li></ul><h3>🧾 Quick Regression Check: Multivariate OLS Analysis</h3><p>After exploring the impact of individual variables through t-tests and ANOVA, we now shift to a more comprehensive view using a <strong>multivariate Ordinary Least Squares (OLS) regression</strong>. Unlike one-variable-at-a-time tests, OLS allows us to evaluate each feature’s contribution while <strong>controlling for all other factors</strong> — this helps uncover hidden interactions, reduce bias, and better quantify marginal effects.</p><pre>formula = &#39;PremiumPrice ~ Age + BMI + Diabetes + AnyChronicDiseases + NumberOfMajorSurgeries&#39;<br>model  = smf.ols(formula, data=df).fit()<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*gJ5ZTWGDyauOErPauNz2_g.png" /></figure><p>The OLS regression results confirmed some of our earlier findings while also revealing a few surprises. <strong>Age, BMI, and chronic disease status</strong> stood out as the most influential predictors, all highly significant with p-values well below 0.001 and strong effect sizes.</p><p>Interestingly, once we accounted for age and other health conditions, the <strong>diabetes variable flipped direction</strong>. It showed a small negative impact on premiums — about ₹663 lower on average. This likely points to <strong>collinearity</strong>, where diabetes risk is already captured by other stronger features like age or chronic illness.</p><p>Another unexpected result was that the <strong>number of major surgeries lost significance</strong> in the full model. With age and chronic disease in the mix, surgeries no longer added much explanatory power (p ≈ 0.12), suggesting they might overlap in the risk signals they convey.</p><p>Overall, the model delivered an <strong>R² of approximately 0.54</strong>, meaning these five features together explain about 54% of the variation in premium costs. That’s a solid start — but also a cue that more complex models might reveal deeper patterns.</p><p>And perhaps most useful from a practical standpoint: <strong>each extra year of age adds around ₹323 to the expected premium</strong>, all else being equal. This kind of clear, quantified insight is exactly what makes regression so valuable in shaping pricing strategies.</p><h3>6. 🌲 Implementing Tree-Based Models for Insurance Premium Prediction</h3><p>After establishing a strong linear baseline with OLS, we moved on to more flexible, non-linear models — specifically, <strong>Decision Trees</strong>, <strong>Random Forests</strong>, and <strong>Gradient Boosting Machines (GBM)</strong>. These algorithms are powerful in handling complex interactions, non-linear relationships, and varied data distributions — ideal for a domain like insurance pricing.</p><h4>6.1 Drop Unnecessary Columns</h4><p>We start by dropping Height, Weight, and the intermediate Height_m column since BMI already captures this information more meaningfully.</p><p>We start by dropping Height, Weight, and the intermediate Height_m column since BMI already captures this information more meaningfully.</p><pre>df.drop(columns=[&#39;Height&#39;, &#39;Weight&#39;, &#39;Height_m&#39;], inplace=True)</pre><h4>6.2 Define Features and Target</h4><p>Our target variable is PremiumPrice, and everything else becomes part of our feature matrix.</p><pre>X = df.drop(columns=[&#39;PremiumPrice&#39;])<br>y = df[&#39;PremiumPrice&#39;]</pre><h4>6.3 Scale Numerical Features</h4><p>We scale continuous features like Age, BMI, and NumberOfMajorSurgeries to ensure models that are sensitive to scale (like Gradient Boosting) perform optimally.</p><pre>num_cols = [&#39;Age&#39;, &#39;BMI&#39;, &#39;NumberOfMajorSurgeries&#39;]<br>scaler = StandardScaler()<br>X[num_cols] = scaler.fit_transform(X[num_cols])</pre><h4>6.4 Split Data into Train and Test Sets</h4><p>To evaluate model performance, we split the data using an 80/20 ratio.</p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><h4>6.5 Build and Evaluate Tree-Based Models</h4><p>We define three models and evaluate them using both cross-validation and test-set performance. For each model, we compute:</p><ul><li>Cross-validated R²</li><li>RMSE (Root Mean Squared Error)</li><li>MAE (Mean Absolute Error)</li><li>Test-set R²</li><li>Feature Importances</li></ul><pre>models = {<br>    &#39;Decision Tree&#39;  : DecisionTreeRegressor(random_state=42),<br>    &#39;Random Forest&#39;  : RandomForestRegressor(n_estimators=100, random_state=42),<br>    &#39;Gradient Boost&#39; : GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, random_state=42)<br>}<br><br>results = {}<br>for name, model in models.items():<br>    cv = KFold(n_splits=5, shuffle=True, random_state=42)<br>    cv_scores = cross_val_score(model, X, y, cv=cv, scoring=&#39;r2&#39;)<br><br>    model.fit(X_train, y_train)<br>    y_pred = model.predict(X_test)<br><br>    rmse = np.sqrt(mean_squared_error(y_test, y_pred))<br>    mae  = mean_absolute_error(y_test, y_pred)<br>    r2   = r2_score(y_test, y_pred)<br><br>    importances = model.feature_importances_<br><br>    results[name] = {<br>        &#39;CV R2 Mean&#39;: cv_scores.mean(),<br>        &#39;Test RMSE&#39; : rmse,<br>        &#39;Test MAE&#39;  : mae,<br>        &#39;Test R2&#39;   : r2,<br>        &#39;Importances&#39;: importances<br>    }</pre><h4>6.6 Review and Visualize Results</h4><p>Here, we display evaluation metrics and plot feature importances for each model to see which variables drove predictions.</p><pre>for name, res in results.items():<br>    print(f&quot;\n=== {name} ===&quot;)<br>    print(f&quot;CV R² Mean: {res[&#39;CV R2 Mean&#39;]:.4f}&quot;)<br>    print(f&quot;Test RMSE : {res[&#39;Test RMSE&#39;]:.2f}&quot;)<br>    print(f&quot;Test MAE  : {res[&#39;Test MAE&#39;]:.2f}&quot;)<br>    print(f&quot;Test R²   : {res[&#39;Test R2&#39;]:.4f}&quot;)<br><br>    plt.figure(figsize=(6,4))<br>    plt.barh(X.columns, res[&#39;Importances&#39;], color=&#39;skyblue&#39;)<br>    plt.title(f&quot;{name} Feature Importances&quot;)<br>    plt.xlabel(&#39;Importance&#39;)<br>    plt.gca().invert_yaxis()<br>    plt.tight_layout()<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*I6MC9H4r-jj9aWJUAaQ34Q.png" /><figcaption>Observation from Decision Tree</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*pTvrS8KjGQxKI4a7SuVKnQ.png" /><figcaption>Observation from Random Tree</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*niYQt_zX18qsHLax2Ua1Bg.png" /><figcaption>Observation from Gradient Boosting</figcaption></figure><p><strong><em>Model Comparison: Why Random Forest Stands Out</em></strong></p><p>After evaluating all three tree-based models, <strong>Random Forest</strong> clearly emerged as the most reliable and well-rounded performer.It achieved the <strong>highest test R² of 0.8625</strong>, meaning it explained more variance in premium prices than any other model on unseen data. It also delivered the <strong>lowest RMSE at ₹2,421</strong>, indicating that its predictions were closest to the actual premium values. While its cross-validated R² (0.7208) was slightly behind Gradient Boosting (0.7351), it <strong>generalized better</strong> when tested on new data — an essential quality for any production model.</p><p>In comparison, the <strong>Decision Tree</strong> model struggled the most. With a CV R² of around 0.50 and a higher RMSE of approximately ₹3,013, it was the least consistent, often overfitting to the training data. <strong>Gradient Boosting</strong> came in close behind Random Forest, offering good cross-validation results, but slightly under-delivering on the test set (R² = 0.8549, RMSE ≈ ₹2,487).</p><p>So, when we weigh both <strong>cross-validation stability</strong> and <strong>real-world accuracy</strong>, <strong>Random Forest</strong> stands as the top choice.</p><h4>6.7 Hyperparameter Tuning: Getting More from the Decision Tree</h4><p>While the default Decision Tree model gave us a decent starting point, it struggled with overfitting and lagged behind the ensemble models. To improve its performance, we ran a <strong>Grid Search</strong> to tune its hyperparameters.</p><p>We explored a range of values for key parameters like:</p><ul><li>max_depth – how deep the tree can grow</li><li>min_samples_split and min_samples_leaf – to control overfitting by limiting how splits are made</li><li>max_features – to restrict the number of features considered at each split</li></ul><p>The goal: optimize the model using <strong>5-fold cross-validation</strong>, with <strong>R² as the scoring metric</strong>.</p><pre># Define Decision Tree and parameter grid<br>dt = DecisionTreeRegressor(random_state=42)<br>param_grid = {<br>    &#39;max_depth&#39;         : [None, 3, 5, 7, 10],<br>    &#39;min_samples_split&#39; : [2, 5, 10],<br>    &#39;min_samples_leaf&#39;  : [1, 2, 4],<br>    &#39;max_features&#39;      : [None, &#39;sqrt&#39;, &#39;log2&#39;]<br>}<br><br># Grid search with 5-fold CV optimizing R²<br>grid = GridSearchCV(<br>    dt, <br>    param_grid, <br>    cv=5, <br>    scoring=&#39;r2&#39;, <br>    n_jobs=-1,<br>    verbose=1<br>)<br>grid.fit(X_train, y_train)</pre><p>After evaluating <strong>135 combinations</strong> of hyperparameters across <strong>5 cross-validation folds</strong> — a total of <strong>675 fits</strong> — we found the optimal configuration for our Decision Tree mode. This tuned setup strikes a strong balance between model complexity and generalization. A max_depth of 5 prevents the tree from growing too deep (and overfitting), while requiring at least 2 samples at each leaf and 10 to split ensures robustness. Keeping max_features as None allows the tree to consider all available features at each split.</p><h4>6.8 Test Set Evaluation</h4><pre># Evaluate the tuned tree on the test set<br>best_dt = grid.best_estimator_<br>y_pred_dt = best_dt.predict(X_test)<br><br>rmse_dt = np.sqrt(mean_squared_error(y_test, y_pred_dt))<br>mae_dt  = mean_absolute_error(y_test, y_pred_dt)<br>r2_dt   = r2_score(y_test, y_pred_dt)<br><br>print(&quot;\nTuned Decision Tree Performance on Test Set:&quot;)<br>print(f&quot;  RMSE: {rmse_dt:.2f}&quot;)<br>print(f&quot;  MAE : {mae_dt:.2f}&quot;)<br>print(f&quot;  R²  : {r2_dt:.4f}&quot;)</pre><h3>7. Model Performance Recap: How the Tuned Tree Compares</h3><p>After tuning our Decision Tree, we benchmarked it against its default version and two powerful ensemble models: Random Forest and Gradient Boosting. Here’s how they stacked up across key metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5zTWPjaAImrLhc6WIsncJg.png" /></figure><h3>What We Learned</h3><p>The <strong>default Decision Tree</strong> model already offered an improvement over linear methods, reducing RMSE and boosting R². However, it suffered from <strong>overfitting</strong>, as seen in the large gap between its cross-validated and test R² scores.</p><p>After tuning, the <strong>Decision Tree performed considerably better</strong>, bringing RMSE down to ₹2.75K and raising R² to 0.82. Cross-validation scores also improved, showing a more balanced generalization. Interestingly, the tuned tree showed a slightly higher MAE (₹1.76K) compared to the default (~₹1.33K), suggesting it’s making fewer large errors but slightly more mid-range ones — a trade-off worth noting.</p><p>Even so, <strong>ensemble models still lead the pack</strong>. Both <strong>Random Forest</strong> and <strong>Gradient Boosting</strong> outperform the tuned tree on nearly every metric:</p><ul><li><strong>Random Forest</strong> achieved the lowest RMSE (~₹2.42K) and highest test R² (~0.86), making it the most accurate all-around.</li><li><strong>Gradient Boosting</strong> was a close second, particularly excelling in cross-validation consistency.</li></ul><h3>8. 🌐 Streamlit App: Bringing the Model to Life</h3><p>To make this project more interactive and accessible, I deployed the final model using <strong>Streamlit</strong>, a lightweight Python framework for building data apps. The result is a simple web-based tool where users can estimate their annual health insurance premium by entering personal health details.</p><p>The app loads the <strong>tuned Decision Tree model</strong> and its corresponding <strong>scaler</strong> from disk using joblib, then processes user input through a form. Here’s a quick breakdown of the logic:</p><ul><li>User inputs include age, height, weight, and health flags like diabetes or chronic disease.</li><li>BMI is calculated dynamically from height and weight.</li><li>Numerical features (Age, BMI, NumberOfMajorSurgeries) are scaled using the same scaler used during training.</li><li>The model then predicts the premium in real time and displays it using st.success().</li></ul><pre># Load model and scaler<br>scaler = joblib.load(&#39;models/scaler.joblib&#39;)<br>model  = joblib.load(&#39;models/tuned_dt.joblib&#39;)<br><br># Streamlit form<br>age = st.slider(&quot;Age&quot;, 18, 66, 30)<br>height = st.number_input(&quot;Height (cm)&quot;, 145, 188)<br>weight = st.number_input(&quot;Weight (kg)&quot;, 50, 132)<br># ...additional fields...<br># Calculate BMI and scale features<br>df[&#39;BMI&#39;] = df[&#39;Weight&#39;] / ((df[&#39;Height&#39;]/100)**2)<br>df = df.drop(columns=[&#39;Height&#39;, &#39;Weight&#39;])<br>df[[&#39;Age&#39;,&#39;BMI&#39;,&#39;NumberOfMajorSurgeries&#39;]] = scaler.transform(df[[&#39;Age&#39;,&#39;BMI&#39;,&#39;NumberOfMajorSurgeries&#39;]])<br># Predict<br>premium = model.predict(df)[0]<br>st.success(f&quot;Estimated Annual Premium: ₹{premium:,.2f}&quot;)</pre><p><strong><em>Stream lit Deployment:</em></strong><em> </em><a href="https://app-insurance-premium-app-khb24aerhbzajoynnzixvn.streamlit.app/"><em>https://app-insurance-premium-app-khb24aerhbzajoynnzixvn.streamlit.app/</em></a></p><p>This deployment turns a static ML model into a <strong>dynamic, user-friendly experience</strong> — perfect for showcasing your skills in both machine learning and application development.</p><h3>9. 🚀 Recommendations</h3><ul><li><strong>Go with Random Forest</strong> if you want the best out-of-the-box performance with strong generalization.</li><li>Use the <strong>tuned Decision Tree</strong> when interpretability is crucial — for example, in explainable underwriting models where visualizing splits helps inform decisions.</li><li>Consider <strong>hyperparameter tuning</strong> for Random Forest and Gradient Boosting next. A few carefully chosen tweaks could push these models even closer to their full potential.</li></ul><h3>🙌 Let’s Connect!</h3><p>If you found this project insightful or want to explore the code in more detail, feel free to check out the full repository or reach out on LinkedIn:</p><p>🔗 <strong>GitHub Repository</strong>: <a href="https://github.com/Shubhashi01/streamlit-insurance-premium-app">https://github.com/Shubhashi01/streamlit-insurance-premium-app</a><br> 🔗 <strong>LinkedIn</strong>: <a href="http://www.linkedin.com/in/shubhashi-gupta-685b5a133">www.linkedin.com/in/shubhashi-gupta-685b5a133</a></p><p>I’d love to hear your thoughts, answer any questions, or just connect with fellow data enthusiasts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7b09544b7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>