<?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 Jithmini Kulatunga on Medium]]></title>
        <description><![CDATA[Stories by Jithmini Kulatunga on Medium]]></description>
        <link>https://medium.com/@jithminikulatunga?source=rss-3e46fcde6dd7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gdBWpyaFVBa7zMqP</url>
            <title>Stories by Jithmini Kulatunga on Medium</title>
            <link>https://medium.com/@jithminikulatunga?source=rss-3e46fcde6dd7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:05:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jithminikulatunga/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[Loan Eligibility Prediction using Machine Learning Models in Python]]></title>
            <link>https://medium.com/@jithminikulatunga/loan-eligibility-prediction-using-machine-learning-models-in-python-7df72fbb9260?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7df72fbb9260</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 13:39:42 GMT</pubDate>
            <atom:updated>2026-11-12T13:39:42.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqzGNv6xW-3cix-4sDPeSw.png" /></figure><p>Have you ever thought about the apps that can predict whether you will get your loan approved or not? In this article, we are going to develop one such model that can predict whether a person will get his/her loan approved or not by using some of the background information of the applicant like the applicant’s gender, marital status, income, etc.</p><h3>Step 1: Importing Libraries</h3><p>In this step, we will be importing libraries like <a href="https://www.geeksforgeeks.org/numpy/python-numpy/">NumPy</a>, <a href="https://www.geeksforgeeks.org/pandas/pandas-tutorial/">Pandas</a>, <a href="https://www.geeksforgeeks.org/python/python-introduction-matplotlib/">Matplotlib</a>, etc.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sb<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder, StandardScaler<br>from sklearn import metrics<br>from sklearn.svm import SVC<br>from imblearn.over_sampling import RandomOverSampler<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h3>Step 2: Loading Dataset</h3><pre>df = pd.read_csv(&#39;loan_data.csv&#39;)<br>df.head()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*nJjHFeiFErzjhGXR.png" /></figure><p>To see the shape of the dataset, we can use <strong>shape</strong> method.</p><pre>df.shape</pre><p><strong>Output:</strong></p><pre>(598, 6)</pre><p>To print the information of the dataset, we can use <a href="https://www.geeksforgeeks.org/python/python-pandas-dataframe-info/"><strong>info()</strong></a> method</p><pre>df.info()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*3raQ2nzR4LNIPYcX.png" /></figure><p>To get values like the mean, count and min of the column we can use<strong> describe() </strong>method.</p><pre>df.describe()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/0*RFiKjBaR0aAhSccq.png" /></figure><h3>Step 3: Exploratory Data Analysis</h3><p>EDA refers to the detailed analysis of the dataset which uses plots like distplot, barplots, etc.</p><p>Let’s start by plotting the <a href="https://www.geeksforgeeks.org/data-science/plot-a-pie-chart-in-python-using-matplotlib/">piechart</a> for LoanStatus column.</p><pre>temp = df[&#39;Loan_Status&#39;].value_counts()<br>plt.pie(temp.values,<br>        labels=temp.index,<br>        autopct=&#39;%1.1f%%&#39;)<br>plt.show()</pre><p><strong>Output</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*Gx0JIA1iKXqXXMmC.png" /></figure><p>Here we have an imbalanced dataset. We will have to balance it before training any model on this data.</p><p>We specify the DataFrame df as the data source for the sb.countplot() function. The x parameter is set to the column name from which the count plot is to be created, and hue is set to &#39;Loan_Status&#39; to create count bars based on the &#39;Loan_Status&#39; categories.</p><pre>plt.subplots(figsize=(15, 5))<br>for i, col in enumerate([&#39;Gender&#39;, &#39;Married&#39;]):<br>    plt.subplot(1, 2, i+1)<br>    sb.countplot(data=df, x=col, hue=&#39;Loan_Status&#39;)<br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XK0u7Bmthse6idRG.png" /></figure><p>One of the main observations we can draw here is that the chances of getting a loan approved for married people are quite low compared to those who are not married.</p><pre>plt.subplots(figsize=(15, 5))<br>for i, col in enumerate([&#39;ApplicantIncome&#39;, &#39;LoanAmount&#39;]):<br>    plt.subplot(1, 2, i+1)<br>    sb.distplot(df[col])<br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zcw3KYQ_FjwR2LT2.png" /></figure><p>To find out the outliers in the columns, we can use <a href="https://www.geeksforgeeks.org/python/boxplot-using-seaborn-in-python/">boxplot</a>.</p><pre>plt.subplots(figsize=(15, 5))<br>for i, col in enumerate([&#39;ApplicantIncome&#39;, &#39;LoanAmount&#39;]):<br>    plt.subplot(1, 2, i+1)<br>    sb.boxplot(df[col])<br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9r1YDDq9EI2n5XV.png" /></figure><p>There are some extreme outlier’s in the data we need to remove them.</p><pre>df = df[df[&#39;ApplicantIncome&#39;] &lt; 25000]<br>df = df[df[&#39;LoanAmount&#39;] &lt; 400000]</pre><p>Let’s see the mean amount of the loan granted to males as well as females. For that, we will use <a href="https://www.geeksforgeeks.org/python/pandas-groupby-count-occurrences-in-column/"><strong>groupyby() </strong></a>method.</p><pre>df.groupby(&#39;Gender&#39;).mean(numeric_only=True)[&#39;LoanAmount&#39;]</pre><p><strong>Output:</strong></p><pre>Gender	  LoanAmount<br>Female	  126.697248<br>Male	      146.872294<br>dtype: float64</pre><p>The loan amount requested by males is higher than what is requested by females.</p><pre>df.groupby([&#39;Married&#39;, &#39;Gender&#39;]).mean(numeric_only=True)[&#39;LoanAmount&#39;]</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*BC3aVDErhNAJL90F.png" /></figure><p>Here is one more interesting observation in addition to the previous one that the married people requested loan amount is generally higher than that of the unmarried. This may be one of the reason’s that we observe earlier that the chances of getting loan approval for a married person are lower than that compared to an unmarried person.</p><pre># Function to apply label encoding<br>def encode_labels(data):<br>    for col in data.columns:<br>        if data[col].dtype == &#39;object&#39;:<br>            le = LabelEncoder()<br>            data[col] = le.fit_transform(data[col])<br><br>    return data<br><br># Applying function in whole column<br>df = encode_labels(df)<br># Generating Heatmap<br>sb.heatmap(df.corr() &gt; 0.8, annot=True, cbar=False)<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*_km6wJq1-qVpkAoz.png" /></figure><h3>Step 4: Data Preprocessing</h3><p>In this step, we will split the data for training and testing. After that, we will preprocess the training data.</p><pre>features = df.drop(&#39;Loan_Status&#39;, axis=1) <br>target = df[&#39;Loan_Status&#39;].values <br><br>X_train, X_val, Y_train, Y_val = train_test_split(features, target, <br>         test_size=0.2, <br>         random_state=10) <br># As the data was highly imbalanced we will balance <br># it by adding repetitive rows of minority class. <br>ros = RandomOverSampler(sampling_strategy=&#39;minority&#39;, <br>      random_state=0) <br>X, Y = ros.fit_resample(X_train, Y_train) <br>X_train.shape, X.shape</pre><p><strong>Output:</strong></p><pre>((456, 5), (638, 5))</pre><p>We will now use Standard scaling for normalizing the data. To know more about StandardScaler refer this <a href="https://www.geeksforgeeks.org/python/how-to-scale-pandas-dataframe-columns/">link</a>.</p><pre># Normalizing the features for stable and fast training.<br>scaler = StandardScaler()<br>X = scaler.fit_transform(X)<br>X_val = scaler.transform(X_val)</pre><h3>Step 5: Model Development</h3><p>We will use <a href="https://www.geeksforgeeks.org/machine-learning/support-vector-machine-algorithm/">Support Vector Classifier</a> for training the model.</p><pre>from sklearn.metrics import roc_auc_score<br>model = SVC(kernel=&#39;rbf&#39;)<br>model.fit(X, Y)<br><br>print(&#39;Training Accuracy : &#39;, metrics.roc_auc_score(Y, model.predict(X)))<br>print(&#39;Validation Accuracy : &#39;, metrics.roc_auc_score(Y_val, model.predict(X_val)))<br>print()</pre><p><strong>Output:</strong></p><pre>Training Accuracy :  0.6300940438871474<br>Validation Accuracy :  0.48198198198198194</pre><h3>Step 6: Model Evaluation</h3><p>Model Evaluation can be done using <a href="https://www.geeksforgeeks.org/machine-learning/confusion-matrix-machine-learning/">confusion matrix</a>.</p><p>we first train the SVC model using the training data X and Y. Then, we calculate the ROC AUC scores for both the training and validation datasets. The confusion matrix is built for the validation data by using the confusion_matrix function from sklearn.metrics. Finally, we plot the confusion matrix using the plot_confusion_matrix function from the sklearn.metrics.plot_confusion_matrix submodule.</p><pre>from sklearn.svm import SVC<br>from sklearn.metrics import confusion_matrix<br>training_roc_auc = roc_auc_score(Y, model.predict(X))<br>validation_roc_auc = roc_auc_score(Y_val, model.predict(X_val))<br>print(&#39;Training ROC AUC Score:&#39;, training_roc_auc)<br>print(&#39;Validation ROC AUC Score:&#39;, validation_roc_auc)<br>print()<br>cm = confusion_matrix(Y_val, model.predict(X_val))</pre><p><strong>Output:</strong></p><pre>Training ROC AUC Score: 0.6300940438871474<br>Validation ROC AUC Score: 0.48198198198198194</pre><pre>plt.figure(figsize=(6, 6))<br>sb.heatmap(cm, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;, cbar=False)<br>plt.title(&#39;Confusion Matrix&#39;)<br>plt.xlabel(&#39;Predicted Label&#39;)<br>plt.ylabel(&#39;True Label&#39;)<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*QzAYUI7axrP2bXe7.png" /></figure><pre>from sklearn.metrics import classification_report<br>print(classification_report(Y_val, model.predict(X_val)))</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*5GEVrSmHzBMohrBE.png" /></figure><p>As this dataset contains fewer features the performance of the model is not up to the mark maybe if we will use a better and big dataset we will be able to achieve better accuracy.</p><p>You can download the dataset and source code from here:</p><ul><li><strong>Dataset: </strong><a href="https://media.geeksforgeeks.org/wp-content/uploads/20250117025332187854/loan_data.csv">Load Eligibility Dataset</a></li><li><strong>Source Code:</strong><a href="https://media.geeksforgeeks.org/wp-content/uploads/20250402152938031115/Loan_Eligibility_prediction_using_Machine_Learning_Models_in_Python.ipynb"><strong> </strong>Loan Eligibility Prediction using Machine Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7df72fbb9260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loan Approval Prediction using Machine Learning]]></title>
            <link>https://medium.com/@jithminikulatunga/loan-approval-prediction-using-machine-learning-06ed496cba38?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/06ed496cba38</guid>
            <category><![CDATA[loan-approvals]]></category>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 13:05:39 GMT</pubDate>
            <atom:updated>2026-11-12T13:05:39.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-Hlr6Z-HaYMYdCIrP_rZg.png" /></figure><p>Loans are a major requirement of the modern world. By this alone, banks receive a major portion of the total profit. It is beneficial for students to manage their education and living expenses, and for individuals to purchase various luxuries, such as houses and cars. But when it comes to deciding whether the applicant’s profile is relevant to be granted with loan or not. Banks have to look after many aspects.</p><p>So, here we will be using machine learning algorithms to ease their work and predict whether the candidate’s profile is relevant or not, using key features like Marital Status, Education, Applicant Income, Credit History, etc.</p><h3>Loan Approval Prediction using Machine Learning</h3><blockquote>You can download the used data by visiting this <a href="https://drive.google.com/file/d/1LIvIdqdHDFEGnfzIgEh4L6GFirzsE3US/view?usp=sharing">link</a>.</blockquote><p>The dataset contains 13 features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*9i3UXNz386DNKWXS4sxc3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*F3ELEVRcAL_Rejof-ldeDQ.png" /></figure><h3>Importing Libraries and Dataset</h3><p>Firstly we have to import libraries:</p><ul><li><a href="https://www.geeksforgeeks.org/pandas/python-pandas-dataframe/">Pandas</a> — To load the Dataframe</li><li><a href="https://www.geeksforgeeks.org/python/python-matplotlib-an-overview/">Matplotlib</a> — To visualize the data features i.e. barplot</li><li><a href="https://www.geeksforgeeks.org/python/introduction-to-seaborn-python/">Seaborn</a> — To see the correlation between features using heatmap</li></ul><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>data = pd.read_csv(&quot;LoanApprovalPrediction.csv&quot;)</pre><p>Once we imported the dataset, let’s view it using the below command.</p><pre>data.head(5)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*f-0Oe2TeKCTT-RdR.PNG" /></figure><h3>Data Preprocessing and Visualization</h3><p>Get the number of columns of object datatype.</p><pre>obj = (data.dtypes == &#39;object&#39;)<br>print(&quot;Categorical variables:&quot;,len(list(obj[obj].index)))</pre><p><strong>Output :</strong></p><pre>Categorical variables: 7</pre><p>As Loan_ID is completely unique and not correlated with any of the other column, So we will drop it using .<a href="https://www.geeksforgeeks.org/python/python-delete-rows-columns-from-dataframe-using-pandas-drop/">drop()</a> function.</p><pre># Dropping Loan_ID column<br>data.drop([&#39;Loan_ID&#39;],axis=1,inplace=True)</pre><p>Visualize all the unique values in columns using <a href="https://www.geeksforgeeks.org/pandas/bar-plot-in-matplotlib/">barplot</a>. This will simply show which value is dominating as per our dataset.</p><pre>obj = (data.dtypes == &#39;object&#39;)<br>object_cols = list(obj[obj].index)<br>plt.figure(figsize=(18,36))<br>index = 1<br><br>for col in object_cols:<br>  y = data[col].value_counts()<br>  plt.subplot(11,4,index)<br>  plt.xticks(rotation=90)<br>  sns.barplot(x=list(y.index), y=y)<br>  index +=1</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-HRkjaIgwQxOp2pbM4Iog.jpeg" /></figure><p>As all the categorical values are binary so we can use <a href="https://www.geeksforgeeks.org/machine-learning/ml-label-encoding-of-datasets-in-python/">Label Encoder</a> for all such columns and the values will change into <strong>int</strong> datatype.</p><pre># Import label encoder<br>from sklearn import preprocessing<br>  <br># label_encoder object knows how <br># to understand word labels.<br>label_encoder = preprocessing.LabelEncoder()<br>obj = (data.dtypes == &#39;object&#39;)<br>for col in list(obj[obj].index):<br>  data[col] = label_encoder.fit_transform(data[col])</pre><p>Again check the object datatype columns. Let’s find out if there is still any left.</p><pre># To find the number of columns with <br># datatype==object<br>obj = (data.dtypes == &#39;object&#39;)<br>print(&quot;Categorical variables:&quot;,len(list(obj[obj].index)))</pre><p><strong>Output :</strong></p><pre>Categorical variables: 0</pre><pre>plt.figure(figsize=(12,6))<br><br>sns.heatmap(data.corr(),cmap=&#39;BrBG&#39;,fmt=&#39;.2f&#39;,<br>            linewidths=2,annot=True)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*meKzCSVXD6WIQ3Dj.PNG" /></figure><p>The above heatmap is showing the correlation between Loan Amount and ApplicantIncome. It also shows that Credit_History has a high impact on Loan_Status.</p><p>Now we will use <a href="https://www.geeksforgeeks.org/machine-learning/python-seaborn-catplot/">Catplot</a> to visualize the plot for the Gender, and Marital Status of the applicant.</p><pre>sns.catplot(x=&quot;Gender&quot;, y=&quot;Married&quot;,<br>            hue=&quot;Loan_Status&quot;, <br>            kind=&quot;bar&quot;, <br>            data=data)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*otfCYACFWWXghWZp.PNG" /></figure><p>Now we will find out if there is any missing values in the dataset using below code.</p><pre>for col in data.columns:<br>  data[col] = data[col].fillna(data[col].mean()) <br>  <br>data.isna().sum()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/0*zm4r4o-euCxuJqiv.png" /></figure><p>As there is no missing value then we must proceed to model training.</p><h3>Splitting Dataset</h3><pre>from sklearn.model_selection import train_test_split<br><br>X = data.drop([&#39;Loan_Status&#39;],axis=1)<br>Y = data[&#39;Loan_Status&#39;]<br>X.shape,Y.shape<br>X_train, X_test, Y_train, Y_test = train_test_split(X, Y,<br>                                                    test_size=0.4,<br>                                                    random_state=1)<br>X_train.shape, X_test.shape, Y_train.shape, Y_test.shape</pre><p><strong>Output:</strong></p><pre>((358, 11), (240, 11), (358,), (240,))</pre><h3>Model Training and Evaluation</h3><p>As this is a classification problem so we will be using these models :</p><ul><li><a href="https://www.geeksforgeeks.org/machine-learning/k-nearest-neighbor-algorithm-in-python/">KNeighborsClassifiers</a></li><li><a href="https://www.geeksforgeeks.org/dsa/random-forest-classifier-using-scikit-learn/">RandomForestClassifiers</a></li><li><a href="https://www.geeksforgeeks.org/machine-learning/classifying-data-using-support-vector-machinessvms-in-python/">Support Vector Classifiers (SVC)</a></li><li><a href="https://www.geeksforgeeks.org/machine-learning/understanding-logistic-regression/">Logistics Regression</a></li></ul><p>To predict the accuracy we will use the accuracy score function from <a href="https://www.geeksforgeeks.org/machine-learning/learning-model-building-scikit-learn-python-machine-learning-library/">scikit-learn</a> library.</p><pre>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.svm import SVC<br>from sklearn.linear_model import LogisticRegression<br><br>from sklearn import metrics<br>knn = KNeighborsClassifier(n_neighbors=3)<br>rfc = RandomForestClassifier(n_estimators = 7,<br>                             criterion = &#39;entropy&#39;,<br>                             random_state =7)<br>svc = SVC()<br>lc = LogisticRegression()<br># making predictions on the training set<br>for clf in (rfc, knn, svc,lc):<br>    clf.fit(X_train, Y_train)<br>    Y_pred = clf.predict(X_train)<br>    print(&quot;Accuracy score of &quot;,<br>          clf.__class__.__name__,<br>          &quot;=&quot;,100*metrics.accuracy_score(Y_train, <br>                                         Y_pred))</pre><p><strong>Output :</strong></p><blockquote>Accuracy score of RandomForestClassifier = 98.04469273743017</blockquote><blockquote>Accuracy score of KNeighborsClassifier = 78.49162011173185</blockquote><blockquote>Accuracy score of SVC = 68.71508379888269</blockquote><blockquote>Accuracy score of LogisticRegression = 80.44692737430168</blockquote><p><strong>Prediction on the test set:</strong></p><pre># making predictions on the testing set<br>for clf in (rfc, knn, svc,lc):<br>    clf.fit(X_train, Y_train)<br>    Y_pred = clf.predict(X_test)<br>    print(&quot;Accuracy score of &quot;,<br>          clf.__class__.__name__,&quot;=&quot;,<br>          100*metrics.accuracy_score(Y_test,<br>                                     Y_pred))</pre><p><strong>Output :</strong></p><blockquote>Accuracy score of RandomForestClassifier = 82.5</blockquote><blockquote>Accuracy score of KNeighborsClassifier = 63.74999999999999</blockquote><blockquote>Accuracy score of SVC = 69.16666666666667</blockquote><blockquote>Accuracy score of LogisticRegression = 80.83333333333333</blockquote><p>Random Forest Classifier is giving the best accuracy with an accuracy score of 82% for the testing dataset. And to get much better results ensemble learning techniques like <a href="https://www.geeksforgeeks.org/machine-learning/bagging-vs-boosting-in-machine-learning/"><strong>Bagging </strong></a>and <strong>Boosting </strong>can also be used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06ed496cba38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Click-Through Rate Prediction using Machine Learning]]></title>
            <link>https://medium.com/@jithminikulatunga/click-through-rate-prediction-using-machine-learning-2058a0a0c9ee?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2058a0a0c9ee</guid>
            <category><![CDATA[click-through-rate]]></category>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 12:20:55 GMT</pubDate>
            <atom:updated>2026-11-12T12:20:55.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obrNDY459TpEB-uGsU2QMg.png" /></figure><p><strong><em>Predicting the click-through Rate (CTR) </em></strong>is crucial for optimizing online advertising campaigns. By accurately estimating the likelihood of a user clicking on an ad, businesses can make informed decisions about ad placement and design, ultimately maximizing their return on investment (ROI).</p><p>In this article, we will explore how to use the<strong><em> eXtreme Gradient Boosting (XGBoost) algorithm</em></strong>, a popular and powerful machine learning technique, to predict CTR. We will start by understanding the basics of CTR prediction and then delve into implementing a CTR prediction model using XGBoost in Python.</p><h3>What is Click-Through Rate?</h3><p>Click-Through Rate is calculated as the number of clicks an ad receives divided by the number of times the ad is shown (impressions), expressed as a percentage. The CTR prediction task involves modeling the likelihood of a click based on ad characteristics, user profile data, and contextual features.</p><h3>Why XGBoost for Click-Through Rate Prediction?</h3><p><a href="https://www.geeksforgeeks.org/machine-learning/xgboost/">XGBoos</a>t is an ensemble learning method, meaning it builds a strong predictive model by combining multiple weak models, typically decision trees, in a sequential manner. It iteratively trains new models to correct errors made by previous models, with each new model focusing on the residuals or errors of the previous models.</p><p>XGBoost is a popular choice for CTR prediction because of several key features:</p><ul><li><strong>Gradient Boosting Framework</strong>: XGBoost is based on the gradient boosting framework, which builds models sequentially to correct the residuals of previous models.</li><li><strong>Regularization</strong>: It incorporates both L1 and L2 regularization, which helps prevent overfitting — a common issue with standard boosting techniques.</li><li><strong>Scalability and Efficiency</strong>: XGBoost is highly scalable and can handle large datasets efficiently, thanks to its parallel processing and tree pruning methods.</li><li><strong>Handling Sparse Data</strong>: XGBoost can handle sparse data from one-hot encoding of categorical variables without extensive memory consumption.</li><li><strong>Flexibility</strong>: It can be used for both regression and classification tasks and allows for custom optimization objectives and evaluation criteria.</li></ul><h3>Predicting Click-Through Rate with XGBoost</h3><p>This section discusses the steps to predict the click-through rate with the help of the XGBoost algorithm. The <a href="https://media.geeksforgeeks.org/wp-content/uploads/20240430115227/ad_10000records.csv">dataset </a>contains 10 columns, with 9 of them representing an instance of a data record as features. We will be predicting the “Clicked on Ad” column, which represents if the visitor clicks on the ad.</p><p>Follow the steps given below to create a click-through rate prediction model using the XGBoost algorithm:</p><h3>Step 1: Import Necessary Libraries</h3><ul><li>In this step, you will be importing the necessary libraries that you can use to predict the click-through rate.</li><li>It includes data manipulation libraries such as <strong>pandas</strong> and <strong>numpy</strong>, <strong>LabelEncoder</strong> to encode the categorical features into numerical value, <strong>train_test_split</strong> to split the dataset into training and test sets, <strong>XGBoost</strong> library to leverage its powers to predict the clicks, and <strong>accuracy_score</strong> to measure how our model performs.</li></ul><pre>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.model_selection import train_test_split<br>from xgboost import XGBClassifier as xgb<br>from sklearn.metrics import accuracy_score</pre><h3>Step 2: Reading Data and Performing Basic Analysis</h3><pre>data = pd.read_csv(&quot;ad_10000records.csv&quot;)<br>print(data.head())</pre><p><strong>Output:</strong></p><pre>Daily Time Spent on Site     Age              Area Income                Daily Internet Usage  \<br>0                         62.26                     32.                  69481.85                              172.83   <br>1                          41.73                      31.0                 61840.26                             207.17   <br>2                         44.40                     30.0                57877.15                               172.83   <br>3                         59.88                     28.0                56180.93                              207.17   <br>4                         49.21                      30.0                54324.73                              201.58   </pre><pre>                         Ad Topic Line                                     City                                    Gender  \<br>0         Decentralized real-time circuit                 Lisafort                                   Male   <br>1          Optional full-range projection             West Angelabury                       Male   <br>2      Total 5thgeneration standardization           Reyesfurt                              Female   <br>3          Balanced empowering success              New Michael                         Female   <br>4      Total 5thgeneration standardization         West Richard                         Female   </pre><pre>                              Country                                         Timestamp                     Clicked on Ad  <br>0          Svalbard &amp; Jan Mayen Islands         2016-06-09 21:43:05                        0   <br>1                           Singapore                            2016-01-16 17:56:05                          0  <br>2                         Guadeloupe                          2016-06-29 10:50:45                        0  <br>3                             Zambia                               2016-06-21 14:32:32                          0  <br>4                               Qatar                                2016-07-21 10:54:35                          1</pre><p>In the above output, “Clicked on Ad” column, 0 represents the users not clicking on the ad, and 1 represents the user who click on the ads. Let’s look at the total value counts of the combined 0’s and 1’s and check for the click through rate.</p><pre>print(data[&quot;Clicked on Ad&quot;].value_counts())<br><br># Click through rate<br>click_through_rate = 4917 / 10000 * 100<br>print(f&quot;The click through rate is: {click_through_rate}%&quot;)</pre><p><strong>Output</strong>:</p><pre>0    5083<br>1    4917<br>The click through rate is: 49.17%</pre><p>From the above information, we get 49.17% of the total visitors clicking on the ads. After this step we can transform the “Gender” column into numeric values so that the data can be fit in the machine learning model.</p><h3>Step 3: Data Preprocessing</h3><p>This encodes the “Gender” variable into numeric values.</p><pre>le = LabelEncoder()<br><br>data[&quot;Gender&quot;] = le.fit_transform(data[&quot;Gender&quot;])</pre><p>In this step, you will be splitting the dataset into feature and target set and then again splitting it into training and test dataset to train and test your model on.</p><pre># Taking the first seven columns of the dataset as features<br>x=data.iloc[:,0:7]<br># Dropping the Categorical Variables<br>x=x.drop([&#39;Ad Topic Line&#39;,&#39;City&#39;],axis=1)<br><br># Assigning the final variable as the target variable<br>y=data.iloc[:,9]<br># Using train test split to split the dataset<br>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)</pre><h3>Step 4: Defining &amp; Training a XGBoost Classifier Model</h3><p>In this step, you create your XGBClassifier model and train it on the training dataset created in the previous step.</p><pre># XGBoostClassifier model<br>model = xgb(random_state=42)<br><br># Training the model<br>model.fit(x_train, y_train)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*v6v4fQUDKj7XH_Cj.PNG" /></figure><h3>Step 5: Predicting &amp; Checking Accuracy of the Model</h3><p>Finally, you will be predicting the model’s performance on the test dataset and check its accuracy against the original values.</p><pre># Predicting test dataset values with the model<br>y_pred = model.predict(x_test)<br><br># Accuracy check of the model prediction<br>print(&quot;The model accuracy is&quot;, accuracy_score(y_test,y_pred))</pre><p><strong>Output</strong>:</p><pre>The model accuracy is 0.81</pre><p>So, the model is accurate almost 81% of the times.</p><h3>Conclusion</h3><p>The article highlights the importance of click-through rate and how you can predict the visitor behavior on the basis of a few features. Having a good knowledge of how advertisement works is essential for any business to flourish and click-through rate is an essential metric. With the help of proper monitoring and analysis of CTR, you can get knowledgable insights about you business and how you can work on ad campaign to increase revenue.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2058a0a0c9ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flipkart Reviews Sentiment Analysis using Python]]></title>
            <link>https://medium.com/@jithminikulatunga/flipkart-reviews-sentiment-analysis-using-python-e7b9412f896d?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b9412f896d</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 12:10:14 GMT</pubDate>
            <atom:updated>2026-11-12T12:10:14.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoM5FzUz8pBlayxLP5ECxw.png" /></figure><p>Sentiment analysis is a NLP task used to determine the sentiment behind textual data. In context of product reviews it helps in understanding whether the feedback given by customers is positive, negative or neutral. It helps businesses gain valuable insights about customer experiences, product quality and brand perception. It helps in improving product quality and refining customer service strategies.</p><p>In this article, we will explore how to apply machine learning techniques to perform sentiment analysis on Flipkart reviews.</p><h3>Code Implementation of Sentiment Analysis on Flipkart Reviews</h3><h3>1. Importing Libraries and Dataset</h3><p>We will be using libraries like <a href="https://www.geeksforgeeks.org/pandas/introduction-to-pandas-in-python/"><strong>Pandas</strong></a><strong>, </strong><a href="https://www.geeksforgeeks.org/machine-learning/what-is-python-scikit-library/"><strong>Scikit-learn</strong></a>, <a href="https://www.geeksforgeeks.org/python/NLTK-NLP/"><strong>NLTK</strong></a><strong>, </strong><a href="https://www.geeksforgeeks.org/python/python-introduction-matplotlib/"><strong>Matplotlib</strong></a>, <a href="https://www.geeksforgeeks.org/python/generate-word-clouds-of-any-shape-in-python/"><strong>Wordcloud</strong></a><strong> </strong>and <a href="https://www.geeksforgeeks.org/python/introduction-to-seaborn-python/"><strong>Seaborn</strong></a> for this. You can download the dataset by clicking this <a href="https://media.geeksforgeeks.org/wp-content/uploads/20240923174013/flipkart_data.csv">link</a>.</p><pre>import pandas as pd<br>import nltk<br>from nltk.corpus import stopwords<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.metrics import accuracy_score, confusion_matrix<br>import matplotlib.pyplot as plt<br>from wordcloud import WordCloud<br>import seaborn as sns<br><br>file_path = &#39;/content/flipkart_data.csv&#39;<br>df = pd.read_csv(file_path)<br><br><br>df.head()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*NY4hhN3Fxa6vxVrp.png" /></figure><h3>2. Preprocessing the Data</h3><p>The next step is<a href="https://www.geeksforgeeks.org/dbms/data-preprocessing-in-data-mining/"> preprocessing the data</a> which involves cleaning the review text and preparing the sentiment labels. We’ll start by converting the reviews to lowercase and removing stopwords to make text more manageable. Then we will convert ratings (from 1 to 5) into binary sentiment labels like 1 for positive reviews (ratings 4 and 5) and 0 for negative reviews (ratings 3 and below).</p><pre>nltk.download(&#39;stopwords&#39;)<br>stop_words = set(stopwords.words(&#39;english&#39;))<br><br>def preprocess_reviews_stopwords(df):<br>    df[&#39;review&#39;] = df[&#39;review&#39;].str.lower()<br>    df[&#39;review&#39;] = df[&#39;review&#39;].apply(lambda x: &#39; &#39;.join([word for word in x.split() if word not in stop_words]))<br>    df[&#39;sentiment&#39;] = df[&#39;rating&#39;].apply(lambda x: 1 if x &gt;= 4 else 0)<br>    return df<br><br>df_cleaned = preprocess_reviews_stopwords(df)</pre><h3>3. Visualizing the Data</h3><p>Before we proceed with model making it’s important to explore the dataset. We can visualize the distribution of sentiment labels and analyze the frequency of words in positive reviews.</p><h3>Sentiment Distribution</h3><p>To understand the overall sentiment distribution, we will use a <a href="https://www.geeksforgeeks.org/pandas/bar-plot-in-matplotlib/">bar plot</a> to visualize the counts of positive and negative reviews.</p><pre>sentiment_counts = df_cleaned[&#39;sentiment&#39;].value_counts()<br>plt.figure(figsize=(6, 4))<br>sentiment_counts.plot(kind=&#39;bar&#39;, color=[&#39;red&#39;, &#39;green&#39;])<br>plt.title(&#39;Sentiment Distribution (0: Negative, 1: Positive)&#39;)<br>plt.xlabel(&#39;Sentiment&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.xticks(ticks=[0, 1], labels=[&#39;Negative&#39;, &#39;Positive&#39;], rotation=0)<br>plt.show()</pre><p><strong>Output</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*F4RcgjOCaZwDY8TI.png" /></figure><h3>Word Cloud for Positive Reviews</h3><p>Next, we’ll create a <a href="https://www.geeksforgeeks.org/python/generate-word-clouds-of-any-shape-in-python/"><strong>Wordcloud</strong></a> to visualize the most frequent words in positive reviews. This can help us understand the common themes in customer feedback.</p><pre>positive_reviews = df_cleaned[df_cleaned[&#39;sentiment&#39;] == 1][&#39;review&#39;]<br>positive_text = &#39; &#39;.join(positive_reviews)<br>wordcloud = WordCloud(width=800, height=400).generate(positive_text)<br><br>plt.figure(figsize=(8, 6))<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud for Positive Reviews&#39;)<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*68brBaw9RhQmkQ9iH9DGFw.jpeg" /></figure><h3>4. Vectorizing the Text Data</h3><p>Machine learning models require numerical input so we need to convert the textual reviews into numerical vectors. We will use <a href="https://www.geeksforgeeks.org/machine-learning/understanding-tf-idf-term-frequency-inverse-document-frequency/"><strong>TF-IDF (Term Frequency-Inverse Document Frequency)</strong></a> which helps converting these texts into vectors.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br><br>vectorizer = TfidfVectorizer(max_features=5000)<br>X = vectorizer.fit_transform(df_cleaned[&#39;review&#39;])<br>y = df_cleaned[&#39;sentiment&#39;]</pre><h3>5. Model Training, Evaluation and Prediction</h3><p>Now that the data is prepared we can split it into training and testing sets where 80% data is used for training and rest is used for testing. We will train a <a href="https://www.geeksforgeeks.org/machine-learning/building-and-implementing-decision-tree-classifiers-with-scikit-learn-a-comprehensive-guide/"><strong>Decision Tree Classifier</strong></a> on the training data and evaluate its performance on the test data. We will also measure the model’s accuracy and generate a <a href="https://www.geeksforgeeks.org/machine-learning/confusion-matrix-machine-learning/">confusion matrix</a> to analyze the predictions.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>model = DecisionTreeClassifier(random_state=42)<br>model.fit(X_train, y_train)<br><br>y_pred = model.predict(X_test)<br>accuracy = accuracy_score(y_test, y_pred)<br>conf_matrix = confusion_matrix(y_test, y_pred)<br><br>sns.heatmap(conf_matrix , annot=True,fmt=&#39;d&#39;, cmap=&quot;Blues&quot;)<br>plt.title(&#39;Confusion Matrix&#39;)<br>plt.xlabel(&#39;Predicted&#39;)<br>plt.ylabel(&#39;Actual&#39;)<br>plt.show()<br>print(accuracy)</pre><p><strong>Output</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*1gKCl5PtCCD0VNFZ.png" /></figure><p>We are able to classify reviews as positive or negative with an accuracy of approximately 86% which is great for a machine learning model but we can further fine tune this model to get better accuracy for more complex task. With this businesses can gain valuable insights into customer satisfaction and make data-driven decisions to improve their products and services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b9412f896d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Box Office Revenue Prediction Using Linear Regression in ML]]></title>
            <link>https://medium.com/@jithminikulatunga/box-office-revenue-prediction-using-linear-regression-in-ml-8ac729e01037?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ac729e01037</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 11:54:06 GMT</pubDate>
            <atom:updated>2026-11-12T11:54:06.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXLNYXZ2HYmqWOkLmbkSHw.png" /></figure><p>The objective of this project is to develop a machine learning model using <a href="https://www.geeksforgeeks.org/machine-learning/ml-linear-regression/">Linear Regression</a> to accurately predict the box office revenue of movies based on various available features. The model will be trained on a dataset containing historical movie data and will aim to identify key factors that impact revenue. By implementing data preprocessing, feature engineering, visualization and model evaluation techniques, this project seeks to:</p><ol><li>Build a predictive model that can estimate the expected revenue of a movie prior to its release.</li><li>Provide insights into which features most influence box office success.</li><li>Compare linear regression performance with more advanced models (e.g., XGBoost) to assess predictive accuracy.</li></ol><h3>1. Importing Libraries and Dataset</h3><h3>Core Libraries</h3><ul><li><a href="https://www.geeksforgeeks.org/pandas/pandas-tutorial/"><strong>Pandas: </strong></a>For loading and exploring the dataset.</li><li><a href="https://www.geeksforgeeks.org/python/numpy-tutorial/"><strong>NumPy:</strong></a>For working with numerical arrays and math operations.</li></ul><h3>Visualization</h3><ul><li><a href="https://www.geeksforgeeks.org/python/matplotlib-tutorial/"><strong>Matplotlib</strong></a><strong> and </strong><a href="https://www.geeksforgeeks.org/python/python-seaborn-tutorial/"><strong>Seaborn</strong></a><strong>:</strong> Used to plot data distributions, trends and model performance.</li></ul><h3>Preprocessing and Modeling</h3><ul><li><strong>train_test_split: </strong>Splits the data into training and validation sets.</li><li><strong>LabelEncoder:</strong> Converts categories like genres into numeric format.</li><li><strong>StandardScaler:</strong> Scales features for better model performance.</li><li><strong>CountVectorizer: </strong>Converts text data (e.g., genres) into numeric vectors.</li><li><strong>metrics: </strong>Offers tools for evaluating model accuracy.</li></ul><h3>Advanced Modeling</h3><ul><li><a href="https://www.geeksforgeeks.org/machine-learning/xgboost/"><strong>XGBoost</strong></a><strong>:</strong> A high-performance gradient boosting algorithm used for better predictions.</li></ul><h3>Utility</h3><ul><li><strong>warnings.filterwarnings(‘ignore’):</strong> Hides unnecessary warning messages for cleaner output.</li></ul><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sb<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder, StandardScaler<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn import metrics<br>from xgboost import XGBRegressor<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h3>2. Loading the dataset into a pandas DataFrame</h3><p>We now load the dataset into a pandas DataFrame to begin analysis. You can download the dataset from <a href="https://media.geeksforgeeks.org/wp-content/uploads/20240930185118/boxoffice.csv"><strong>here.</strong></a></p><pre>df = pd.read_csv(&#39;boxoffice.csv&#39;,<br>                 encoding=&#39;latin-1&#39;)<br>df.head()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*TXoHDEtwtIW35mbu.png" /></figure><h3>2.1 Checking Dataset Size</h3><p>Let’s see how many rows and columns we have.</p><pre>df.shape</pre><p><strong>Output:</strong></p><blockquote>(2694, 10)</blockquote><h3>2.2 Checking Data Types</h3><p>We check the data types of each column and look for issues.</p><pre>df.info()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*chKAU18oxETHeDqc.png" /></figure><p>Here we can observe an unusual discrepancy in the dtype column the columns which should be in the number format are also in the object type. This means we need to clean the data before moving any further.</p><h3>3. Exploring the Dataset</h3><p>We take a quick look at statistical metrics (like mean, min, max) for each numeric column to understand the data distribution.</p><ul><li><strong>df.describe() </strong>gives a summary of the numeric columns (count, mean, standard deviation, min, max, etc.).</li><li><strong>.T</strong> transposes the output for better readability ( rows become columns and vice versa ).</li></ul><pre>df.describe().T</pre><p><strong>Output:</strong></p><p>Since we are predicting only domestic revenue in this project, we are dropping <strong>world_revenue</strong> and <strong>opening_revenue</strong> columns from the dataframe.</p><pre>to_remove = [&#39;world_revenue&#39;, &#39;opening_revenue&#39;]<br>df.drop(to_remove, axis=1, inplace=True)</pre><h3>3.1 Checking Missing Values</h3><p>We calculate what percentage of values is missing in each column. <strong>isnull().sum() </strong>functions helps us identify columns with many missing entries.</p><pre>df.isnull().sum() * 100 / df.shape[0]</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/0*YKnwJ0HB2eISitdm.png" /></figure><h3>4. Handling Missing Values</h3><p>We clean the data by removing or filling missing values appropriately.</p><ul><li>We drop the budget column entirely, likely due to too many missing values.</li><li>Fill missing values in MPAA and genres columns using their most frequent values (mode).</li><li>Remove any remaining rows with missing values.</li><li>Finally, check if any null values remain; the result should be 0.</li></ul><pre>df.drop(&#39;budget&#39;, axis=1, inplace=True)<br><br>for col in [&#39;MPAA&#39;, &#39;genres&#39;]:<br>    df[col] = df[col].fillna(df[col].mode()[0])<br>df.dropna(inplace=True)<br>df.isnull().sum().sum()</pre><p><strong>Output:</strong></p><blockquote>0</blockquote><h3>4.1 Cleaning Numeric Columns Stored as Strings</h3><p>Some numeric columns might be stored as strings with special characters (like $ or ,). We need to remove these characters and convert the columns back to numeric format.</p><ul><li>Remove the first character from ‘<strong>domestic_revenue</strong>’ (likely a $ sign).</li><li>Remove commas from numeric values (e.g., 1,000 to 1000).</li><li>Ensure the columns are properly converted to float types.</li><li>Use <strong>pd.to_numeric</strong> to handle any remaining non-numeric values gracefully to turn them into <strong>NaNs</strong>.</li></ul><pre>df[&#39;domestic_revenue&#39;] = df[&#39;domestic_revenue&#39;].astype(str).str[1:]<br><br>for col in [&#39;domestic_revenue&#39;, &#39;opening_theaters&#39;, &#39;release_days&#39;]:<br>    df[col] = df[col].astype(str).str.replace(&#39;,&#39;, &#39;&#39;) <br>    <br>    temp = (~df[col].isnull()) <br>    df[temp][col] = df[temp][col].convert_dtypes(float) <br>    df[col] = pd.to_numeric(df[col], errors=&#39;coerce&#39;)</pre><h3>5. Visualizing MPAA Rating Distribution</h3><p>We want to see how many movies fall under each MPAA rating category like PG, R, PG-13, etc. We will create a horizontal bar chart showing the count of movies in each MPAA rating.</p><ul><li><strong>plt.figure(figsize=(10, 5))</strong> sets the size of the plot.</li><li><strong>sb.countplot() </strong>from Seaborn automatically counts and plots the frequency of each category in the ‘MPAA’ column.</li><li><strong>plt.show() </strong>displays the plot.</li></ul><pre>plt.figure(figsize=(10, 5))<br>sb.countplot(df[&#39;MPAA&#39;])<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*9CnPqNMTXKvsXa_h.png" /></figure><h3>5.1 Average Domestic Revenue by MPAA Rating</h3><p>We group the dataset by the ‘MPAA’ rating category and calculate the mean (average) of the ‘<strong>domestic_revenue</strong>’ for each rating group.</p><pre>df.groupby(&#39;MPAA&#39;)[&#39;domestic_revenue&#39;].mean()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*z3NMPNM7jxJnm8rz.png" /></figure><p>Here we can observe that the movies with PG or R ratings generally have their revenue higher than the other rating class.</p><h3>6. Visualizing Distributions of Key Numeric Features</h3><p>We plot the distribution (shape) of three important numeric columns to see how their values spread out.</p><ul><li>We create three side-by-side plots in one row.</li><li>For each feature (domestic_revenue, opening_theaters, release_days) we show the distribution using Seaborn’s distplot.</li><li>This helps check if the data is normally distributed, skewed or has any unusual patterns.</li></ul><pre>plt.subplots(figsize=(15, 5))<br><br>features = [&#39;domestic_revenue&#39;, &#39;opening_theaters&#39;, &#39;release_days&#39;]<br>for i, col in enumerate(features):<br>    plt.subplot(1, 3, i+1)<br>    sb.distplot(df[col])<br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*NRvypXUN78kj0lrR.png" /></figure><p>Understanding these distributions is important before modeling, as it affects how the model interprets the data.</p><h3>7. Detecting Outliers Using Boxplots</h3><p>We use boxplots to visually check for outliers in key numeric features. Boxplots show the spread of data and highlight any outliers (points outside the whiskers).</p><ul><li>We create three boxplots side by side, one for each feature (domestic_revenue, opening_theaters, release_days).</li><li>This helps us identify unusual values that might affect the model.</li></ul><pre>plt.subplots(figsize=(15, 5))<br>for i, col in enumerate(features):<br>    plt.subplot(1, 3, i+1)<br>    sb.boxplot(df[col])<br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*32JjhuhoIp1WK6tC.png" /></figure><p>We can observe that there are no outliers in the above features.</p><h3>8. Applying Log Transformation to Numeric Features</h3><p>We apply a log transformation to reduce skewness in our numeric data because log transformation often improves model performance and stability.</p><ul><li>We take the base-10 logarithm of each value in the specified columns (domestic_revenue, opening_theaters, release_days).</li><li>This helps make skewed data more normally distributed and reduces the effect of extreme values.</li></ul><pre>for col in features:<br>  df[col] = df[col].apply(lambda x: np.log10(x))</pre><p>Now the data in the columns we have visualized above should be close to normal distribution.</p><h3>8.1 Checking Distributions After Log Transformation</h3><p>We visualize the distributions of the numeric features again to see the effect of the log transformation.</p><pre>plt.subplots(figsize=(15, 5))<br>for i, col in enumerate(features):<br>    plt.subplot(1, 3, i+1)<br>    sb.distplot(df[col])<br>plt.tight_layout()<br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*EUPXYOQ3tlGUyzXv.png" /></figure><h3>9. Converting Movie Genres into Numeric Features</h3><p>We transform the text data in the genres column into separate numeric features using one-hot encoding.</p><ul><li>We use <strong>CountVectorizer </strong>to convert each genre like “Action”, “Comedy” into a binary feature i.e 1 if the movie belongs to that genre, else 0.</li><li>Then drop the original genres text column since it’s now represented numerically.</li></ul><pre>vectorizer = CountVectorizer() <br>vectorizer.fit(df[&#39;genres&#39;]) <br>features = vectorizer.transform(df[&#39;genres&#39;]).toarray() <br><br>genres = vectorizer.get_feature_names_out() <br>for i, name in enumerate(genres): <br> df[name] = features[:, i] <br>df.drop(&#39;genres&#39;, axis=1, inplace=True)</pre><p>But there will be certain genres that are not that frequent which will lead to increases in the complexity of the model unnecessarily. So we will remove those genres which are very rare.</p><h3>9.1 Removing Rare Genre Columns with Mostly Zero Values</h3><p>We will check for columns between ‘action’ and ‘western’ in the DataFrame and drop columns where over 95% of values are zero meaning that genre is rare.</p><pre>removed = 0<br><br>if &#39;action&#39; in df.columns and &#39;western&#39; in df.columns:<br>    for col in df.loc[:, &#39;action&#39;:&#39;western&#39;].columns: <br>        <br>        if (df[col] == 0).mean() &gt; 0.95: <br>            removed += 1<br>            df.drop(col, axis=1, inplace=True) <br>print(removed) <br>print(df.shape)</pre><p><strong>Output:</strong></p><blockquote>0<br>(2694, 12)</blockquote><p>This helps simplify the model by focusing on genres that actually appear frequently.</p><h3>10. Encoding Categorical Columns into Numbers</h3><p>We use <a href="https://www.geeksforgeeks.org/machine-learning/ml-label-encoding-of-datasets-in-python/"><strong>LabelEncoder</strong></a><strong> </strong>to replace each unique category with a number like “PG” to 0, “R” to 1. This is necessary because machine learning models work better with numbers than text labels.</p><pre>for col in [&#39;distributor&#39;, &#39;MPAA&#39;]:<br>    le = LabelEncoder()<br>    df[col] = le.fit_transform(df[col])</pre><h3>11. Visualizing Strong Correlations Between Numeric Features</h3><p>As all the categorical features have been labeled encoded let’s check if there are highly correlated features in the dataset.</p><ul><li>We will calculate the correlation matrix for all numeric columns.</li><li>The plot a heatmap, highlighting pairs of features with correlation greater than 0.8 (very strong correlation).</li></ul><p>This helps us identify redundant features that may need to be removed or handled before modeling.</p><pre>plt.figure(figsize=(8, 8))<br>sb.heatmap(df.select_dtypes(include=np.number).corr() &gt; 0.8, <br>            annot=True, <br>            cbar=False) <br>plt.show()</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*sboCild-s9VdkD-h.png" /></figure><h3>12. Preparing Data for Model Training and Validation</h3><p>Now we will separate the features and target variables and split them into training and the testing data by using which we will select the model which is performing best on the <a href="https://www.geeksforgeeks.org/machine-learning/training-vs-testing-vs-validation-sets/">validation data</a>.</p><ul><li>We will remove the title and target column <strong>domestic_revenue </strong>from the features and set <strong>domestic_revenue </strong>as the target variable.</li><li>We split the data into 90% training and 10% validation sets to evaluate model performance.</li></ul><pre>features = df.drop([&#39;title&#39;, &#39;domestic_revenue&#39;], axis=1) <br>target = df[&#39;domestic_revenue&#39;].values <br><br>X_train, X_val, Y_train, Y_val = train_test_split(features, target, <br>         test_size=0.1, <br>         random_state=22) <br>X_train.shape, X_val.shape</pre><p><strong>Output:</strong></p><blockquote>((2424, 10), (270, 10))</blockquote><h3>12.1 Normalizing Features for Better Model Training</h3><p>We scale the features to have a mean of 0 and a standard deviation of 1, which helps models learn more effectively.</p><ul><li><strong>fit_transform </strong>learns scaling parameters from training data and applies scaling.</li><li>transform applies the same scaling to validation data without changing the scaler.</li></ul><p>This standardization helps the model converge faster and improves stability during training.</p><pre>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_val = scaler.transform(X_val)</pre><h3>13. Training the XGBoost Regression Model</h3><p>XGBoost library models help to achieve state-of-the-art results most of the time so, we will also train this model to get better results.</p><ul><li>We initialize an <a href="https://www.geeksforgeeks.org/machine-learning/xgboost-for-regression/"><strong>XGBoost regresso</strong>r </a>a gradient boosting model.</li><li>Then train the model on the normalized training data (<strong>X_train</strong>) and target values (<strong>Y_train</strong>).</li></ul><pre>from sklearn.metrics import mean_absolute_error as mae<br>model = XGBRegressor()<br>model.fit(X_train, Y_train)</pre><h3>14. Evaluating Model Performance on Training and Validation Sets</h3><p>We use Mean Absolute Error (MAE) to check how well the model predicts revenue on both training and validation data.</p><ul><li>We predict revenue for the training data and calculate MAE to measure training error.</li><li>Also we predict revenue for the validation data and calculate MAE to measure how well the model generalizes.</li></ul><blockquote><strong>Note</strong>: Lower MAE means better predictions, it helps identify if the model is overfitting or underfitting.</blockquote><pre>train_preds = model.predict(X_train) <br>print(&#39;Training Error : &#39;, mae(Y_train, train_preds)) <br><br>val_preds = model.predict(X_val) <br>print(&#39;Validation Error : &#39;, mae(Y_val, val_preds)) <br>print()</pre><p><strong>Output:</strong></p><blockquote>Training Error: 0.2104541861999253<br>Validation Error: 0.6358190127903746</blockquote><p>We can observe that :</p><ul><li><strong>Training Error (0.21) is low: </strong>The model fits the training data quite well.</li><li><strong>Validation Error (0.63) is significantly higher than training: </strong>This gap suggests the model might be overfitting, meaning it performs well on training data but not as well on unseen (validation) data.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ac729e01037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing Selling Price of used Cars using Python]]></title>
            <link>https://medium.com/@jithminikulatunga/analyzing-selling-price-of-used-cars-using-python-55893627061f?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/55893627061f</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 14:08:24 GMT</pubDate>
            <atom:updated>2026-10-24T14:08:24.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Hop8eeFp_q5SgYLCuKwEQ.png" /><figcaption>Analyzing Selling Price of used Cars using Python</figcaption></figure><p>Analyzing the selling prices of used cars is important for making well-informed decisions in the automotive market. Python provides powerful tools for processing, analyzing, and visualizing data to identify the key factors that affect car prices. This analysis helps buyers and sellers better understand market trends and provides a foundation for developing machine learning models to predict used car prices. In this case study, we will explore how to analyze used car selling prices using Python.</p><h3>Step 1: Understanding the Dataset</h3><p>The dataset includes several attributes of used cars, such as selling price, brand, color, horsepower, and other vehicle characteristics. The objective is to examine these features and understand how they influence the selling price. You can download the dataset used in this analysis from the <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data?utm_source=chatgpt.com">UCI Machine Learning Repository</a>.</p><p><em>Problem Statement: Our friend Otis is planning to sell his car but is uncertain about the right selling price. His goal is to maximize his profit while offering buyers a fair and reasonable deal. To assist him, we will analyze the dataset to identify the key factors that influence car prices and help estimate an appropriate selling price.</em></p><h3>Step 2: Converting a .data File into a .csv File</h3><p>If your dataset is stored in .data format, you can convert it into a .csv file by following these steps:</p><ol><li>Open Microsoft Excel.</li><li>Navigate to Data &gt; From Text.</li><li>Choose Comma as the delimiter to separate the data into columns.</li><li>Save the converted file in .csv format.</li></ol><p>Once the conversion is complete, the dataset will be ready to load into Python for further analysis.</p><h3>Step 3: Installing and Importing the Required Python Libraries</h3><p>Before starting the data analysis process, install the necessary Python libraries by running the following command:</p><pre>pip install pandas numpy matplotlib seaborn scipy</pre><p>Next, import the required libraries into your Python environment:</p><ul><li>NumPy: For numerical computations and array operations.</li><li>Pandas: For data manipulation and analysis.</li><li>Matplotlib: For creating data visualizations and charts.</li><li>Seaborn: For producing informative statistical visualizations.</li><li>SciPy: For scientific computing and statistical analysis.</li></ul><p>These libraries provide the essential tools needed to explore, process, analyze, and visualize the dataset.</p><pre>import pandas as pd <br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import scipy as sp</pre><h3>Step 4: Load the Dataset</h3><p>In this step, we import the dataset into a Pandas DataFrame and examine its structure by displaying the first five rows.</p><pre>df = pd.read_csv(&#39;output.csv&#39;)</pre><pre>df = df.iloc[: , 1:]</pre><pre>df.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*HgWoWGMIXj4T_TX4" /><figcaption>Dataset</figcaption></figure><h3>Step 5: Assign Column Headers</h3><p>To improve the dataset’s readability, we assign appropriate column names to each column.</p><pre>headers = [&quot;symboling&quot;, &quot;normalized-losses&quot;, &quot;make&quot;, <br>           &quot;fuel-type&quot;, &quot;aspiration&quot;,&quot;num-of-doors&quot;,<br>           &quot;body-style&quot;,&quot;drive-wheels&quot;, &quot;engine-location&quot;,<br>           &quot;wheel-base&quot;,&quot;length&quot;, &quot;width&quot;,&quot;height&quot;, &quot;curb-weight&quot;,<br>           &quot;engine-type&quot;,&quot;num-of-cylinders&quot;, &quot;engine-size&quot;, <br>           &quot;fuel-system&quot;,&quot;bore&quot;,&quot;stroke&quot;, &quot;compression-ratio&quot;,<br>           &quot;horsepower&quot;, &quot;peak-rpm&quot;,&quot;city-mpg&quot;,&quot;highway-mpg&quot;,&quot;price&quot;]</pre><pre>df.columns=headers<br>df.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*keOM69jmkvuqPid6" /><figcaption>Column Header</figcaption></figure><h3>Step 6: Identify Missing Values</h3><p>Missing data can affect the accuracy of our analysis. Let’s examine the dataset to determine whether any columns contain missing values.</p><pre>data = df</pre><pre>data.isna().any()</pre><pre>data.isnull().any()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*4d7LUg1ZtWftyZhC" /><figcaption>Missing Values</figcaption></figure><h3>Step 7: Convert MPG to L/100km</h3><p>As fuel efficiency is expressed differently across regions, we convert miles per gallon (MPG) into liters per 100 kilometers (L/100km) to standardize the measurement.</p><pre>data[&#39;city-mpg&#39;] = 235 / df[&#39;city-mpg&#39;]<br>data.rename(columns = {&#39;city_mpg&#39;: &quot;city-L / 100km&quot;}, inplace = True)</pre><pre>print(data.columns)</pre><pre>data.dtypes</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*qr0S_-CfGeGPme6_" /><figcaption>MPG</figcaption></figure><h3>Step 8: Convert the Price Column to Integer</h3><p>The price column should contain numerical values, but it may include invalid string entries such as ?. To ensure the data is suitable for analysis, we need to clean these values and convert the column into an integer format.</p><pre>data.price.unique()</pre><pre>data = data[data.price != &#39;?&#39;]</pre><pre>data[&#39;price&#39;] = data[&#39;price&#39;].astype(int)</pre><pre>data.dtypes</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*6Xyr2PHgZiD2frdy" /></figure><h3>Step 9: Feature Normalization</h3><p>Numerical features are normalized to ensure consistency and enable fair comparisons across different variables. Additionally, car prices are grouped into three categories — Low, Medium, and High — based on their price ranges.</p><pre>data[&#39;length&#39;] = data[&#39;length&#39;]/data[&#39;length&#39;].max()<br>data[&#39;width&#39;] = data[&#39;width&#39;]/data[&#39;width&#39;].max()<br>data[&#39;height&#39;] = data[&#39;height&#39;]/data[&#39;height&#39;].max()</pre><pre># binning- grouping values<br>bins = np.linspace(min(data[&#39;price&#39;]), max(data[&#39;price&#39;]), 4) <br>group_names = [&#39;Low&#39;, &#39;Medium&#39;, &#39;High&#39;]<br>data[&#39;price-binned&#39;] = pd.cut(data[&#39;price&#39;], bins, <br>                              labels = group_names, <br>                              include_lowest = True)</pre><pre>print(data[&#39;price-binned&#39;])<br>plt.hist(data[&#39;price-binned&#39;])<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*CnWh1lzReINO_arA" /><figcaption>Normalization Features</figcaption></figure><h3>Step 10: Encode Categorical Data into Numerical Values</h3><p>Machine learning algorithms work with numerical data. Therefore, we transform categorical features into numerical representations using one-hot encoding.</p><pre>pd.get_dummies(data[&#39;fuel-type&#39;]).head()</pre><pre>data.describe()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*jOZXHvlUAXA52YWf" /><figcaption>Convert Categorical Data to Numerical</figcaption></figure><h3>Step 11: Data Visualization</h3><pre>plt.boxplot(data[&#39;price&#39;])</pre><pre>sns.boxplot(x =&#39;drive-wheels&#39;, y =&#39;price&#39;, data = data)</pre><pre>plt.scatter(data[&#39;engine-size&#39;], data[&#39;price&#39;])<br>plt.title(&#39;Scatterplot of Enginesize vs Price&#39;)<br>plt.xlabel(&#39;Engine size&#39;)<br>plt.ylabel(&#39;Price&#39;)<br>plt.grid()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*TKoi3mTJQj2F7EAB" /><figcaption>Engine Size</figcaption></figure><h3>Step 12: Analyzing Data by Drive-Wheel and Body-Style Categories</h3><p>Grouping the data helps uncover patterns and trends by examining key variables such as drive-wheel configuration and vehicle body style.</p><pre>test = data[[&#39;drive-wheels&#39;, &#39;body-style&#39;, &#39;price&#39;]]<br>data_grp = test.groupby([&#39;drive-wheels&#39;, &#39;body-style&#39;], <br>                         as_index = False).mean()</pre><pre>data_grp</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*BT5PP5SeURkGkXJP" /><figcaption>Grouping Data</figcaption></figure><h3>Step 13: Create a Pivot Table &amp; Heatmap</h3><pre>data_pivot = data_grp.pivot(index = &#39;drive-wheels&#39;,<br>                            columns = &#39;body-style&#39;)<br>data_pivot</pre><pre>plt.pcolor(data_pivot, cmap =&#39;RdBu&#39;)<br>plt.colorbar()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*2979ekZ47LDz6UuM" /><figcaption>Pivot Table</figcaption></figure><h3>Step 14: Conduct the ANOVA Test</h3><p>Analysis of Variance (ANOVA) is a statistical method used to determine whether there are statistically significant differences between the means of two or more groups.</p><pre>data_annova = data[[&#39;make&#39;, &#39;price&#39;]]<br>grouped_annova = data_annova.groupby([&#39;make&#39;])<br>annova_results_l = sp.stats.f_oneway(<br>                             grouped_annova.get_group(&#39;honda&#39;)[&#39;price&#39;],<br>                             grouped_annova.get_group(&#39;subaru&#39;)[&#39;price&#39;]<br>                                    )<br>print(annova_results_l)</pre><pre>sns.regplot(x =&#39;engine-size&#39;, y =&#39;price&#39;, data = data)<br>plt.ylim(0, )</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*HiLYwBAm-4-2sOvB" /><figcaption>ANOVA Test</figcaption></figure><p>This step-by-step analysis provides valuable insights into the main factors affecting used car prices. Effective data cleaning, visualization, and statistical testing help ensure reliable, accurate, and meaningful results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55893627061f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Segmentation using Unsupervised Machine Learning in Python]]></title>
            <link>https://medium.com/@jithminikulatunga/customer-segmentation-using-unsupervised-machine-learning-in-python-ffe266b06ff9?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe266b06ff9</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 13:56:01 GMT</pubDate>
            <atom:updated>2026-10-24T13:58:02.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miURDKNKJ6IodblmxANIAQ.png" /><figcaption>Customer Segmentation using Unsupervised Machine Learning in Python</figcaption></figure><p>Customer Segmentation is the process of dividing customers into distinct groups based on their common characteristics, purchasing behaviors, and preferences. This approach enables businesses to develop targeted marketing strategies, better understand customer needs, and maximize overall market value. In this case study, we will apply <a href="https://www.geeksforgeeks.org/machine-learning/unsupervised-learning/">Unsupervised Machine Learning</a> techniques to perform customer segmentation using Python.</p><h3>Step 1: Import Libraries</h3><p>First, we will import the essential Python libraries required for data manipulation, numerical computations, data visualization, and machine learning. These include <a href="https://www.geeksforgeeks.org/pandas/python-pandas-dataframe/">Pandas</a>, <a href="https://www.geeksforgeeks.org/numpy/python-numpy/">Numpy</a>, <a href="https://www.geeksforgeeks.org/python/matplotlib-tutorial/">Matplotlib</a>, <a href="https://www.geeksforgeeks.org/python/introduction-to-seaborn-python/">Seaborn</a> and Scikit-learn (<a href="https://www.geeksforgeeks.org/machine-learning/learning-model-building-scikit-learn-python-machine-learning-library/">Sklearn</a>).</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sb</pre><pre>from sklearn.preprocessing import StandardScaler, LabelEncoder<br>from sklearn.cluster import KMeans</pre><pre>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h3>Step 2: Load the Dataset</h3><p>Import the dataset containing customer information, including marital status, income, purchase quantities, product categories, and other relevant attributes. You can download the dataset from <a href="https://media.geeksforgeeks.org/wp-content/uploads/20240903152131/new.csv?utm_source=chatgpt.com">this link</a>.</p><pre>df = pd.read_csv(&#39;new.csv&#39;)<br>df.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*IkkHHKdv4L3RK1QD" /><figcaption>Dataset</figcaption></figure><p>We can use the data.shape attribute to determine the dimensions of the dataset, including the number of rows and columns.</p><pre>df.shape</pre><p>Output:</p><pre>(2240, 29)</pre><h3>Step 3: Data Preprocessing</h3><p>To inspect the dataset and obtain an overview of its structure, including column information, non-null values, and data types, we will use the .info() method.</p><pre>df.info()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*L_o7uV4zuw2lqSXc" /><figcaption>Dataset Info</figcaption></figure><pre>df.describe().T</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*Jn6nGi9dM3-68mgm" /><figcaption>Described Dataset</figcaption></figure><p>To identify missing values in the dataset.</p><pre>for col in df.columns:<br>    temp = df[col].isnull().sum()<br>    if temp &gt; 0:<br>        print(f&#39;Column {col} contains {temp} null values.&#39;)</pre><p>Output:</p><pre>Column Income contains 24 null values.</pre><p>Since the number of missing values is very small, we can remove those rows from the dataset without significantly affecting the overall data quality or analysis.</p><pre>df = df.dropna()<br>print(&quot;Total values in the dataset after removing the null values:&quot;, len(df))</pre><p>Output:</p><pre>Total values in the dataset after removing the null values: 2216</pre><p>To determine the number of distinct values in each column, we can use the data.unique() method.</p><pre>df.nunique()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*nIx2NLl5suTnKv5h" /><figcaption>Unique Value</figcaption></figure><p>Some columns contain only a single unique value throughout the entire dataset, making them irrelevant for model development and suitable for removal.</p><p>Additionally, the dataset includes a Dt_Customer column containing customer enrollment dates. We can extract the day, month, and year from this column and create three separate features to make the date information more useful for analysis and modeling.</p><pre>parts = df[&quot;Dt_Customer&quot;].str.split(&quot;-&quot;, n=3, expand=True)<br>df[&quot;day&quot;] = parts[0].astype(&#39;int&#39;)<br>df[&quot;month&quot;] = parts[1].astype(&#39;int&#39;)<br>df[&quot;year&quot;] = parts[2].astype(&#39;int&#39;)</pre><p>After identifying all the essential features, we can remove the unnecessary columns, such as Z_CostContact, Z_Revenue, and Dt_Customer, from the dataset.</p><pre>df.drop([&#39;Z_CostContact&#39;, &#39;Z_Revenue&#39;, &#39;Dt_Customer&#39;],<br>        axis=1,<br>        inplace=True)</pre><h3>Step 4: Data Visualization and Analysis</h3><p>Data visualization is the process of presenting information and data through graphical or visual formats, making patterns and insights easier to understand. In this step, we will use bar plots and count plots to visualize the data and analyze the distribution of different features effectively.</p><pre>floats, objects = [], []<br>for col in df.columns:<br>    if df[col].dtype == object:<br>        objects.append(col)<br>    elif df[col].dtype == float:<br>        floats.append(col)</pre><pre>print(objects)<br>print(floats)</pre><p>Output:</p><pre>[&#39;Education&#39;, &#39;Marital_Status&#39;, &#39;Accepted&#39;] <br>[&#39;Income&#39;]</pre><p>To generate count plots for columns with the object data type, use the following code.</p><pre>plt.subplots(figsize=(15, 10))<br>for i, col in enumerate(objects):<br>    plt.subplot(2, 2, i + 1)<br>    sb.countplot(df[col])<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*hpSy4AKlOkMrUyFa" /><figcaption>Count Plot</figcaption></figure><p>Let’s examine the frequency distribution of the Marital_Status column in the dataset using value_counts().</p><pre>df[&#39;Marital_Status&#39;].value_counts()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*-87yLG4jdlz68e8r" /><figcaption>Value Count</figcaption></figure><p>Next, let’s compare the features based on the corresponding response values.</p><pre>plt.subplots(figsize=(15, 10))<br>for i, col in enumerate(objects):<br>    plt.subplot(2, 2, i + 1)</pre><pre>    df_melted = df.melt(id_vars=[col], value_vars=[&#39;Response&#39;], var_name=&#39;hue&#39;)<br>    sb.countplot(x=col, hue=&#39;value&#39;, data=df_melted)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*lmzFIB8XT8DxUU8j" /><figcaption>Countplot</figcaption></figure><h3>Label Encoding converts categorical data into numerical values, allowing machine learning models to process and interpret the data effectively.</h3><pre>for col in df.columns:<br>    if df[col].dtype == object:<br>        le = LabelEncoder()<br>        df[col] = le.fit_transform(df[col])</pre><p>A <a href="https://www.geeksforgeeks.org/python/seaborn-heatmap-a-comprehensive-guide/">heatmap</a> is an effective visualization technique for identifying correlations between different features in a dataset. Let’s set the correlation threshold to 0.8.</p><pre>plt.figure(figsize=(15, 15))<br>sb.heatmap(df.corr() &gt; 0.8, annot=True, cbar=False)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/0*Dx80sW98rrQLvB4J" /><figcaption>Heatmap</figcaption></figure><p>Standardization is a feature-scaling technique used in feature engineering to transform numerical data into a common scale. It helps machine learning models process and learn from data more effectively by adjusting the features to have a mean of 0 and a standard deviation of 1.</p><pre>scaler = StandardScaler()<br>data = scaler.fit_transform(df)</pre><h3>Step 5: Segmentation</h3><p>In this step, we will use <a href="https://www.geeksforgeeks.org/machine-learning/ml-t-distributed-stochastic-neighbor-embedding-t-sne-algorithm/">T-distributed Stochastic Neighbor Embedding</a> (t-SNE), a dimensionality reduction technique that helps visualize high-dimensional data in a lower-dimensional space. It transforms similarities between data points into probability distributions and minimizes the differences between these distributions to represent the data points in a low-dimensional embedding.</p><pre>from sklearn.manifold import TSNE<br>model = TSNE(n_components=2, random_state=0)<br>tsne_data = model.fit_transform(df)<br>plt.figure(figsize=(7, 7))<br>plt.scatter(tsne_data[:, 0], tsne_data[:, 1])<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*9U2qUL99WKf1Yt8P" /><figcaption>Scatter Plot</figcaption></figure><p>The 2D visualization of the dataset reveals several distinct clusters that can be easily identified. <a href="https://www.geeksforgeeks.org/machine-learning/k-means-clustering-introduction/">KMeans Clustering</a> can also be applied to group different data points on a plane based on their similarities.</p><pre>error = []<br>for n_clusters in range(1, 21):<br>    model = KMeans(init=&#39;k-means++&#39;,<br>                   n_clusters=n_clusters,<br>                   max_iter=500,<br>                   random_state=22)<br>    model.fit(df)<br>    error.append(model.inertia_)</pre><p>In this context, inertia refers to the total sum of squared distances between data points and their respective cluster centroids.</p><pre>plt.figure(figsize=(10, 5))<br>sb.lineplot(x=range(1, 21), y=error)<br>sb.scatterplot(x=range(1, 21), y=error)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/0*Oig97nmZelIytADR" /><figcaption>Elbow Method</figcaption></figure><p>Based on the Elbow Method, k = 6 is identified as the optimal number of clusters, as the inertia decreases significantly up to six clusters and shows a much slower rate of reduction beyond this point.</p><pre>model = KMeans(init=&#39;k-means++&#39;,<br>               n_clusters=5,<br>               max_iter=500,<br>               random_state=22)<br>segments = model.fit_predict(df)</pre><p>A <a href="https://www.geeksforgeeks.org/python/scatterplot-using-seaborn-in-python/">scatterplot</a> will be used to visualize the six clusters identified by the K-Means Clustering algorithm.</p><pre>plt.figure(figsize=(7, 7))</pre><pre>df_tsne = pd.DataFrame({&#39;x&#39;: tsne_data[:, 0], &#39;y&#39;: tsne_data[:, 1], &#39;segment&#39;: segments})</pre><pre>sb.scatterplot(x=&#39;x&#39;, y=&#39;y&#39;, hue=&#39;segment&#39;, data=df_tsne)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*5a6U-PKEgz0N1Ima" /><figcaption>Elbow Method</figcaption></figure><p>The customers have been divided into five distinct clusters, allowing businesses to identify groups with similar purchasing behaviours. This segmentation helps deliver personalized advertisements, develop targeted marketing strategies, and make data-driven business decisions to improve customer engagement and support business growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe266b06ff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inventory Demand Forecasting using Machine Learning — Python]]></title>
            <link>https://medium.com/@jithminikulatunga/inventory-demand-forecasting-using-machine-learning-python-df584353f1ba?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/df584353f1ba</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 13:42:25 GMT</pubDate>
            <atom:updated>2026-10-24T13:51:14.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1k2MSyxW_uKQTA9JX2v7OA.png" /><figcaption>Inventory Demand Forecasting using Machine Learning — Python</figcaption></figure><p>Retailers need to manage their inventory effectively to ensure that essential products are always available when customers need them. Maintaining optimal stock levels helps prevent shortages that may lead to customer dissatisfaction while reducing excess inventory and unnecessary storage costs.</p><p>This article explores how Machine Learning (ML) can be used to predict the inventory requirements of various products across multiple stores, helping businesses make smarter, data-driven stocking decisions.</p><h3>Step 1: Importing Libraries and Loading the Dataset</h3><p>First, we import the essential Python libraries required for data manipulation, preprocessing, visualization, and machine learning model development. These include <a href="https://www.geeksforgeeks.org/pandas/introduction-to-pandas-in-python/">Pandas</a>,<a href="https://www.geeksforgeeks.org/python/introduction-to-numpy/"> Numpy</a>, <a href="https://www.geeksforgeeks.org/python/python-introduction-matplotlib/">Matplotlib</a>, <a href="https://www.geeksforgeeks.org/python/introduction-to-seaborn-python/">Seaborn</a>, and Scikit-learn (Sklearn).</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sb<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import LabelEncoder, StandardScaler<br>from sklearn import metrics<br>from sklearn.svm import SVC<br>from xgboost import XGBRegressor<br>from sklearn.linear_model import LinearRegression, Lasso, Ridge<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import mean_absolute_error as mae</pre><pre>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h3>Step 2: Load and Explore the Dataset</h3><p>Import the dataset into a pandas DataFrame and explore its structure to understand the available data. It includes sales records for 10 stores and 50 products spanning five years.</p><p>To download the dataset, <a href="https://media.geeksforgeeks.org/wp-content/uploads/20250321170426512464/train.csv?utm_source=chatgpt.com">click here</a>.</p><pre>df = pd.read_csv(&#39;StoreDemand.csv&#39;)<br>display(df.head())<br>display(df.tail())</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*b1t3AFm41wUlL0mg" /><figcaption>First five rows of the dataset.</figcaption></figure><pre>df.shape</pre><p>Output:</p><pre>(913000, 4)</pre><p>Let’s use the <a href="https://www.geeksforgeeks.org/python/python-pandas-dataframe-info/">info()</a> function to examine the dataset’s columns and identify the data types of each column.</p><pre>df.info()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*6F738qOL7JIcMn6i" /><figcaption>Information regarding data in the columns</figcaption></figure><p>After examining the information available for each column, we can confirm that the dataset does not contain any missing (null) values.</p><pre>df.describe()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*UzBvji-BXIDyR94X" /><figcaption>Descriptive statistical measures of the dataset</figcaption></figure><h3>Step 3: Feature Engineering</h3><p>Feature engineering involves combining existing features or extracting new features from the available data to create additional meaningful variables. This process helps uncover valuable patterns, relationships, and insights within the dataset.</p><p>When carefully designed, these new features can improve the model’s ability to identify important patterns and potentially enhance its predictive accuracy.</p><pre>parts = df[&quot;date&quot;].str.split(&quot;-&quot;, n = 3, expand = True)<br>df[&quot;year&quot;]= parts[0].astype(&#39;int&#39;)<br>df[&quot;month&quot;]= parts[1].astype(&#39;int&#39;)<br>df[&quot;day&quot;]= parts[2].astype(&#39;int&#39;)<br>df.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*TwaUBhCGju95ea79" /><figcaption>Addition of day, month, and year feature</figcaption></figure><p>Whether a day falls on a weekday or a weekend can influence demand and affect the resources needed to meet it.</p><pre>from datetime import datetime</pre><pre>def weekend_or_weekday(year, month, day):<br>    d = datetime(year, month, day)<br>    return 1 if d.weekday() &gt; 4 else 0</pre><pre>df[&#39;weekend&#39;] = df.apply(lambda x: weekend_or_weekday(x[&#39;year&#39;], x[&#39;month&#39;], x[&#39;day&#39;]), axis=1)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/0*_hEgaQNlYiNq9iJH" /><figcaption>Addition of a weekend feature</figcaption></figure><p>Adding a column to identify whether a particular day is a holiday would be useful for further analysis.</p><pre>from datetime import date<br>import holidays</pre><pre>india_holidays = holidays.country_holidays(&#39;IN&#39;)<br>df[&#39;holidays&#39;] = df[&#39;date&#39;].apply(lambda x: 1 if india_holidays.get(x) else 0)</pre><p>Next, let’s introduce some cyclical features to the dataset.</p><pre>df[&#39;m1&#39;] = np.sin(df[&#39;month&#39;] * (2 * np.pi / 12))<br>df[&#39;m2&#39;] = np.cos(df[&#39;month&#39;] * (2 * np.pi / 12))<br>df.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*TLvuFwrZv3Csm1zT" /><figcaption>Addition of Cyclical Features</figcaption></figure><p>Let’s create a new column that identifies the day of the week for each record.</p><pre>def which_day(year, month, day):<br>    return datetime(year, month, day).weekday()</pre><pre>df[&#39;weekday&#39;] = df.apply(lambda x: which_day(x[&#39;year&#39;], x[&#39;month&#39;], x[&#39;day&#39;]), axis=1)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*BcB_RiMiofzvYpYx" /><figcaption>Addition of weekday Features</figcaption></figure><p>Next, we’ll remove the columns that do not contribute meaningful information to our analysis or model training.</p><pre>df.drop(&#39;date&#39;, axis=1, inplace=True)</pre><p>There may be other useful features that could be incorporated into the dataset. However, for now, we will proceed with the features currently available and use them to explore the data and uncover meaningful insights.</p><h3>Step 4: Exploratory Data Analysis (EDA)</h3><p>Exploratory Data Analysis (EDA) involves examining and understanding a dataset through visualizations and statistical techniques. It helps identify trends, patterns, relationships, and potential issues in the data using statistical summaries and graphical representations. In this case, we have also introduced additional features based on certain assumptions.</p><p>Next, we will use the <a href="https://www.geeksforgeeks.org/python/python-pandas-dataframe-nunique/">nunique()</a> function to determine the number of distinct values in the store and item columns. This will help us understand the variety of stores and items represented in the dataset.</p><pre>df[&#39;store&#39;].nunique(), df[&#39;item&#39;].nunique()</pre><p>Output:</p><pre>(10, 50)</pre><p>The results indicate that the dataset contains 10 unique stores, offering a total of 50 different products.</p><p>Next, we will visualize the data to explore how different features are associated with sales performance.</p><ul><li>plt.subplots() creates a figure that can contain multiple subplots, allowing us to display several visualizations in one figure.</li><li>df.groupby(col).mean()[‘sales’].<a href="http://plot.bar/">plot.bar</a>() groups the dataset according to the selected column, calculates the average sales for each category, and displays the results in a bar chart. This helps us compare sales performance across different feature categories and identify potential patterns or trends.</li></ul><pre>df[&#39;weekend&#39;] = df[&#39;weekday&#39;].apply(lambda x: 1 if x &gt;= 5 else 0)<br>features = [&#39;store&#39;, &#39;year&#39;, &#39;month&#39;, &#39;weekday&#39;, &#39;weekend&#39;, &#39;holidays&#39;]</pre><pre>plt.subplots(figsize=(20, 10))<br>for i, col in enumerate(features):<br>    plt.subplot(2, 3, i + 1)<br>    df.groupby(col).mean()[&#39;sales&#39;].plot.bar()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*rzGj6RE1OQRsKvaQ" /><figcaption>Bar plot for the average count of the ride request</figcaption></figure><p>Next, let’s use a line plot to examine how the stock price fluctuates as the month approaches its end.</p><pre>plt.figure(figsize=(10,5))<br>df.groupby(&#39;day&#39;).mean()[&#39;sales&#39;].plot()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*vMD7nNhQEEORWMkn" /><figcaption>Line plot for the average count of stock required on the respective days of the month</figcaption></figure><p>Let’s calculate and plot the 30-day Simple Moving Average (SMA) to smooth out short-term fluctuations in the data and reveal longer-term trends and recurring patterns.</p><pre>plt.figure(figsize=(15, 10))</pre><pre># Calculating Simple Moving Average <br># for a window period of 30 days<br>window_size = 30<br>data = df[df[&#39;year&#39;]==2013]<br>windows = data[&#39;sales&#39;].rolling(window_size)<br>sma = windows.mean()<br>sma = sma[window_size - 1:]</pre><pre>data[&#39;sales&#39;].plot()<br>sma.plot()<br>plt.legend()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*KRDNjpsRa0aOWk-X" /></figure><p>Since the Sales column contains continuous numerical values, we will examine its distribution to understand how the data is spread and identify any potential outliers. To perform this analysis, we will use a distribution plot (<a href="https://www.geeksforgeeks.org/machine-learning/seaborn-distribution-plots/">distplot</a>) and a <a href="https://www.geeksforgeeks.org/machine-learning/box-plot/">boxplot</a> to visualize the data and detect unusual values.</p><pre>plt.subplots(figsize=(12, 5))<br>plt.subplot(1, 2, 1)<br>sb.distplot(df[&#39;sales&#39;])</pre><pre>plt.subplot(1, 2, 2)<br>sb.boxplot(df[&#39;sales&#39;])<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*Ol171pFtVzXt-THx" /><figcaption>Distribution plot and Box plot for the target column</figcaption></figure><p>The distribution appears to be right-skewed, indicating that the dataset contains outliers.</p><p>Next, we will examine the correlations between the dataset’s features and apply a filter to identify only those with strong correlations. We can use the <a href="https://www.geeksforgeeks.org/pandas/python-pandas-dataframe-corr/">corr()</a> function in Pandas to calculate the correlation coefficients between the features.</p><pre>plt.figure(figsize=(10, 10))<br>sb.heatmap(df.corr() &gt; 0.8,<br>           annot=True,<br>           cbar=False)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*sCjdf8_iE5X97iFp" /><figcaption>Heatmap to detect the highly correlated features</figcaption></figure><p>As identified during the earlier analysis, we will now remove the outliers present in the dataset to improve data quality and support more reliable analysis.</p><pre>df = df[df[&#39;sales&#39;]&lt;140]</pre><h3>Step 5: Model Training</h3><p>In this step, we separate the input features from the target variable and divide the dataset into training and testing sets. We then train different models and evaluate their performance on validation data to identify the model that delivers the best results.</p><pre>features = df.drop([&#39;sales&#39;, &#39;year&#39;], axis=1)<br>target = df[&#39;sales&#39;].values<br></pre><pre>X_train, X_val, Y_train, Y_val = train_test_split(features, target,<br>                                                  test_size = 0.05,<br>                                                  random_state=22)<br>X_train.shape, X_val.shape</pre><p>Output:</p><pre>((861170, 9), (45325, 9))</pre><p>Normalizing the data before passing it to a machine learning model helps ensure faster, more stable, and efficient training.</p><pre># Normalizing the features for stable and fast training.<br>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_val = scaler.transform(X_val)</pre><p>The dataset has been divided into training and validation sets, and the data normalization process has been completed. The next step is to train multiple machine learning models and evaluate their performance on the validation set to identify the most effective model.</p><p>In this implementation, we use four algorithms: <a href="https://www.geeksforgeeks.org/machine-learning/ml-linear-regression/">Linear Regression</a>, <a href="https://www.geeksforgeeks.org/machine-learning/xgboost/">XGBoost</a>, <a href="https://www.geeksforgeeks.org/machine-learning/what-is-lasso-regression/">Lasso Regression</a>, and <a href="https://www.geeksforgeeks.org/machine-learning/what-is-ridge-regression/">Ridge Regression</a>.</p><pre>models = [LinearRegression(), XGBRegressor(), Lasso(), Ridge()]</pre><pre>for i in range(4):<br>    models[i].fit(X_train, Y_train)</pre><pre>    print(f&#39;{models[i]} : &#39;)</pre><pre>    train_preds = models[i].predict(X_train)<br>    print(&#39;Training Error : &#39;, mae(Y_train, train_preds))</pre><pre>    val_preds = models[i].predict(X_val)<br>    print(&#39;Validation Error : &#39;, mae(Y_val, val_preds))<br>    print()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*TUlrFvdW_KYTuaZ-" /></figure><p>After training and evaluating the models, XGBoost achieves the best performance by producing the lowest validation error. This highlights the effectiveness of ensemble learning techniques in identifying complex patterns and relationships within sales data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df584353f1ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Analysis Prediction — Python]]></title>
            <link>https://medium.com/@jithminikulatunga/customer-churn-analysis-prediction-python-1aa31e7e22f4?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa31e7e22f4</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 13:25:43 GMT</pubDate>
            <atom:updated>2026-10-24T13:25:43.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KUdWdfgzBhexReG1jL3Qw.png" /><figcaption>Customer Churn Analysis Prediction — Python</figcaption></figure><p>Customer churn refers to a situation where customers discontinue using a company’s services, potentially resulting in revenue loss. Analyzing customer churn enables businesses to identify the reasons behind customer departures and develop effective strategies to improve customer retention. A high churn rate can negatively impact revenue, profitability, and long-term business growth. By identifying churn patterns and customer behavior, businesses can take proactive measures to retain customers and strengthen customer relationships.</p><p>In this guide, we will explore the Telco Customer Churn dataset to analyze customer behavior and build a machine learning model to predict customer churn effectively.</p><h3>1. Importing Libraries and Dataset</h3><h3>Loading the Dataset</h3><p>We begin by importing the required Python libraries and loading the Telco Customer Churn dataset. It contains customer-related information, including service subscriptions, usage patterns, and churn status. You can download the dataset from <a href="https://media.geeksforgeeks.org/wp-content/uploads/20250324112511187444/Telco-Customer-Churn.csv">this link</a>.</p><pre>import numpy as np<br>import pandas as pd<br><br># give you file path here<br>dataset = pd.read_csv(&#39;/filename&#39;)<br><br>dataset.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*lEiaiw2cVHFCkyJ_" /><figcaption>Dataset</figcaption></figure><h3>Understanding the Dataset</h3><p>To better understand the dataset, we first examine its structure and check for missing values. The dataset contains several features, including:</p><pre>print(dataset.isnull().sum())<br>print(dataset.describe())</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*sbCECVPTYG3h5lyX" /></figure><ul><li>tenure – The number of months a customer has stayed with the company.</li><li>InternetService – The type of internet service the customer has DSL, Fiber optic or None.</li><li>PaymentMethod– The method the customer uses for payments.</li><li>Churn – The target variable i.e Yes for customer churned and No for customer stayed.</li></ul><h3>Analyzing Churn Distribution</h3><p>We analyze the number of customers who churned and those who stayed to understand the class distribution and balance of the dataset.</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>print(dataset[&#39;Churn&#39;].value_counts())<br>sns.countplot(x=&#39;Churn&#39;, data=dataset, palette=&#39;coolwarm&#39;)<br>plt.title(&#39;Churn Distribution&#39;)<br>plt.xlabel(&#39;Churn (0 = No, 1 = Yes)&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*fAF3Cy3NDMpxlgEi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*qSaF_hD3zk4NEK8c" /></figure><h3>2. Data Preprocessing</h3><h3>Handling Missing and Incorrect Values</h3><p>Before proceeding with data preprocessing, we need to ensure that all numerical columns contain valid numeric values. In the Telco Customer Churn dataset, the TotalCharges column may contain empty strings that must be handled appropriately.</p><ul><li>pd.to_numeric(dataset[&#39;TotalCharges&#39;], errors=&#39;coerce&#39;) converts the TotalCharges column into a numeric data type. Any values that cannot be converted, such as empty strings, are replaced with NaN (Not a Number).</li><li>dataset[&#39;TotalCharges&#39;] = dataset[&#39;TotalCharges&#39;].fillna(dataset[&#39;TotalCharges&#39;].median()) replaces missing values (NaN) with the median of the TotalCharges column, helping preserve the completeness of the dataset for further analysis and model development.</li></ul><pre>dataset[&#39;TotalCharges&#39;] = pd.to_numeric(dataset[&#39;TotalCharges&#39;], errors=&#39;coerce&#39;)<br>dataset[&#39;TotalCharges&#39;].fillna(dataset[&#39;TotalCharges&#39;].median(), inplace=True)</pre><h3>Handling Categorical Variables</h3><p>Some features, such as State, International Plan, and Voice Mail Plan, contain categorical data that must be transformed into numerical values before they can be used to train a machine learning model.</p><ul><li>LabelEncoder() converts categorical data into numerical labels by assigning a unique integer to each distinct category.</li><li>The loop iterates through the specified categorical columns and applies fit_transform() to identify the unique categories and replace them with their corresponding numerical labels.</li></ul><pre>from sklearn.preprocessing import LabelEncoder<br><br>labelencoder = LabelEncoder()<br>categorical_cols = [<br>    &#39;gender&#39;,<br>    &#39;Partner&#39;,<br>    &#39;Dependents&#39;,<br>    &#39;PhoneService&#39;,<br>    &#39;MultipleLines&#39;,<br>    &#39;InternetService&#39;,<br>    &#39;OnlineSecurity&#39;,<br>    &#39;OnlineBackup&#39;,<br>    &#39;DeviceProtection&#39;,<br>    &#39;TechSupport&#39;,<br>    &#39;StreamingTV&#39;,<br>    &#39;StreamingMovies&#39;,<br>    &#39;Contract&#39;,<br>    &#39;PaperlessBilling&#39;,<br>    &#39;PaymentMethod&#39;,<br>    &#39;Churn&#39;<br>]<br><br>for col in categorical_cols:<br>    dataset[col] = labelencoder.fit_transform(dataset[col].astype(str))</pre><h3>Feature Selection and Splitting Data</h3><p>We separate the input features (X) from the target variable (y) and divide the dataset into training and testing sets.</p><ul><li>X = dataset.drop([&#39;customerID&#39;, &#39;Churn&#39;], axis=1) removes the customerID column, which is generally not useful for prediction, and the Churn column, which represents the target variable.</li><li>y = dataset[&#39;Churn&#39;] assigns the Churn column to y, representing the outcome the model aims to predict.</li><li>train_test_split() divides the dataset into 80% training data to train the model and 20% testing data to evaluate its predictive performance on unseen data.</li></ul><pre>from sklearn.model_selection import train_test_split<br><br>X = dataset.drop([&#39;customerID&#39;, &#39;Churn&#39;], axis=1)<br>y = dataset[&#39;Churn&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)</pre><h3>Feature Scaling</h3><p>Since the features in a dataset may have different numerical scales, standardization is applied to bring them to a comparable scale. This helps prevent certain machine-learning algorithms from being disproportionately influenced by features with larger numerical values and can improve the convergence speed of optimization methods such as gradient descent.</p><ul><li>StandardScaler(): Scales the features so that they have a mean of 0 and a standard deviation of 1, helping place them on a comparable scale.</li><li>fit_transform(X_train): Calculates the scaling parameters from the training data and applies the transformation to it.</li><li>transform(X_test): Applies the same scaling parameters learned from the training data to the test data, ensuring consistent preprocessing and helping prevent data leakage.</li></ul><pre>from sklearn.preprocessing import StandardScaler<br><br>scaler = StandardScaler()<br><br>X_train = scaler.fit_transform(X_train)<br>X_test = scaler.transform(X_test)</pre><h3>3. Model Training and Prediction</h3><p>We use the <a href="https://www.geeksforgeeks.org/dsa/random-forest-classifier-using-scikit-learn/">Random Forest Classifier</a> to train our model. It is an ensemble machine learning algorithm that combines predictions from multiple decision trees to produce a final prediction.</p><pre>from sklearn.ensemble import RandomForestClassifier<br><br>clf = RandomForestClassifier()<br>clf.fit(X_train, y_train)<br><br>y_pred = clf.predict(X_test)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/0*0zeGMTr_rd0MRFQ8" /></figure><h3>4. Model Evaluation</h3><h3>Accuracy Score</h3><p>We evaluate the model’s performance by calculating its accuracy using the accuracy_score() function.</p><pre>from sklearn.metrics import accuracy_score<br><br>accuracy = accuracy_score(y_test, y_pred)<br>print(f&quot;Model Accuracy: {accuracy:.2f}&quot;)</pre><p>Output:</p><pre>Model Accuracy: 0.78</pre><h3>Confusion Matrix and Performance Metrics</h3><p>Precision, recall, and accuracy are evaluated using a confusion matrix.</p><pre>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br><br>cm = confusion_matrix(y_test, y_pred)<br>disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[&quot;No Churn&quot;, &quot;Churn&quot;])<br>disp.plot(cmap=&quot;coolwarm&quot;)<br>plt.title(&#39;Confusion Matrix&#39;)<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*SyR-ruAB6musanCs" /></figure><p>The confusion matrix illustrates the model’s performance in predicting customer churn. It correctly classifies 924 customers who do not churn and 181 customers who churn. However, 117 non-churning customers are incorrectly predicted as churners, while 187 actual churners are incorrectly classified as non-churners. The large number of missed churners indicates that the model may require further optimization to improve its ability to identify customers at risk of leaving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa31e7e22f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sales Forecast Prediction — Python]]></title>
            <link>https://medium.com/@jithminikulatunga/sales-forecast-prediction-python-7a320f24be20?source=rss-3e46fcde6dd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a320f24be20</guid>
            <dc:creator><![CDATA[Jithmini Kulatunga]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 13:17:07 GMT</pubDate>
            <atom:updated>2026-10-24T13:17:07.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgYrWMSmGSMBHbd_u6211A.png" /><figcaption>Sales Forecast Prediction — Python</figcaption></figure><p>Sales forecasting plays a vital role in effective business planning by enabling organizations to anticipate future sales and make data-driven decisions regarding inventory, marketing strategies, and resource allocation. In this article, we will explore how to develop a sales forecasting model using Python. The process involves analyzing historical data and identifying trends to estimate future sales performance.</p><p>The following section presents a step-by-step implementation of the sales forecasting model.</p><h3>1. Importing the Required Libraries</h3><p>Before beginning the project, make sure all the necessary Python libraries are installed. In this project, we will use Pandas, Matplotlib, Seaborn, XGBoost, and Scikit-learn for data manipulation, visualization, machine learning, and model development. These libraries can be installed easily using the pip package manager.</p><blockquote>pip install pandas numpy matplotlib seaborn scikit-learn xgboost</blockquote><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import xgboost as xgb<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error</pre><h3>2. Loading the Dataset</h3><p>In this step, we will use a sales dataset containing various features, such as Row ID, Order ID, Customer ID, and other relevant sales-related information. The dataset can be downloaded from the link provided <a href="https://media.geeksforgeeks.org/wp-content/uploads/20250408123407596371/train.csv">here</a>.</p><pre>file_path = &#39;train.csv&#39;<br>data = pd.read_csv(file_path)</pre><pre>data.head()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hKHGvjs-NKUJJcsN" /><figcaption>Dataset</figcaption></figure><h3>3. Data Preprocessing and Visualization</h3><p>In this step, we prepare the data for analysis and visualize how sales change over time.</p><ul><li>pd.to_datetime: Converts the “Order Date” column into a datetime format, making it easier to perform date- and time-based analysis.</li><li>groupby: Groups the sales records according to “Order Date” and calculates the total sales for each date, producing a daily sales time series.</li></ul><pre>data[&#39;Order Date&#39;] = pd.to_datetime(data[&#39;Order Date&#39;], format=&#39;%d/%m/%Y&#39;)</pre><pre>sales_by_date = data.groupby(&#39;Order Date&#39;)[&#39;Sales&#39;].sum().reset_index()</pre><pre>plt.figure(figsize=(12, 6))<br>plt.plot(sales_by_date[&#39;Order Date&#39;], sales_by_date[&#39;Sales&#39;], label=&#39;Sales&#39;, color=&#39;red&#39;)<br>plt.title(&#39;Sales Trend Over Time&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.grid(True)<br>plt.legend()<br>plt.xticks(rotation=45)<br>plt.tight_layout()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kjjp9sCgmujSyFG4" /><figcaption>Sales Trend Over Time</figcaption></figure><h3>4. Feature Engineering — Creating Lagged Features</h3><p>In this step, we create lagged features to capture time-based patterns and relationships within the sales data.</p><ul><li>create_lagged_features: This function creates lag features by shifting the sales values backward by a specified number of time steps, such as 1, 2, 3, and so on. These features allow the model to use previous sales information to identify patterns and make more accurate predictions of future sales.</li><li>dropna: This function removes rows containing missing values that are generated at the beginning of the dataset as a result of the shifting operation used to create the lagged features.</li></ul><pre>def create_lagged_features(data, lag=1):<br>    lagged_data = data.copy()<br>    for i in range(1, lag+1):<br>        lagged_data[f&#39;lag_{i}&#39;] = lagged_data[&#39;Sales&#39;].shift(i)<br>    return lagged_data</pre><pre>lag = 5  <br>sales_with_lags = create_lagged_features(data[[&#39;Order Date&#39;, &#39;Sales&#39;]], lag)</pre><pre>sales_with_lags = sales_with_lags.dropna()</pre><h3>5. Preparing the Data for Training</h3><p>In this step, the dataset is prepared for the model’s training and testing processes.</p><ul><li>drop(columns): Removes the Order Date and Sales columns from the feature set X. The Sales column is the target variable, while Order Date is not required as a direct input for model training.</li><li>train_test_split: Divides the dataset into two subsets: 80% for training the model and 20% for testing its performance.</li><li>shuffle=False: Prevents the data from being randomly shuffled, ensuring that the observations remain in chronological order and the original time-series structure is preserved.</li></ul><pre>X = sales_with_lags.drop(columns=[&#39;Order Date&#39;, &#39;Sales&#39;])<br>y = sales_with_lags[&#39;Sales&#39;]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)</pre><h3>6. Training the XGBoost Model</h3><p>In this step, we train an XGBoost model to predict sales. XGBoost is a powerful machine learning algorithm based on gradient boosting, which builds a series of decision trees to improve prediction performance. It is particularly effective for regression problems such as sales forecasting, where the goal is to predict continuous numerical values.</p><ul><li>XGBRegressor: Creates an XGBoost regression model designed to predict continuous numerical values.</li><li>objective=’reg:squarederror’: Specifies that the model is solving a regression problem using squared error as the loss function.</li><li>learning_rate (lr): Determines how much the model adjusts its predictions during each boosting iteration. A smaller learning rate generally results in slower learning but can help the model achieve better generalization.</li><li>n_estimators: Specifies the number of boosting rounds, or decision trees, used to build the model. Increasing this value can improve predictive performance, but using too many trees may result in overfitting.</li><li>max_depth: Sets the maximum depth of each decision tree and therefore controls the model’s complexity. Deeper trees can capture more complex patterns but may also increase the risk of overfitting.</li><li>fit: Trains the XGBoost model using the training features X_train and corresponding target values y_train.</li></ul><pre>model_xgb = xgb.XGBRegressor(objective=&#39;reg:squarederror&#39;, n_estimators=100, learning_rate=0.1, max_depth=5)<br>model_xgb.fit(X_train, y_train)</pre><h3>7. Making Predictions and Evaluating the Model</h3><p>In this step, we use the trained XGBoost model to generate predictions and assess its performance using the Root Mean Squared Error (RMSE) metric.</p><ul><li>predict: Uses the trained XGBoost model to predict the target values for the test dataset (X_test).</li><li>mean_squared_error: Calculates the Mean Squared Error (MSE) by comparing the actual values with the predicted values. We then apply np.sqrt to the MSE to obtain the Root Mean Squared Error (RMSE), a commonly used evaluation metric for regression models.</li></ul><pre>predictions_xgb = model_xgb.predict(X_test)<br>rmse_xgb = np.sqrt(mean_squared_error(y_test, predictions_xgb))</pre><pre>print(f&quot;RMSE: {rmse_xgb:.2f}&quot;)</pre><p>Output:</p><p><em>RMSE: 734.63</em></p><p>The RMSE value of 734.63 represents the average difference between the actual and predicted sales values. Generally, a lower RMSE indicates better model performance, as it means the predictions are closer to the actual sales figures. Considering the large volume of sales data used in this analysis, an RMSE of 734.63 is considered an acceptable result.</p><h3>8. Visualizing Results</h3><p>To further evaluate the model’s performance, we will visualize both the actual and predicted sales values. This comparison allows us to clearly observe how closely the model’s predictions follow the actual sales trends.</p><pre>plt.figure(figsize=(12, 6))<br>plt.plot(y_test.index, y_test, label=&#39;Actual Sales&#39;, color=&#39;red&#39;)<br>plt.plot(y_test.index, predictions_xgb, label=&#39;Predicted Sales&#39;, color=&#39;green&#39;)<br>plt.title(&#39;Sales Forecasting using XGBoost&#39;)<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.tight_layout()<br>plt.show()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JuLFdlkEuWFOuu_8" /><figcaption>Sales Forecasting using XGBoost</figcaption></figure><p>As shown in the results, the predicted values are relatively close to the actual values, demonstrating the effectiveness of the model. Machine learning algorithms such as XGBoost can improve sales forecasting accuracy by identifying and learning from temporal patterns in historical sales data. These predictions can help businesses make better decisions regarding inventory management, pricing strategies, and demand planning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a320f24be20" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>