<?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 Rahul Sisodia on Medium]]></title>
        <description><![CDATA[Stories by Rahul Sisodia on Medium]]></description>
        <link>https://medium.com/@rahulsisodia06?source=rss-8d0e847c9dca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NXF3HhlTXPv-swKKoiyH4Q.jpeg</url>
            <title>Stories by Rahul Sisodia on Medium</title>
            <link>https://medium.com/@rahulsisodia06?source=rss-8d0e847c9dca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:55:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulsisodia06/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[Credit Risk Modelling in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/credit-risk-modelling-in-python-7b21a0b794b1?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b21a0b794b1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[credit-risk]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 09:32:34 GMT</pubDate>
            <atom:updated>2022-01-21T10:30:54.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1kuLl_N1AsrWDdd2.jpg" /><figcaption>The Source of the image is <a href="https://cascadebusnews.com/understanding-credit-risk-management-matters/">here</a></figcaption></figure><h3>What is Credit Risk?</h3><p>Credit risk is the possibility that a borrower will not be able to make timely payments and will default on their debt. It refers to the possibility that a lender may not get the interest or principal due to them on time.</p><p>Financial organizations are concerned about reducing the risk of default. As a result, commercial and investment banks, venture capital funds, asset management organizations, and insurance corporations, to mention a few, are increasingly depending on technology to anticipate which customers are most likely to default on their obligations.</p><h3>What is Credit Risk Modelling?</h3><p>A person’s credit risk is influenced by a variety of things. As a result, determining a borrower’s credit risk is a difficult undertaking. Credit risk modeling has entered the scene since there is so much money relying on our ability to appropriately predict a borrower’s credit risk.</p><p>Credit risk modeling is the practice of applying data models to determine two key factors. The first is the likelihood that the borrower will default on the loan. The second factor is the lender’s financial impact if the default occurs.</p><p>Credit risk models are used by financial organizations to assess the credit risk of potential borrowers.</p><blockquote>For companies involved in the financial system, preserving the financial health of clients is critical. However, you could be wondering how to protect each client’s financial well-being. The answer to this challenge entails assessing each client’s payment likelihood based on a set of criteria and devising tactics to anticipate customer wants.</blockquote><blockquote>As a result, the goal of this research is to forecast the likelihood of default on a specific obligation, in this example, credit cards. This will enable the creation of solutions that reduce the risk of the client’s financial health deteriorating. Furthermore, it is proposed to employ clustering techniques to locate homogeneous portions within the population and thus provide differentiated treatment to each client in order to assist the creation of collection tactics.</blockquote><blockquote>The model will be constructed using the procedures below.</blockquote><p>1. Data preparation and Pre-processing</p><p>2. Feature Engineering and Selection</p><p>3. Model Development and Model Evaluation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*6KcRkfNyIhpHbZiO.png" /><figcaption>(Source: <a href="https://www.omnisci.com/technical-glossary/feature-engineering)">https://www.omnisci.com/technical-glossary/feature-engineering)</a></figcaption></figure><h3>About the Data</h3><p>The data set was taken from Kaggle <a href="https://www.kaggle.com/uciml/default-of-credit-card-clients-dataset">here</a></p><p>This study analyses the predicted accuracy of probability of default among six data mining methods in the instance of consumers&#39; default payments in Taiwan. The result of predictive accuracy of the projected probability of default will be more beneficial than the binary result of classification — credible or not credible clients — from the standpoint of risk management. Because the true likelihood of default is unknown, this study used a novel sorting Smoothing Method to approximate it. The response variable (Y) is the real probability of default, while the independent variable is the prediction chance of default (X).</p><p><strong>Variables:</strong></p><p><em>LIMIT_BAL</em>: Amount of the given credit (NT dollar): it includes both the individual consumer credit and his/her family (supplementary) credit. SEX: Gender (1 = male; 2 = female).</p><p><em>EDUCATION</em>: Education (1 = graduate school; 2 = university; 3 = high school; 4 = others).</p><p><em>MARRIAGE</em>: Marital status (1 = married; 2 = single; 3 = divorse, 0= others).</p><p><em>AGE</em>: Age (year).</p><p><em>PAY0 — PAY6</em>: History of past payment. We tracked the past monthly payment records (from April to September, 2005) as follows: PAY0 = the repayment status in September, 2005; PAY1 = the repayment status in August, 2005; . . .;PAY6 = the repayment status in April, 2005. The measurement scale for the repayment status is: -2: No consumption; -1: Paid in full; 0: The use of revolving credit; 1 = payment delay for one month; 2 = payment delay for two months; . . .; 8 = payment delay for eight months; 9 = payment delay for nine months and above.</p><p><em>BILL_AMT1- BILL_AMT6</em>: Amount of bill statement (NT dollar). BILL_AMT1 = amount of bill statement in September, 2005; BILL_AMT2 = amount of bill statement in August, 2005; . . .; BILL_AMT6 = amount of bill statement in April, 2005.</p><p><em>PAY_AMT1-PAY_AMT2</em>: Amount of previous payment (NT dollar). PAY_AMT1 = amount paid in September, 2005; PAY_AMT2 = amount paid in August, 2005; . . .; PAY_AMNT6 = amount paid in April, 2005.</p><pre><em># Reading the data </em><br>credit_risk<strong>=</strong> pd<strong>.</strong>read_csv(&quot;UCI_credit_card.csv&quot;)<br>credit_risk<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0cYsuyaOJbZv4PvTmkFAQ.png" /><figcaption>Data</figcaption></figure><h3>Data preparation and Pre-processing</h3><p>This is where the data for credit risk modeling came from. Initially, the data revealed a total of 25 attributes. It is critical to clean the data in a suitable format before developing any machine learning model.</p><h4>Analysis of column “EDUCATION”</h4><p>EDUCATION: (1=graduate school, 2=university, 3=high school, 4=others, 5=unknown, 6=unknown)</p><blockquote><em>From the Data Description given, we know that in df.EDUCATION, 5 and 6 represents “unknown” </em><br><em>Changing 0,5 and 6 to keep it under 1 category.</em></blockquote><pre>df[&#39;EDUCATION&#39;]<strong>.</strong>replace({0:1,1:1,2:2,3:3,4:4,5:1,6:1}, inplace<strong>=True</strong>)<br>df<strong>.</strong>EDUCATION<strong>.</strong>value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*lyOg-ovnuNjmetHi6tb2vQ.png" /><figcaption>Education column in data</figcaption></figure><h4>Analysis of column “MARRIAGE”</h4><p>Marital status (1=married, 2=single, 3=others)</p><pre><em># lets see the values count in column marriage</em><br>df[&#39;MARRIAGE&#39;]<strong>.</strong>value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*CM93Q-zJL_OHdkCdpXW3Jw.png" /><figcaption>Marriage column in data</figcaption></figure><p>Here I am going to map 0 with 1.</p><pre>df[&#39;MARRIAGE&#39;]<strong>.</strong>replace({0:1,1:1,2:2,3:3}, inplace<strong>=True</strong>)<br>df[&#39;MARRIAGE&#39;]<strong>.</strong>value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*VcOQ1dqgGshGofJPnsXswA.png" /><figcaption>marriage column after mapping</figcaption></figure><h4>Analysis of column “PAY_0 to PAY_6”</h4><p>PAY_0: Repayment status in September 2005 (-1=pay duly, 1=payment delay for one month, 2=payment delay for two months, … 8=payment delay for eight months, 9=payment delay for nine months and above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*0dMAB_uw-NqIPNldsqqrTg.png" /><figcaption>pay_0 column in data</figcaption></figure><h3>Data Visualization</h3><figure><img alt="So, By looking at the target varibale we could say that, our data is pretty much imbalance. We would like to make it balanced before going to trained the model." src="https://cdn-images-1.medium.com/max/649/1*A-TUx5nmTeMVMGbelT6Zhg.png" /><figcaption>Target variable (Author image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*e5v-M8wkh5WJzzh1celrUQ.png" /><figcaption>Education column (Author image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*NgL_BXELqYF5-NmW3SeaGg.png" /><figcaption>Age column distribution (Author image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*mSEG_VxvanX7WCgQ7sroUA.png" /><figcaption>Sex column ( Author image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viLjqTEoI4PjyiY1Z-tlkA.png" /><figcaption>Scatter plot ( Author image)</figcaption></figure><h4>Creating Independent features and dependent features</h4><ul><li>Independent variables (also referred to as Features) are the input for a process that is being analyzed. Dependent variables are the output of the process.</li></ul><pre><em># Independnet features</em><br>X <strong>=</strong> df<strong>.</strong>drop([&#39;default.payment.next.month&#39;], axis<strong>=</strong>1)<br><em># Dependent feature</em><br>y <strong>=</strong> df[&#39;default.payment.next.month&#39;]<br>X<strong>.</strong>head()</pre><h4>Scaling the features</h4><ul><li>The process of scaling or transforming all of the variables in our dataset to a given scale is known as feature scaling. Gradient descent optimization is used in some machine learning methods such as linear regression, logistic regression, and others. For these algorithms to work properly, the data must be scaled.</li><li>Standardization is the process of scaling the data values in such a way that they gain the properties of standard normal distribution. This means that the data is rescaled in such a way that the mean becomes zero and the data has a unit standard deviation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*C9nhpuiviXJqMcIzNQRYug.png" /><figcaption>Formula for standardization</figcaption></figure><pre><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler<br>scaler<strong>=</strong> StandardScaler()<br>X<strong>=</strong> scaler<strong>.</strong>fit_transform(X)</pre><h4>Train Test Split</h4><ul><li>The entire dataset (population) is split into two groups: the train set and the test set. Depending on the use case, the data can be divided into 70–30 or 60–40, 75–25 or 80–20, or even 50–50. In general, the proportion of training data must be greater than the proportion of test data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pr4nVYDtuNNq4Rck-wa9iw.png" /><figcaption>Splitting the data (Image Source: DataVedas)</figcaption></figure><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br>X_train,X_test,y_train,y_test<strong>=</strong> train_test_split(X,y,test_size<strong>=</strong>0.20,random_state<strong>=</strong>42)</pre><h4><strong>Class imbalance</strong></h4><ul><li>For over-sampling techniques, SMOTE (Synthetic Minority Oversampling Technique) is considered one of the most popular and influential data sampling algorithms in ML and data mining. With SMOTE, the minority class is over-sampled by creating “synthetic” examples rather than by over-sampling with replacement [2]. These introduced synthetic examples are based along the line segments joining a defined number of k minority class nearest neighbors, which is in the learning package is set at five by default.</li></ul><pre><strong>from</strong> imblearn.over_sampling <strong>import</strong> SMOTE<br><strong>from</strong> collections <strong>import</strong> Counter<br><br><em># summarize class distribution</em><br>print(&quot;Before oversampling: &quot;,Counter(y_train))<br><br><em># define oversampling strategy</em><br>SMOTE<strong>=</strong> SMOTE()<br><br><em># fit and apply the transform </em><br>X_train,y_train<strong>=</strong> SMOTE<strong>.</strong>fit_resample(X_train,y_train)<br><br><em># summarize class distribution</em><br>print(&quot;After oversampling: &quot;,Counter(y_train))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*SxzvOVlJNnAvUgeDWdjWLg.png" /></figure><h3>Building Model</h3><ul><li>Logistic Regression</li><li>Random Forest Classifier</li><li>XGBoost Classifier</li><li>Cross-validation</li></ul><h4>Logistic regression Model</h4><ul><li>The main aim of logistic regression is to determine the relationship between features and the probability of a particular outcome.</li><li>It used the Sigmoid function to map the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*4WAwVBLfngaGciU6ENM4vw.png" /><figcaption>Image source <a href="https://www.analyticsvidhya.com/blog/2021/03/logistic-regression/">here</a></figcaption></figure><pre><strong>from</strong> sklearn.linear_model <strong>import</strong> LogisticRegression<br>logit<strong>=</strong> LogisticRegression()</pre><pre>logit<strong>.</strong>fit(X_train, y_train)</pre><pre><em># Predicting the model</em><br>pred_logit<strong>=</strong> logit<strong>.</strong>predict(X_test)</pre><h4>Evaluating the logit model</h4><ul><li><strong>Accuracy</strong>: the proportion of the total number of correct predictions.</li><li><strong>Positive Predictive Value or Precision</strong>: the proportion of positive cases that were correctly identified.</li><li><strong>Negative Predictive Value</strong>: the proportion of negative cases that were correctly identified.</li><li><strong>Sensitivity or Recall</strong>: the proportion of actual positive cases which are correctly identified.</li><li><strong>Specificity</strong>: the proportion of actual negative cases which are correctly identified.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*HH0OTfLcj2eIy3U_.jpg" /><figcaption>Confusion metrics (Image source <a href="https://manisha-sirsat.blogspot.com/2019/04/confusion-matrix.html">here</a>)</figcaption></figure><pre><strong>from</strong> sklearn.metrics <strong>import</strong> classification_report, accuracy_score, confusion_matrix, roc_auc_score, plot_confusion_matrix, plot_precision_recall_curve<br><br>print(&quot;The accuracy of logit model is:&quot;, accuracy_score(y_test, pred_logit))<br>print(classification_report(y_test, pred_logit))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*M-XxGM3cX6mIi5JAK1KnSQ.png" /><figcaption>Classification report of Logit model</figcaption></figure><h4>Random Forest Classifer</h4><blockquote>Step 1: In Random forest n number of random records are taken from the data set having k number of records.</blockquote><blockquote>Step 2: Individual decision trees are constructed for each sample.</blockquote><blockquote>Step 3: Each decision tree will generate an output.</blockquote><blockquote>Step 4: Final output is considered based on <strong><em>Majority Voting or Averaging </em></strong>for Classification and regression respectively.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxLAfrbH7WzAjLyVxKmGaQ.png" /><figcaption>Random forest(Image source <a href="https://www.analyticsvidhya.com/blog/2021/06/understanding-random-forest/">here</a>)</figcaption></figure><pre><strong>from</strong> sklearn.ensemble <strong>import</strong> RandomForestClassifier<br>rf<strong>=</strong> RandomForestClassifier()<br><em># Fitting the model</em><br>rf<strong>.</strong>fit(X_train,y_train)</pre><pre><em># Predicting the model</em><br>pred_rf<strong>=</strong> rf<strong>.</strong>predict(X_test)</pre><h4>Evaluating the Random Forest model</h4><pre>print(&quot;The accuracy of logit model is:&quot;, accuracy_score(y_test, pred_rf))<br>print(classification_report(y_test,pred_rf ))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*Se7TyplLHw670ZSCW_2Gog.png" /><figcaption>classification report of the Random Forest model</figcaption></figure><h4>XGBoost Classifier</h4><ul><li>Another prominent boosting method is Extreme Gradient Boosting or XGBoost. XGBoost is, in reality, just a tweaked version of the GBM algorithm! The operation of XGBoost is identical to that of GBM. In XGBoost, trees are produced in sequential order, with each tree trying to fix the errors of the previous trees.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*HVUCSrNehO91ZI1zPWu4yg.png" /><figcaption>Image source <a href="https://www.analyticsvidhya.com/blog/2020/02/4-boosting-algorithms-machine-learning/">here</a></figcaption></figure><pre><strong>import</strong> xgboost <strong>as</strong> xgb<br><br>xgb_clf<strong>=</strong> xgb<strong>.</strong>XGBClassifier()<br><em>#fitting the model</em><br>xgb_clf<strong>.</strong>fit(X_train,y_train)</pre><pre><em>## Predicting the model</em><br>xgb_predict<strong>=</strong> xgb_clf<strong>.</strong>predict(X_test)</pre><h4>Evaluating the Xgboost model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ziwa7-6qXxrDhKw_79BETw.png" /><figcaption>classification report of xgboost model</figcaption></figure><h4>Hyperparameter tunning the xgboost model</h4><pre><em>## Hyper Parameter Optimization</em><br><br>params<strong>=</strong>{<br> &quot;learning_rate&quot;    : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] ,<br> &quot;max_depth&quot;        : [ 3, 4, 5, 6, 8, 10, 12, 15],<br> &quot;min_child_weight&quot; : [ 1, 3, 5, 7 ],<br> &quot;gamma&quot;            : [ 0.0, 0.1, 0.2 , 0.3, 0.4 ],<br> &quot;colsample_bytree&quot; : [ 0.3, 0.4, 0.5 , 0.7 ]<br>    <br>}</pre><pre><em>## Hyperparameter optimization using RandomizedSearchCV</em><br><strong>from</strong> sklearn.model_selection <strong>import</strong> RandomizedSearchCV, GridSearchCV</pre><pre>random_search<strong>=</strong>RandomizedSearchCV(xgb_clf,param_distributions<strong>=</strong>params,n_iter<strong>=</strong>5,scoring<strong>=</strong>&#39;roc_auc&#39;,n_jobs<strong>=-</strong>1,cv<strong>=</strong>5,verbose<strong>=</strong>3)<br><br><em># fitting the RandomizedSearchCV</em><br>random_search<strong>.</strong>fit(X_train,y_train)</pre><p>Then we will find the best estimators and parameters.</p><pre><em># Finding the best estimators</em><br>random_search<strong>.</strong>best_estimator_</pre><pre><em># Finding the best param</em><br>random_search<strong>.</strong>best_params_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*SdhfvzUNLxDlS8qS3_Np9A.png" /><figcaption>Optimal parameters</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*qKG5WsJT7M8VHQnQlrVjdw.png" /><figcaption>Best estimators</figcaption></figure><pre><em># Predicting model</em><br>y_pred<strong>=</strong> classifier<strong>.</strong>predict(X_test)</pre><h4>k-fold Cross-validation</h4><p>Let’s extrapolate the last example to k-fold from 2-fold cross-validation. Now, we will try to visualize how does a k-fold validation work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7GByn7i7tAaa1etn.png" /><figcaption>(Image source<a href="https://dataaspirant.com/10-k-fold-cross-validation/"> here</a>)</figcaption></figure><p>This is a seven-fold cross-validation procedure.</p><p>Here’s how it works: we divide the total population into 5 equal samples. Models are now trained on four samples (blue boxes) and validated on one sample (yellow box). The model is then trained with a new sample held as validation in the second iteration. We developed a model on each sample in 5 iterations and held each of them as validation. This is a method for lowering selection bias and lowering prediction power variance. Once we have all five models, we average the error terms to determine which one is the best.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> cross_val_score<br>score<strong>=</strong>cross_val_score(classifier,X,y,cv<strong>=</strong>10)</pre><pre>score<strong>.</strong>mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ALS6w4dPH07iPds9yzKk7A.png" /><figcaption>Final accuracy</figcaption></figure><h3>Conclusion:</h3><p>We have built the credit risk model by using python. we have tried with different machine learning algorithms ie. Logistic regression, Random Forest, and Xgboost classifier. we have also done hyperparameter tuning and cross-validation. The final accuracy of the model we achieved was 82%.</p><h4>For the full code, please refer to the <a href="https://github.com/rahkum96/Credit-Risk-Modelling-in-Python/blob/main/Credit%20Risk%20Modelling%20in%20Python.ipynb">Notebook.</a></h4><h3>Sources:</h3><ul><li><a href="https://medium.com/analytics-vidhya/credit-risk-modelling-in-python-3ab4b00f6505">Source 1</a></li><li><a href="https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/">Source 2</a></li><li><a href="https://towardsdatascience.com/credit-risk-analysis-with-machine-learning-736e87e95996">Source 3</a></li></ul><h3>Follow me</h3><p><a href="https://www.linkedin.com/in/rahulsisodia06/">LinkedIn</a></p><p><a href="https://github.com/rahkum96">GitHub</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b21a0b794b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping Using Python BeautifulSoup]]></title>
            <link>https://medium.com/@rahulsisodia06/web-scraping-using-python-beautifulsoup-cb1554c0aae?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb1554c0aae</guid>
            <category><![CDATA[imdb]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 18:11:15 GMT</pubDate>
            <atom:updated>2021-12-23T07:13:54.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-1efL6hXvwbLiD_1.jpg" /><figcaption>Source: Google</figcaption></figure><p>With a sample scenario, you’ll learn what web scraping is and how to extract data from a website in this blog.</p><h3>What is Web Scraping?</h3><p>Web scraping is a method of extracting data from web pages using computer software. This technology is mostly used to convert unstructured data (HTML format) on the web into structured data (database or spreadsheet).</p><p>Web scraping can be done in a variety of ways, from Google Docs to practically any computer language. Python would be my first choice due to its simplicity and diverse ecosystem. It features a library called ‘BeautifulSoup’ that helps with this. In this post, I’ll show you how to learn web scraping using Python programming in the simplest way possible.</p><h3>Workflow</h3><ol><li>Insect the page</li><li>Obtain HTML</li><li>Choose a parser (Html. parser)</li><li>Create a BeautifulSoup object</li><li>Extract tags that we need</li><li>Store the data in lists</li><li>Make a data frame</li><li>Download excel file that contains all data scraped Specification</li></ol><p>The packages that we need for this task are <a href="https://requests.readthedocs.io/en/master/">requests</a>, <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">beautifulsoup4</a>, and <a href="https://pandas.pydata.org/">pandas</a>. Here’s a quick look at how to download this information:</p><h3>Libraries required for web scraping</h3><p><strong>BeautifulSoup:</strong> It’s a fantastic tool for extracting data from a webpage. You may use it to extract tables, lists, and paragraphs from web pages, as well as apply filters to extract information.</p><p><strong>requests:</strong> Target URL to scrap</p><pre># importing required libraries<strong><br>import</strong> requests <br><strong>from</strong> bs4 <strong>import</strong> BeautifulSoup </pre><h3>Step 1: Insect the page</h3><p>The initial step in web scraping is to go to the target website and download the page’s source code. This will be accomplished with the help of the requests library.</p><h4><strong>Target URL to scrap</strong></h4><blockquote><em>I’ve used “raise_for_status ()”, it doesn&#39;t throw an error it means the URL link is valid.</em></blockquote><p>Then, I sent a request to get data from the website and check its status.</p><pre># send request to download the data<br>url<strong>=</strong> requests<strong>.</strong>get(&#39;https://www.imdb.com/chart/top/&#39;)<br><em># Lets check the the url is valid or not </em><br>url<strong>.</strong>raise_for_status()</pre><h3>Step 2:</h3><blockquote>Obtain HTML</blockquote><blockquote>Choose a parser (Html. parser)</blockquote><blockquote>Create a BeautifulSoup object</blockquote><h4>Using BeautifulSoup:</h4><p>After getting the HTML of the page, I created a Beautiful Soup object from the HTML. Access the HTML content from the webpage by assigning the URL and creating a soap object.</p><pre><em># Now we have to get html written code here by using parser</em><br>soup<strong>=</strong> BeautifulSoup(url<strong>.</strong>text,&#39;html.parser&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTPbJJ9euUaCMzYME39HRA.png" /><figcaption>Output of soup</figcaption></figure><p>The above code stores the HTML content of our web page into an BeautifulSoup object. The HTML of the page can be printed out clearly by running the following line:</p><h3>Step 3: Extract tags that we need</h3><p>To check which tags contain our information, right-click on the element in your browser and select <strong>Inspect</strong>. In this case, the relevant information in the table is associated with the tag &lt;td&gt;. Use the find_all method to check it out:</p><ul><li>Extract the movie ratings and their details. Here, we are extracting data from the BeautifulSoup objects using Html tags like “tbody”, “tr”, etc.</li><li>I can use the find or find all methods to access objects. Even if you know very little about HTML at this point, you can simply access your objects.</li></ul><pre><em># Now we have find the tag in html file for 250 movies </em><br>movies<strong>=</strong> soup<strong>.</strong>find(&#39;tbody&#39;, class_<strong>=</strong> &#39;lister-list&#39;) <br><em># find will try to match the first tag who has &#39;tbody&#39; and class with &#39;lister-list&#39;</em><br><em>#Here class is different meaning in python, so we will use class with underscore  &quot;class_&quot;</em><br><br><em># from tbody we have find all &#39;tr&#39; tags which is movie list of 250 movies</em><br>movies<strong>=</strong>movies<strong>.</strong>find_all(&#39;tr&#39;)</pre><p>Here, I went to “tbody” tags where all the 250 movies are present under the “tbody” tag there are tags with “tr” and class lister-list which has each movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMqCjKBTQdIeyn2A7Ala4w.png" /><figcaption>output of movies</figcaption></figure><h3>Step 4: Store the data in lists</h3><p>After extracting the movie details, create an empty list and store the details in a dictionary, and then add them to a list.</p><p>Here we are extracting the movie name, Ranking, Year of release, and IMDB Rating.</p><p>Now, for each movie, we have to find the above movie Name which can be extracted from the <em>&lt;tr&gt;</em> tag only. <strong>This is because there is only one <em>&lt;tr&gt;</em> tag for each movie name followed by &lt;td&gt; tag along with the &lt;class&gt; tag and class name “title column</strong>”</p><p>Now that we know how to find all such tags on a page, we’re nearly good to go. The following snippet will parse the HTML page to get the data we need in a pandas data frame with four columns — Ranking, Movie Name, Year, and IMDB Rating:</p><pre><em># I will for loop for extracting 250 movies name</em><br>movie_details<strong>=</strong>[]<br><strong>for</strong> movie <strong>in</strong> movies:<br>    name<strong>=</strong> movie<strong>.</strong>find(&#39;td&#39;, class_<strong>=</strong>&quot;titleColumn&quot;)<strong>.</strong>a<strong>.</strong>text <br><em># We are fetching the name of movies by first entring into the &#39;td&#39; tag then &#39;a&#39;tag then fetching the text of &#39;a&#39; tag</em><br>    name1<strong>=</strong> movie<strong>.</strong>find(&#39;td&#39;, class_<strong>=</strong>&quot;titleColumn&quot;)<strong>.</strong>text <em># Here we are getting spaces and not formated </em><br>    name2<strong>=</strong> movie<strong>.</strong>find(&#39;td&#39;, class_<strong>=</strong>&quot;titleColumn&quot;)<strong>.</strong>get_text(strip<strong>=</strong> <strong>True</strong>) <em># Here we remove the all the spaces </em><br>    <br>    <em>#rank</em><br>    rank<strong>=</strong> movie<strong>.</strong>find(&#39;td&#39;, class_<strong>=</strong>&quot;titleColumn&quot;)<strong>.</strong>get_text(strip<strong>=</strong> <strong>True</strong>)<strong>.</strong>split(&#39;.&#39;)[0] <br>    <em># Here i am using split so, it will split into two string and indexing 1st element </em><br>    <br>    <em>#year</em><br>    year<strong>=</strong> movie<strong>.</strong>find(&#39;td&#39;, class_<strong>=</strong>&quot;titleColumn&quot;)<strong>.</strong>span<strong>.</strong>text <br>    <em># first entering into thr &#39;td&#39; tag then &#39;span&#39;tag from there fetching text</em><br>    year1<strong>=</strong> year<strong>.</strong>strip(&#39;()&#39;) <em># Here i am stripping &#39;()&#39;</em><br>    <br>    <em># Rating, </em><br>    rating<strong>=</strong>movie<strong>.</strong>find(&#39;td&#39;, class_<strong>=</strong> &#39;ratingColumn imdbRating&#39;)<strong>.</strong>strong<strong>.</strong>text<br><br>    <br>    print(rank,name,year1,rating)<br>    movie_details<strong>.</strong>append([rank,name,year1,rating])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*PzHMlUNV3qdaecJrQGuL6w.png" /><figcaption>List of movies</figcaption></figure><h3>Step 5: Create DataFrame</h3><p>A DataFrame is a two-dimensional data structure with labels that relate to the data. A DataFrame is a type of data structure that is similar to SQL tables or Excel sheets. Because they are an integral part of the Python and NumPy libraries, DataFrame is often faster, easier to use, and more powerful than spreadsheets or excel sheets/CSV files. There are various ways to generate a pandas DataFrame, however, this article will show you the most straightforward method. We’ll make the DataFrame out of a dictionary of array/list with identical lengths for all the arrays.</p><pre><strong>import</strong> pandas <strong>as</strong> pd<br>df<strong>=</strong> pd<strong>.</strong>DataFrame(movie_details, columns<strong>=</strong>[&#39;Rating&#39;,&#39;Movie_name&#39;,&#39;Year_realse&#39;,&#39;IMDB_rating&#39;])</pre><pre>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*Uxwfrc7-dQ8jOxuM382Qww.png" /><figcaption>Movies DataFrame</figcaption></figure><h3>Step 6: Moving data to excel</h3><p>Now, we can save our DataFrame in an Excel file using the pandas “to_excel” function. As we don’t want to store the preceding indices of each row, hence, we will set index=False.</p><pre>df<strong>.</strong>to_excel(r&#39;Top Movies.xlsx&#39;,index<strong>=False</strong>)</pre><h3>EndNote</h3><p>We looked at web scraping methods in Python using “BeautifulSoup” and “requests” in this article. We also went through the fundamentals of HTML and how to execute web scraping step by step while working on a problem. I encourage that you practice this and apply it to data collection from websites.</p><h3>Code</h3><p><a href="https://github.com/rahkum96/Web-Scraping-Using-Python-BeautifulSoup">GitHub - rahkum96/Web-Scraping-Using-Python-BeautifulSoup: Scraping data from web using python library BeautifulSoup and requests</a></p><h3><strong>Follow me</strong></h3><h4>LinkedIn</h4><p><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></p><h4>GitHub</h4><p><a href="https://github.com/rahkum96">rahkum96 - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb1554c0aae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Movie Recommendation System in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/movie-recommendation-system-c8113226c0aa?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8113226c0aa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Sat, 11 Dec 2021 11:57:52 GMT</pubDate>
            <atom:updated>2025-01-20T19:01:45.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>The MovieLens DataSet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WlOKs3sB_prKln26.jpg" /><figcaption>Source: Google</figcaption></figure><h3><strong>What is a Recommendation System:</strong></h3><p>A recommendation system is a type of information filtering system that attempts to predict how a user would rate or prefer an item. In layman’s terms, it is an algorithm that suggests relevant items to users. For example, on Netflix, which movie to watch, on e-commerce, which product to buy, on Kindle, which book to read, and so on.</p><h3>Recommendation Algorithms:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QEEHhbZ6lwdr926m.png" /></figure><h4>Content-based Algorithms</h4><ul><li>Idea: If you like something, you’ll also like something “similar” items.</li><li>Based on items Content, the similarity of the recommended items.</li><li>It usually works effectively when determining the context/properties of each object is simple. For example, when we are recommending the same type of material, such as a movie or song recommendation.</li></ul><h4>Collaborative filtering algorithms:</h4><ul><li>Idea: If a person A likes movies 1, 2, 3, and B likes 2,3,4, they have identical interests, and A should like movies 4 and B should like movies 1.</li><li>Here We are only seeing the behavior of users, and based on user behavior movies are recommended.</li><li>This method is purely based on previous behavior and does not take into account context. Because it does not require any additional information, it is one of the most widely used algorithms.</li><li>For example, e-commerce players like Amazon make product suggestions, while banks like American Express make merchant recommendations.</li></ul><p><strong>Goal:</strong> In this implementation, when the user searches for a movie we will recommend the top 5 similar movies using our movie recommendation system.</p><h4><strong>Data set:</strong></h4><p>The dataset was provided by MovieLens, a movie recommendation service. It includes the movies and the rating scores made for these movies. contains. It contains<strong>100,000 ratings</strong> (1–5) from 943 users on 1682 movies.</p><h3>Let’s start coding up our Movie recommendation system:</h3><p>Let’s get this data into Python. We may use several of the files in the ml-100k.zip file. To obtain a sense of the data, let’s load the three most important files.</p><pre><strong># Library<br>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> seaborn <strong>as</strong> sns<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt</pre><p>We have imported the basic libraries. And we will also upload the data.</p><h4>Users Data:</h4><pre><em>#Reading users file:</em><br>column_names <strong>=</strong> [&#39;user_id&#39;, &#39;item_id&#39;, &#39;rating&#39;, &#39;timestamp&#39;]<br>users<strong>=</strong> pd<strong>.</strong>read_csv(&#39;u.data&#39;, sep<strong>=</strong>&#39;\t&#39;, names<strong>=</strong>column_names)</pre><pre><em># Checking shape of users files and head </em><br>print(users<strong>.</strong>shape)<br>users<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*hri5LNf9E2FcRpPhFu3i1Q.png" /><figcaption>user data</figcaption></figure><p>This reconfirms that there are 100003 users and we have 4 features. This confirms that there are 100K ratings for different user and movie combinations. Also, notice that each rating has a timestamp associated with it.</p><h4>Movies data:</h4><pre><em># Reading the movie data</em><br>movies<strong>=</strong> pd<strong>.</strong>read_csv(&#39;Movie_Id_Titles&#39;)</pre><pre><em># Checking shape of movie data and look first 5 rows</em><br>print(movies<strong>.</strong>shape)<br>movies<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*2lQrdx0YCSD6I-YeexAH_g.png" /><figcaption>Movies data</figcaption></figure><p>This dataset contains attributes of the 1682 movies. There are 2 columns item_id and title.</p><h4>Merge the 2 CSV files:</h4><ul><li>Here we are going to merge two data frame on the same columns <strong>“item_id”</strong> and store it in a data frame called<strong> “df”</strong></li><li>We will use pd.merge to merge these data frame</li></ul><pre><em># Combining the data on same column</em><br>df<strong>=</strong> pd<strong>.</strong>merge(users, movies, on<strong>=</strong> &#39;item_id&#39;)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*ce3h1FlgX0d8EdslASHQwg.png" /><figcaption>Combined data</figcaption></figure><h4>EDA</h4><p>To better understand the data, EDA entails generating summary statistics for numerical data in the dataset and generating various graphical representations.</p><p>Let’s explore the data a bit and get a look at some of the best-rated movies.</p><pre><em># lets see the average rating for all these movies</em><br>df<strong>.</strong>groupby(&#39;title&#39;)<strong>.</strong>agg({&#39;rating&#39;:&#39;mean&#39;})<strong>.</strong>sort_values(by<strong>=</strong>&#39;rating&#39;, ascending<strong>=False</strong>)<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*btgBP9H6DTu21pqzTSo9nA.png" /><figcaption>Most rated movies</figcaption></figure><p>By looking at the most rated movies, it might happen only a few users have given the rating for movies. So, let&#39;s look at rating counts it means how many users have given ratings for particular movies.</p><pre><em># Lets see the count of each rating given by users</em><br>df<strong>.</strong>groupby(&#39;title&#39;)[&#39;rating&#39;]<strong>.</strong>count()<strong>.</strong>sort_values(ascending<strong>=False</strong>)<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*ncSEmAUCD6_6PWwV0-m7Dg.png" /><figcaption>No of the users watched movies</figcaption></figure><p>Here we can clearly, see that movie <strong>“Star Wars”</strong> has the most-watched movies from this dataset.</p><h4>Let’s create a rating data frame with average rating and number of ratings:</h4><pre># Averge rating <br>ratings<strong>=</strong> pd<strong>.</strong>DataFrame(df<strong>.</strong>groupby(&#39;title&#39;)[&#39;rating&#39;]<strong>.</strong>mean())<br>ratings<strong>.</strong>head()</pre><pre># Rating counts<br>ratings[&#39;rating_counts&#39;]<strong>=</strong> pd<strong>.</strong>DataFrame(df<strong>.</strong>groupby(&#39;title&#39;)[&#39;rating&#39;]<strong>.</strong>count())<br>ratings<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*qK4gC9mAKWGU7Gz9WTIx1w.png" /><figcaption>Avg_Rating and userid_count data</figcaption></figure><p>By looking at the above table we could conclude that number of rating(userid_count) of some of the movies are given very little. If one person has watched those movies and given a rating ‘5’, so, that wouldn&#39;t count it as popular movies. Therefore, we are going to take at least 100 times of different users who watched that particular movie.</p><h4>Let&#39;s visualize the rating given by users:</h4><pre><em># Lets look at the rating </em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(10,5))<br>sns<strong>.</strong>histplot(ratings[&#39;rating&#39;])<br>plt<strong>.</strong>title(&quot;Histogram plot of Rating&quot;)<br>plt<strong>.</strong>xlabel(&#39;ratng&#39;)<br>plt<strong>.</strong>ylabel(&#39;count of rating&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*1cT3U6ObwKsxvnXVsBN6uw.png" /><figcaption>Rating graph</figcaption></figure><p>By looking at the graph we say that there are some outliers, but the graph roughly follows the normal distribution curve. And most user has given a rating of movies between 3 to 4.</p><h4>Let&#39;s visualize the rating vs counts:</h4><pre>sns<strong>.</strong>jointplot(x<strong>=</strong>&#39;rating&#39;,y<strong>=</strong>&#39;rating_counts&#39;,data<strong>=</strong>ratings,alpha<strong>=</strong>0.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*cvFMwk4s2d5QV5NVsaV4rg.png" /><figcaption>Scatter plot rating vs counts</figcaption></figure><h3>Recommending Similar Movies</h3><p>Now let’s create a matrix that has the user ids on one access and the movie title on another axis. Each cell will then consist of the rating the user gave to that movie. Note there will be a lot of NaN values because most people have not seen most of the movies.</p><pre>movies_reco<strong>=</strong> df<strong>.</strong>pivot_table(index<strong>=</strong>&#39;user_id&#39;, columns<strong>=</strong>&#39;title&#39;,values<strong>=</strong>&#39;rating&#39;)<br>movies_reco<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZOgSLTbkvvSTpieBtYSqQ.png" /><figcaption>Pivot table</figcaption></figure><p>Let&#39;s find the Similar movies of “<strong>Star Wars (1977)</strong>”</p><pre>starwars_user_ratings <strong>=</strong> movies_reco[&#39;Star Wars (1977)&#39;]<br></pre><h3>We can then use corrwith() method to get correlations between two pandas series:</h3><ul><li>Correlation also measures the relationship between two variables as well as its magnitude defines the strength between variables. It ranges from -1 to 1.</li><li>We will consider popular movies only if when more than 100 users watched that particular movie.</li><li>We will also drop the missing values from the data</li><li>We will also see the number of ratings as well as average ratings given by users</li></ul><p><strong><em>Here we are going to find the movies more similar to “Star Wars (1977)” with the help of correlation. Higher the correlation more similarity between them.</em></strong></p><pre># Finding the similar movies from pivot_table<br>similar_starwars<strong>=</strong> movies_reco<strong>.</strong>corrwith(starwars_user_ratings)</pre><pre># Making data frame with columns correlation<br>corr_starwars <strong>=</strong> pd<strong>.</strong>DataFrame(similar_starwars,columns<strong>=</strong>[&#39;Correlation&#39;])</pre><pre># Droping the nan values <br>corr_starwars<strong>.</strong>dropna(inplace<strong>=True</strong>)</pre><pre>#combining the no of users watched that movies<br>corr_starwars<strong>=</strong> corr_starwars<strong>.</strong>join(ratings[&#39;rating_counts&#39;])</pre><pre># Cosidering more than 100 users watched that movies<br>corr_starwars[corr_starwars[&#39;rating_counts&#39;]<strong>&gt;</strong>100]<strong>.</strong>sort_values(by<strong>=</strong>&#39;Correlation&#39;,ascending<strong>=False</strong>)<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*ePExK-_mBl44KuZG8xtzyg.png" /><figcaption>Similar movies to “star wars 1977”</figcaption></figure><h3>Method 2: Cosine similarity</h3><ul><li>The similarity is the cosine of the angle between the 2 vectors of the item vectors of A and B</li><li>The closer the vectors, the smaller will be the angle and the larger the cosine</li><li>Cosine Similarity will be used to determine the degree of similarity between the two movies. What is cosine similarity and how does it work?</li></ul><p><strong><em>Assume we have two vectors. If the vectors are almost parallel, i.e. the angle between them is zero, we can conclude that they are “similar,” because cos(0)=1. If the vectors are orthogonal, we can say they are independent or NOT “similar,” because cos(90)=0.</em></strong></p><h4>Let&#39;s create the pivot table:</h4><ul><li>Here we are creating a pivot table, keeping movies as index and users as columns, and filling nan values with 0.</li></ul><pre><em># Lets create a pivot table</em><br>movies_df<strong>=</strong> df<strong>.</strong>pivot_table(index<strong>=</strong>&quot;title&quot;,columns<strong>=</strong>&#39;user_id&#39;,values<strong>=</strong>&#39;rating&#39;)<strong>.</strong>fillna(0)<br>movies_df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5OAEhUBmisDMiazyxSf5g.png" /><figcaption>Pivot table</figcaption></figure><pre><strong>from</strong> scipy.sparse <strong>import</strong> csr_matrix<br><br><em># Now converting into metrix</em><br>movies_df_metrix<strong>=</strong> csr_matrix(movies_df<strong>.</strong>values)</pre><p><strong><em>KNN calculates the distance from all points in the proximity of the unknown data and filters out the ones with the shortest distances to it. As a result, it’s often referred to as a distance-based algorithm.</em></strong></p><pre><em># Here we are going to cosine simalirity </em><br><strong>from</strong> sklearn.neighbors <strong>import</strong> NearestNeighbors<br><br><em># Building the model</em><br>model_knn<strong>=</strong> NearestNeighbors(metric<strong>=</strong> &#39;cosine&#39;, algorithm<strong>=</strong>&#39;brute&#39;)<br><br><em># Fitting the model </em><br>model_knn<strong>.</strong>fit(movies_df_metrix)</pre><p><strong><em>Now we will select the random movies from the pivot table:</em></strong></p><pre><em># Shape[0]---&gt; selecting from rows</em><br>select_random_movies<strong>=</strong> np<strong>.</strong>random<strong>.</strong>choice(movies_df<strong>.</strong>shape[0])<br>select_random_movies</pre><pre><em># Now we will try to find the movies related to select_random_movies</em><br>distances, indices <strong>=</strong> model_knn<strong>.</strong>kneighbors(movies_df<strong>.</strong>iloc[select_random_movies,:]<strong>.</strong>values<strong>.</strong>reshape(1,<strong>-</strong>1), n_neighbors<strong>=</strong> 6)</pre><p><strong><em>Now let&#39;s print similar movies to “select_random_movies”.</em></strong></p><pre><em>#Here 0---&gt; recomendation for same movies</em><br><br><strong>for</strong> i <strong>in</strong> range(0, len(distances<strong>.</strong>flatten())):<br>    <strong>if</strong> i <strong>==</strong> 0:<br>        print(&#39;Recommendations for {0}:\n&#39;<strong>.</strong>format(movies_df<strong>.</strong>index[select_random_movies])) <em># For which movies it selected</em><br>    <strong>else</strong>:<br>        print(&#39;{0}: {1}, with distance of {2}:&#39;<strong>.</strong>format(i, movies_df<strong>.</strong>index[indices<strong>.</strong>flatten()[i]], distances<strong>.</strong>flatten()[i]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Nm7D7CI6IkClyR5BbcZ_g.png" /><figcaption>Similar movies “Hour of the Pig, The (1993)”</figcaption></figure><p>Here we have used cosine similarity to find similar movies to recommend to the users. Therefore, nearest neighbors are those data points that have minimum distance in feature space from our new data point.</p><h4>Conclusion:</h4><p>We talked through the process of creating a basic recommendation engine in Python using Correlation and cosine similarity in this article. We began by learning the principles of recommendation authoring. Then, for the sake of experimentation, we loaded the MovieLens 100K data set.</p><p>Having followed that, we created a simple popularity model in which the most popular movies for each user were recommended by using correlation and also used cosine similarity to find similar movies.</p><h4><strong>Code Link:</strong></h4><p><a href="https://github.com/rahkum96/Movie-Recommendation-System/blob/main/Movies%20Recommender%20Systems%20with%20Python.ipynb">Movie-Recommendation-System/Movies Recommender Systems with Python.ipynb at main · rahkum96/Movie-Recommendation-System</a></p><h4>References:</h4><ul><li><a href="https://www.analyticsvidhya.com/blog/2020/11/create-your-own-movie-movie-recommendation-system/">Build A Movie Recommendation System on Your Own</a></li><li><a href="https://www.analyticsvidhya.com/blog/2016/06/quick-guide-build-recommendation-engine-python/">Building Recommendation Engine In Python | R</a></li></ul><h4><strong>Follow me on:</strong></h4><p>LinkedIn:</p><p><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></p><p>GitHub:</p><p><a href="https://github.com/rahkum96">rahkum96 - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8113226c0aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fake News Detection Using NLP Techniques in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/fake-news-detection-with-nlp-5758f6ca2360?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/5758f6ca2360</guid>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fake-news]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 09:16:03 GMT</pubDate>
            <atom:updated>2025-01-20T19:01:08.972Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By using machine learning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*N2U_G2b4d40OEUdR.gif" /><figcaption>Source: Google</figcaption></figure><h3>Introduction:</h3><p>The definition of fake news is information that pushes people down the wrong road. Fake news is spreading like wildfire these days, and people are sharing it without confirming it. The main goal of viewing or reading the news was to stay updated about what was going on in the world. In the modern era, there are various social media platforms, such as Facebook, Twitter, Reddit, and others, which millions of people rely on to keep up with daily events.</p><h3><strong>Pipeline:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*zMDehGA2f5rv1PZ7.png" /><figcaption>Source:<a href="https://towardsdatascience.com/a-practitioners-guide-to-natural-language-processing-part-i-processing-understanding-text-9f4abfd13e72?gi=ea8456a70bde"><strong>towardsdatascience</strong></a></figcaption></figure><p>This pipeline created numerical features and sent them into a machine learning algorithm, as shown in the picture above. In this project, we’ll be using NLTK, re (Regular Expression), and Scikit Learn, among other machine learning and natural language processing packages.</p><h3><strong>Dataset:</strong></h3><p>Many datasets for detecting fake news can be found on Kaggle or other places. These datasets were obtained through Kaggle. Id, Title, Author, Text, and Label are the attributes of the data (where 1 is unreliable and 0 is reliable).</p><h3>Libraries:</h3><pre><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> seaborn <strong>as</strong> sns</pre><pre><em># We will clean the text by using these library:</em><br><strong>import</strong> re   <em># regular expression</em><br><strong>from</strong> nltk.corpus <strong>import</strong> stopwords <em># for removing stopwords from sentences</em><br><strong>from</strong> nltk.stem.porter <strong>import</strong> PorterStemmer  <em>#for stemning-- it will not make sentences into proper meaningful sentences </em><br><strong>from</strong> nltk.stem <strong>import</strong> WordNetLemmatizer   <em># for lemmatization- to make sentence in proper meaning</em></pre><p><strong><em>Here We are going to store data in a Data frame called df. And we will see the first 5 rows of data.</em></strong></p><pre>df<strong>=</strong> pd<strong>.</strong>read_csv(&#39;train.csv&#39;)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4ZvpzsCTtyBHtaMSlG-Fg.png" /><figcaption>Data</figcaption></figure><h3><strong>Let&#39;s Quickly Explore the data:</strong></h3><ol><li>Missing values check:</li><li>Checking data is balanced or not?</li><li>Shape of data</li></ol><pre><em>#checking for missing values</em><br>df<strong>.</strong>isnull()<strong>.</strong>sum()</pre><pre>df[&#39;label&#39;].value_counts()</pre><pre># Shape of data<br>df<strong>.</strong>shape</pre><p>There are no missing values in this dataset; otherwise, we will have to eliminate that information or impute a value.</p><p>Because both groups have roughly the same number of samples, our final dataset is balanced.</p><h3><strong>Creating Independent and dependent variables:</strong></h3><p>We’ll use the “Id,” “Title,” and “Author” columns as independent features and the “Label” column as a dependent feature in this classifier model.</p><pre><em>#Crteaing independent and dependent features<br>independent<br></em>X<strong>=</strong>df<strong>.</strong>iloc[:,:4]</pre><pre>#Dependent variable <br>y<strong>=</strong>df<strong>.</strong>iloc[:,<strong>-</strong>1]</pre><h3><strong>Let&#39;s make a copy of data:</strong></h3><pre><em># Now we’ll create a copy of this dataset and also reset its index values.</em><br>news<strong>=</strong>df<strong>.</strong>copy()<br>news<strong>.</strong>reset_index(inplace<strong>=True</strong>)<br>news<strong>.</strong>head(10)</pre><h3>Text cleaning and preprocessing:</h3><p>You and I would have understood that sentence in a fraction of a second. But machines simply cannot process text data in raw form. They need us to break down the text into a numerical format that’s easily readable by the machine (the idea behind Natural Language Processing!).</p><p>BoW/TF-IDF is used to convert text into a numeric vector</p><ul><li>Step1: preprocess and remove [,./?} ] these full stop</li><li>step2: Lower the text</li><li>step3: create lemmatization/stemming</li><li>step4: remove stopwords from text</li><li>step5: Creating the TF-IDF model</li></ul><pre>ps<strong>=</strong>PorterStemmer()# Initilizing the port stemmer</pre><blockquote><em>This part of the code is for Stopword removal and Stemming. Here, the corpus is an array in which we have appended all the </em><strong><em>titles</em></strong><em> of the news</em><strong><em>.</em></strong></blockquote><pre>corpus<strong>=</strong>[]<br><strong>for</strong> i <strong>in</strong> range(len(news)):<br>    review<strong>=</strong> re<strong>.</strong>sub(&#39;[^a-zAZ]&#39;,&#39; &#39;,news[&#39;title&#39;][i])<br>    review<strong>=</strong> review<strong>.</strong>lower()<br>    review<strong>=</strong> review<strong>.</strong>split()<br>    review<strong>=</strong> [ps<strong>.</strong>stem(word) <strong>for</strong> word <strong>in</strong> review <strong>if</strong> word <strong>not</strong> <strong>in</strong> set(stopwords<strong>.</strong>words(&#39;english&#39;))]<br>    review<strong>=</strong> &#39; &#39;<strong>.</strong>join(review)<br>    corpus<strong>.</strong>append(review)</pre><blockquote><strong>Lemmatization:</strong></blockquote><ul><li>Convert the word into meaning full word, but this would take more time than stemming</li></ul><p>Example: <br>Stay, Stays, Staying, Stayed — -&gt; Stay</p><p>House, Houses, Housing — -&gt; House</p><blockquote><strong>Stemming:</strong></blockquote><ul><li>process of reducing inflected words to their word stem but, not in meaningful word</li></ul><p>Example:</p><p>Final, Finally, Finalized — → Fina</p><blockquote><strong>Stop words</strong></blockquote><p>Are those that appear frequently yet aren’t regarded informative.<br>[‘the’, ‘a’, ‘an’, ‘and’, ‘but’, ‘for’, ‘on’, ‘in’, ‘at’]</p><h3>Text to Features (Feature Engineering on text data):</h3><h4>Model of the Bag of Words (BoW)</h4><p>The Bag of Words (BoW) model is the most basic type of numerical text representation. A phrase can be represented as a bag of words vector, just like the term itself (a string of numbers).</p><pre><em>#Applying count vectorizer (also known as the “Bag of Words”). Maximum features passed here are 5000.</em><br><strong>from</strong> sklearn.feature_extraction.text <strong>import</strong> CountVectorizer<br>cv<strong>=</strong>CountVectorizer(max_features<strong>=</strong>5000,ngram_range<strong>=</strong>(1, 3))<br>X<strong>=</strong>cv<strong>.</strong>fit_transform(corpus)<strong>.</strong>toarray()</pre><h4><em>N-Grams as Characteristics</em></h4><p><em>N-Grams are a collection of N-words put together. When compared to words (Unigrams), N-grams (N &gt; 1) are often more informative. Furthermore, bigrams (N = 2) are regarded as the most important of all the others. The code below creates a bigram of text.</em></p><h3><strong><em>Split the Data:</em></strong></h3><blockquote>The most important stage in machine learning is splitting the data. We use the trainset to train our model and the testing set to test our data. Using Scikit learns train_test_split function, we split our data into train and test.</blockquote><pre><em>#Dataset is now split into train and test. </em><br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br>X_train,X_test,y_train,y_test<strong>=</strong>train_test_split(X,y,test_size<strong>=</strong>0.2,random_state<strong>=</strong>0)</pre><h4>Preparing data for model building:</h4><pre><em>#The array is converted into dataframe.</em><br>df_news<strong>=</strong>pd<strong>.</strong>DataFrame(X_train,columns<strong>=</strong>cv<strong>.</strong>get_feature_names())<br>df_news<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1DMc_X8MiriqwMoEWGVpQ.png" /><figcaption>Final text converted into a numeric data frame.</figcaption></figure><h3><strong>Building Model:</strong></h3><h4>Naive Bayes Multinomial:</h4><p>When it’s in discrete form, it’s useful for classification. It comes in handy when working with text. Each text will be turned into a word count vector. It can deal with negative numbers.</p><p>It’s pre-programmed in the Scikit Learn Library. We can then import that class into our project and build a Multinomial Naive Bayes Class object.</p><ol><li>Use our vectorized train data to train the classifier.</li><li>Once the classifier has been fitted to the training set, we may use the predict technique to forecast the test set outcome.</li></ol><pre><em># Building the model</em><br><strong>from</strong> sklearn.naive_bayes <strong>import</strong> MultinomialNB<br>nb<strong>=</strong> MultinomialNB()<br>nb<strong>.</strong>fit(X_train,y_train)</pre><pre><em>#predicting </em><br>y_pred<strong>=</strong>nb<strong>.</strong>predict(X_test)</pre><h4><strong>Classification Metrics</strong></h4><p>To see how well our model works, we utilize several metrics to see how accurate it is. In Scikit-learn, there are a variety of categorization metrics to choose from.</p><p>Precision, Recall, F1-Score, Confusion Matrix, Accuracy Score</p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> confusion_matrix,accuracy_score,classification_report<br>cm<strong>=</strong> confusion_matrix(y_test,y_pred)<br>print(cm)<br>accuracy<strong>=</strong> accuracy_score(y_test,y_pred)<br>print(accuracy)<br>report<strong>=</strong> classification_report(y_test,y_pred)<br>print(report)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*jSEWAUkmGlsVfyxI-toGLg.png" /><figcaption>Classification Report</figcaption></figure><p>As you can see, our Precision, Recall, and F1 Score are all excellent. As a result, we can confidently state that our model performs admirably on unobserved data. The accuracy score on the Test Dataset is 90%, which is excellent.</p><h3><strong>Conclusion:</strong></h3><p>We learned how to use Python to detect bogus news today. We used a Fake and True News dataset to fit our model, which included a Text cleaning function, TfidfVectorizer, and an initialized Multinomial Naive Bayes Classifier. We were able to get a magnitude accuracy of 90 percent.<br>I hope you had a good time working on this project.</p><h4>References:</h4><ul><li><a href="https://medium.com/swlh/fake-news-detection-using-machine-learning-69ff9050351f">Fake News Detection Using Machine Learning</a></li><li><a href="https://medium.com/swlh/fake-news-detection-using-machine-learning-69ff9050351f">Fake News Detection Using Machine Learning</a></li><li><a href="https://www.analyticsvidhya.com/blog/2021/06/build-your-own-fake-news-classifier-with-nlp/">Fake News Classifier | Build Your Own Fake News Classifier With NLP</a></li></ul><blockquote><strong>Code:</strong></blockquote><p><a href="https://github.com/rahkum96/Fake-News-Classifier-With-NLP/blob/main/Fake%20News%20Classifier_ML.ipynb">Fake-News-Classifier-With-NLP/Fake News Classifier_ML.ipynb at main · rahkum96/Fake-News-Classifier-With-NLP</a></p><blockquote><strong>Social Media Link:</strong></blockquote><h4>GitHub:</h4><p><a href="https://github.com/rahkum96">rahkum96 - Overview</a></p><h4>LinkedIn:</h4><p><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5758f6ca2360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Predict Apple Stock Price]]></title>
            <link>https://python.plainenglish.io/predicting-apple-stock-price-36f329cda530?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f329cda530</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 17:30:34 GMT</pubDate>
            <atom:updated>2025-01-20T18:59:32.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>Forecasting Apple Stock Prices Using an LSTM Model</h3><p>By using LSTM Model and TensorFlow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1uN1cEHj4BgEguVe" /><figcaption>Image source <a href="https://9to5mac.com/2020/07/30/apple-announces-4-to-1-stock-split-as-shares-cross-400-following-record-q3-earnings/">here</a></figcaption></figure><p>We’ll use TensorFlow to build an LSTM model to forecast Apple stock prices in this post!</p><p>Predicting stock prices is a fascinating field in Machine Learning. Personally, the applications of this topic have always piqued my curiosity.</p><p>Over the last few years, Machine Learning has proven to be quite beneficial in stock market forecasting, and many investing firms now utilize it to make stock market choices.</p><p><em>Note:</em></p><p><em>This (model) sole purpose is to examine and demonstrate how Machine Learning Models perform in the stock market; it is not intended to provide investment advice! The stock market is volatile, and it is not recommended for novices without prior knowledge!</em></p><h3><strong>About Time-Series Forecasting:</strong></h3><p>Traditionally, most machine learning (ML) models have used some observations (samples/examples) as input features, but the data has no time dimension.</p><p>Models capable of predicting future values based on previously observed values are known as time-series forecasting models. For non-stationary data, time-series forecasting is widely used. Non-stationary data are those whose statistical features, such as mean and standard deviation, do not remain constant throughout time but instead change.</p><p>The non-stationary input data used as input to these models is typically called time-series. Temperature values over time, stock prices over time, and the price of a property over time are all instances of time series. As a result, the input is a signal (time-series) characterized by observations recorded in a specific order throughout time.</p><h3><strong>LSTM Model:</strong></h3><ul><li>Long short-term memory (LSTM) is an artificial recurrent neural network (RNN) architecture used in the field of deep learning</li><li>LSTM Models, in a nutshell, can store data throughout time. When working with Time Series or Sequential Data, this is handy.</li><li>The Human Brain is remarkably similar to LSTM Models. When you hear someone speak to you.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*1XrLJdfum88u2Whs.jpg" /><figcaption>Source <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.researchgate.net%2Ffigure%2FStructure-of-the-LSTM-cell-and-equations-that-describe-the-gates-of-an-LSTM-cell_fig5_329362532&amp;psig=AOvVaw0Do5ORi7-ZJs1WJw1YyWZG&amp;ust=1590437056825000&amp;source=images&amp;cd=vfe&amp;ved=0CAIQjRxqFwoTCLjC0PClzekCFQAAAAAdAAAAABAI">here</a></figcaption></figure><p>Essentially, this method performs the magic of forgetting, updating, and storing data.</p><p>This is a good read if you want to learn more about LSTMs <a href="https://machinelearningmastery.com/gentle-introduction-long-short-term-memory-networks-experts/">https://machinelearningmastery.com/gentle-introduction-long-short-term-memory-networks-experts/</a></p><h3><strong>Let’s get started with coding!</strong></h3><h3><strong>Data:</strong></h3><p>I have extracted or read the data from yahoo by using pandas_datareader and stored it in a variable “APPL_data”.</p><p><em>Modules needed: Keras, Tensorflow, Pandas, Scikit-Learn &amp; Numpy</em></p><pre><strong>import</strong> pandas_datareader <strong>as</strong> web <em># to read data from web</em><br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np</pre><pre><em># import the data</em><br>APPL_data<strong>=</strong> web<strong>.</strong>DataReader(&#39;AAPL&#39;,data_source<strong>=</strong>&quot;yahoo&quot;,start<strong>=</strong>&#39;2015-01-01&#39;,end<strong>=</strong>&#39;2021-09-30&#39;)<br>APPL_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*mj2SYLQxtH870DsTi5Ol_Q.png" /><figcaption>Head of data</figcaption></figure><h3><strong>Let&#39;s plot the closing price of data:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo_eu12oE4BZMR9uQfAV6g.png" /><figcaption>Closing price in USD</figcaption></figure><h3><strong>Data preprocessing:</strong></h3><p>Here we are going to split the data, Since the data is time series, we will take the first 90% of data as training and the last 10% as test data.</p><p>We’d want to use the ‘Open’ column in our Model so that we may use <strong>“iloc”</strong> to get values for him.</p><pre><em># Split into train and test:</em><br>data_to_train <strong>=</strong> APPL_data[:1530]<br>data_to_test <strong>=</strong> APPL_data[1530:]</pre><pre>aapl_data<strong>=</strong> APPL_data<strong>.</strong>iloc[: , 3:4]<br>aapl_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*UrAmfW2A3znVfd8qgXDbHQ.png" /><figcaption>Closing price data</figcaption></figure><h3><strong>Creating training data:</strong></h3><pre><em>## We want to create a numpy arrary not a vector </em><br>trainig_set<strong>=</strong> aapl_data<strong>.</strong>iloc[:1530,:]<strong>.</strong>values</pre><h3><strong>Test data:</strong></h3><pre>test_set<strong>=</strong> aapl_data<strong>.</strong>iloc[1530:,:]<strong>.</strong>values</pre><p><strong><em>Before training a model, it’s a good idea to normalize the data. This will improve the results. To scale the values, we can use sklearn!</em></strong></p><pre><em># Feature scalling, Here we will do normalizatioin </em><br><strong>from</strong> sklearn.preprocessing <strong>import</strong> MinMaxScaler<br>sc<strong>=</strong> MinMaxScaler(feature_range<strong>=</strong>(0,1))<br>trainig_set_scaled<strong>=</strong> sc<strong>.</strong>fit_transform(trainig_set)</pre><h3><strong>Building the input features:</strong></h3><p>I utilized the model outlined above to forecast the closing price of AAPL stock for the following trading day using data from the previous sixty trading days as an example for this post.</p><pre><em># Create a data structure with 60 timesteps and 1 output</em><br>X_train<strong>=</strong>[] <em>#Independent variables</em><br>y_train<strong>=</strong> [] <em># Dependent variables </em><br><em># I am going to append past 60 days data </em><br><strong>for</strong> i <strong>in</strong> range(60,1530):<br>    X_train<strong>.</strong>append(trainig_set_scaled[i<strong>-</strong>60:i,0]) <em># Appending prevois 60 days data not including 60</em><br>    y_train<strong>.</strong>append(trainig_set_scaled[i,0])<br>    <br>X_train, y_train<strong>=</strong> np<strong>.</strong>array(X_train), np<strong>.</strong>array(y_train)</pre><h3><strong>Let&#39;s check the shape of the data:</strong></h3><ul><li>We know that the LSTM model takes 3 arguments as (#values, #time-steps, #1-dimensional output).</li></ul><pre><em># lETS CHECK THE SHAPE OF X_train and y_train</em><br>X_train<strong>.</strong>shape, y_train<strong>.</strong>shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*xORxWnM_GS8n5H1QIxcWfQ.png" /><figcaption>Shape of data</figcaption></figure><p>We have now <strong>reshaped</strong> the data into the following format (#values, #time-steps, #1-dimensional output).</p><pre><em># LSMT Model needs to be 3- dimensional, so need to rehsape the x_train, y_train</em><br><em># Reshaping</em><br><em>#numpy.reshape(array, shape, order = &#39;C&#39;)</em><br>X_train<strong>=</strong> np<strong>.</strong>reshape(X_train,(X_train<strong>.</strong>shape[0],X_train<strong>.</strong>shape[1],1))<br>X_train<strong>.</strong>shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*TfeTjK-KKxFP_7uePpdtsQ.png" /><figcaption>Reshaped data</figcaption></figure><h3><strong>Build The LSTM Model:</strong></h3><ul><li>Now it’s time to put the model together. We’ll use 100 neurons and 5 hidden layers to create the LSTM.</li><li>Finally, in the output layer, we will assign 1 neuron to predict the normalized stock price.</li><li>The MSE loss function and Adam stochastic gradient descent optimizer will be used.</li></ul><pre><em># Importing the Keras libraries and packages</em><br><strong>import</strong> tensorflow <strong>as</strong> tf<br><strong>from</strong> tensorflow.keras.models <strong>import</strong> Sequential<br><strong>from</strong> tensorflow.keras.layers <strong>import</strong> Dense, Dropout, LSTM<br><br><em>#  Initialising the RNN</em><br>model<strong>=</strong> Sequential()<br><br><em># Adding first LSTM layer and some dropout Dropout regularisation</em><br>model<strong>.</strong>add(LSTM(units<strong>=</strong>100,return_sequences<strong>=True</strong>, input_shape<strong>=</strong>(X_train<strong>.</strong>shape[1],1)))<br>model<strong>.</strong>add(Dropout(rate<strong>=</strong>0.2))<br><br><em># Adding second LSTM layer and some dropout Dropout regularisation</em><br>model<strong>.</strong>add(LSTM(units<strong>=</strong>100,return_sequences<strong>=True</strong>))<br>model<strong>.</strong>add(Dropout(rate<strong>=</strong>0.2))<br><br><em># Adding third LSTM layer and some dropout Dropout regularisation</em><br>model<strong>.</strong>add(LSTM(units<strong>=</strong>100,return_sequences<strong>=True</strong>))<br>model<strong>.</strong>add(Dropout(rate<strong>=</strong>0.2))<br><br><em># Adding fourth LSTM layer and some dropout Dropout regularisation</em><br>model<strong>.</strong>add(LSTM(units<strong>=</strong>100,return_sequences<strong>=True</strong>))<br>model<strong>.</strong>add(Dropout(rate<strong>=</strong>0.2))<br><br><em># Adding fifth LSTM layer and some dropout Dropout regularisation</em><br>model<strong>.</strong>add(LSTM(units<strong>=</strong>100))<br>model<strong>.</strong>add(Dropout(rate<strong>=</strong>0.2))<br><br><em># Adding the Output Layer</em><br>model<strong>.</strong>add(Dense(units<strong>=</strong>1))<br><br><em># Compiling the Model</em><br><em># Because we&#39;re doing regression hence mean_squared_error</em><br>model<strong>.</strong>compile(loss<strong>=</strong>&#39;mean_squared_error&#39;, optimizer<strong>=</strong>&#39;adam&#39;)</pre><p>Dropout layers are used to avoid Overfitting issues, and the option <strong><em>“return sequences” </em></strong>is used to decide if the layer will return a sequence compatible with an LSTM. When we have an LSTM layer after, we utilize<strong><em> “return sequences=True”!</em></strong></p><pre>model<strong>.</strong>summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*bMATDWjWCxZ-sPMvrQd3ow.png" /><figcaption>Model architecture.</figcaption></figure><h3><strong>Fitting The model:</strong></h3><pre><em># Fitting the model to the Training set</em><br>history<strong>=</strong>model<strong>.</strong>fit(X_train,y_train,epochs<strong>=</strong>100,batch_size<strong>=</strong>32)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*5kFPn_snVZE_xDeoOjFUrw.png" /><figcaption>Model training</figcaption></figure><p>We may plot the Loss after we’ve trained our model to see how good it was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yl9F0LfUK6du8_0OsnE91g.png" /><figcaption>Loss graph</figcaption></figure><h3>Getting ready for Predictions:</h3><p>To create predictions, we’ll use our Test Dataset and prepare him the same way we did with the Train Dataset.</p><pre><em># Hence we will concatenate the dataset and then scale them</em><br>data_total<strong>=</strong> pd<strong>.</strong>concat([train_data[&#39;Close&#39;], test_data[&#39;Close&#39;]],  axis<strong>=</strong>0)<br>inputs<strong>=</strong> data_total[len(data_total)<strong>-</strong>len(test_data)<strong>-</strong>60:]<strong>.</strong>values <br>inputs <strong>=</strong> inputs<strong>.</strong>reshape(<strong>-</strong>1,1) <br>inputs <strong>=</strong> sc<strong>.</strong>transform(inputs)<br><br>X_test <strong>=</strong> []<br><strong>for</strong> i <strong>in</strong> range(60, 230):<br>    X_test<strong>.</strong>append(inputs[i<strong>-</strong>60:i, 0])<br><br>X_test <strong>=</strong> np<strong>.</strong>array(X_test)<br><em># 3D format</em><br>X_test <strong>=</strong> np<strong>.</strong>reshape(X_test, (X_test<strong>.</strong>shape[0], X_test<strong>.</strong>shape[1], 1))</pre><p>After formatting the Test Data, we can make predictions in our X_test.</p><pre><em>#preict the model</em><br>predicted_stock_price <strong>=</strong> model<strong>.</strong>predict(X_test)</pre><p>However, before plotting our predictions, we must first apply an inverse transform() to the predictions array, because we use the Scale to generate predictions, and hence our predictions are between 0 and 1.</p><pre><em># Inverse the scaling</em><br>predicted_stock_price <strong>=</strong> sc<strong>.</strong>inverse_transform(predicted_stock_price)</pre><p>Now it’s time to plot our forecasts against actual stock prices to assess how well our model performed.</p><pre><em># Visualising the results</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(15,8))<br>plt<strong>.</strong>plot(real_stock_price, color<strong>=</strong>&#39;Red&#39;, label<strong>=</strong>&#39;Real Apple Stock Price&#39;)<br>plt<strong>.</strong>plot(predicted_stock_price, color<strong>=</strong>&#39;Blue&#39;, label<strong>=</strong>&#39;Predicted Apple Stock Price&#39;)<br>plt<strong>.</strong>title(&#39;Apple Stock Price Prediction&#39;,fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;Time&#39;, fontsize<strong>=</strong>15)<br>plt<strong>.</strong>ylabel(&#39;Apple Stock Price&#39;,fontsize<strong>=</strong>15)<br>plt<strong>.</strong>legend()<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HuQQiArhaKY9ap-ERmO9A.png" /><figcaption>Graph of predicted price</figcaption></figure><h3><strong>Conclusion:</strong></h3><p>Our model performed admirably, as can be seen. It can accurately follow most unusual jumps/drops; however, we can observe that the model expected (predicted) lower values than the actual stock price for the most recent date stamps.</p><p><strong>You can find the code </strong><a href="https://github.com/rahkum96/Predicting-Apple-Stock-Price-Using-An-LSTM/blob/main/Apple%20stock%20forecasting.ipynb"><strong>here</strong></a></p><p><strong><em>My Social Links:</em></strong></p><ul><li><a href="https://github.com/rahkum96">rahkum96 - Overview</a></li><li><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f329cda530" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/predicting-apple-stock-price-36f329cda530">How to Predict Apple Stock Price</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Churn Prediction Using an Artificial Neural Network (ANN) in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/churn-modelling-fe64c2b9fd83?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe64c2b9fd83</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 09:31:04 GMT</pubDate>
            <atom:updated>2025-01-20T18:49:52.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Neural Network(Classification) in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nUOLTeS4o2ixzzCE.jpg" /><figcaption>Image source <a href="https://www.predicagroup.com/blog/customer-churn-analysis/">here</a></figcaption></figure><h3><strong>What is Artificial Neural Network?</strong></h3><p>Artificial Neural Networks (ANN) are multi-layer fully connected neural nets that resemble the diagram below. An input layer, numerous hidden layers, and an output layer make up these layers. Each node in one layer is connected to the nodes in the next layer. By increasing the number of hidden layers, we can make the network deeper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7BOchMmjKy0vbsal.png" /><figcaption>Image Source <a href="https://commons.wikimedia.org/wiki/File:Neural_network.svg">here</a></figcaption></figure><ul><li>The input units are passed in the first stage. i.e. data is transmitted to the hidden layer with some weights attached. We can have as many hidden layers as we choose. The inputs x1,x2,x3,….xn</li><li>Neurons make up each hidden layer. Each neuron receives all of the inputs.</li><li>All calculation is done in the hidden layer after the inputs are passed on.</li></ul><h3><strong>Problem Statements :</strong></h3><p>We’re working with a dataset from the finance industry. We have a dataset with a total of 14 dimensions and 100000 records in it.</p><p>Our major goal is to construct an artificial neural network that takes into account all independent variables (the first 13) and predicts whether or not our customer will leave the bank (Exited is the dependent variable here).</p><h3><strong>Importing the Libraries Required for an Artificial Neural Network:</strong></h3><p>Let’s get started by importing all of the essential libraries.</p><pre>#Importing necessary Libraries<br>import numpy as np<br>import pandas as pd<br>import tensorflow as tf</pre><pre><strong>import</strong> keras<br><strong>from</strong> keras.models <strong>import</strong> Sequential  <em># for all deep learning neural network</em><br><strong>from</strong> keras.layers <strong>import</strong> Dense <em>#for hidden layer </em><br><strong>from</strong> keras.layers <strong>import</strong> LeakyReLU,PReLU,ELU <em># for Activation function </em><br><strong>from</strong> keras. layers <strong>import</strong> Dropout  <em># to avoid overfittin---&gt; if neural network is too deep we usually used this</em></pre><h3>Importing Dataset:</h3><p>We’re going to import our dataset at this stage. Because our dataset is in CSV format, we’ll import it with pandas’ read_CSV() method.</p><pre><em>#Import data set</em><br>dataset<strong>=</strong> pd<strong>.</strong>read_csv(&#39;Churn_Modelling.csv&#39;)<br>dataset<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePsgTWqBzy_yDEkN4n75Pw.png" /><figcaption>First 5rows of data</figcaption></figure><h3><strong>Creating Independent and dependent features:</strong></h3><pre>X<strong>=</strong> dataset<strong>.</strong>iloc[:,3:-1]<br>y<strong>=</strong>dataset<strong>.</strong>iloc[:,-1]<br>X<strong>.</strong>head()</pre><p><em>I’ve utilized the </em><strong><em>“iloc”</em></strong><em> method of the Pandas data frame to get the values we want from the desired column within the dataset. As can be seen, we are retrieving data from the third column to the last, minus one column. The reason for this is that the first three columns, RowNumber, CustomerId, and Surname, have no bearing on whether or not the client would quit. As a result, we started fetching values from the third column forward in this situation. Finally, because our last column is a dependent variable, we used -1 in the iloc method, which allows us to exclude the last column from our matrix of characteristics X.</em></p><h3><strong>Handling categorical variables:</strong></h3><p>The majority of the variables in the dataset are quantitative, except a few — Gender and Country — as shown in the graphic above. A machine learning model is just a mathematical formula that only accepts digits as input. So, if we try to build an ML model with this dataset, which contains both numeric and textual data, our model will simply fail during the building process. As a result, we must translate those string values into numerical equivalents while maintaining their meaning.</p><ul><li>We will <strong><em>“pd.get_dummies”</em></strong> to convert categorical variables to numerical variables.</li><li>We have also used “<strong><em>drop_first= True”</em></strong>, which means we are not going to be trapped by dummy variable traps.</li><li>We can turn those strings into a binary vector stream using One Hot Encoding. For example, Spain will be 001, France will be 010, and so on.</li></ul><pre>geography<strong>=</strong>pd<strong>.</strong>get_dummies(X[&quot;Geography&quot;],drop_first<strong>=True</strong>)<br>gender<strong>=</strong> pd<strong>.</strong>get_dummies(X[&#39;Gender&#39;],drop_first<strong>=True</strong>)</pre><p>Now, we will use the “<strong><em>Concat”</em></strong> function to add these variables to the original data frame and we will “<strong><em>drop”</em></strong> the useless column from it.</p><pre># concat <br>X<strong>=</strong>pd<strong>.</strong>concat([X,geography,gender],axis<strong>=</strong>1)</pre><pre># Dropping <br>X<strong>.</strong>drop([&#39;Geography&#39;,&#39;Gender&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)<br>X<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jqg9WeAi6Z8ljll6OaJTSw.png" /><figcaption>Final Independent varibales.</figcaption></figure><h3>Splitting dataset into training and testing dataset</h3><ul><li>The training dataset is the one on which our model will be trained, and the testing dataset is the one on which we will be testing our model’s performance.</li><li>The <strong><em>“train_test_split” </em></strong>function from the sklearn library was utilized here. We’ve split our dataset so that 80 percent of the data is in the training phase and 20 percent is in the testing phase.</li></ul><pre><em>#splitting into training and test </em><br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br>X_train,X_test,y_train,y_test<strong>=</strong>train_test_split(X,y,test_size<strong>=</strong>0.20,random_state<strong>=</strong>0)</pre><h3>Feature Scaling</h3><ul><li>Because in neural network features will multiply by weight +bais, so make it so this important how much time is taking, suppose The magnitude of features is a very high number, so weight* features multiplication will take more time So we try to scaled-down all the features in the same scale.</li></ul><pre><em># Feature scalling is must to converage will happen quickly</em><br><br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler<br>sc<strong>=</strong>StandardScaler()<br>X_train<strong>=</strong>sc<strong>.</strong>fit_transform(X_train)<br>X_test<strong>=</strong>sc<strong>.</strong>transform(X_test)</pre><p>To conduct standardization, we used the <strong><em>“StandardScalar”</em></strong> class from the sklearn library.</p><h3>Now we will build the ANN Model!</h3><ol><li>Define your model: create a <strong>Sequential</strong> model and <strong>add layers</strong>.</li><li>Compile your model: specify loss function and optimizers and call the <strong>.compile()</strong> function.</li><li>Fit your model: train the model on data by calling the <strong>.fit()</strong> function.</li><li>Make predictions: use the model to generate predictions on new data by calling functions such as .evaluate() or <strong>.predict()</strong></li></ol><pre><em># Initialising the ANN</em><br>classifier<strong>=</strong> Sequential()</pre><h3>Creating input layer/Hidden layer/Output layer</h3><ul><li>The Dense function in Keras constructs a fully connected neural network layer, automatically initializing the weights as biases.</li><li><strong>Units:</strong> The first argument, represents the number of nodes in this layer. several neurons that will be present in the respective layer.</li><li><strong>Activation: </strong>Specify which activation function to be used. The activation function of a logistic regression model is the logistic function or called the sigmoid</li><li><strong>Input_dim</strong>= No fo features in the training</li></ul><p>We know in a <strong>hidden layer</strong> — — — — -&gt; generally used <strong>Relu</strong> activation function to avoid vanishing gradient problem.</p><p>With <strong>Relu</strong> Activation function — → generally <strong>he_unifrom and he_normal</strong> work very well.</p><p>In the final layer/ <strong>output layer</strong> — — -&gt; we generally used the <strong>sigmoid</strong> activation function, and weight initialization <strong>glorot_uniform</strong> works pretty well.</p><pre><em># Adding the input layer and the first hidden layer</em><br>classifier<strong>.</strong>add(Dense(units<strong>=</strong>6,kernel_initializer<strong>=</strong>&#39;he_uniform&#39;,activation<strong>=</strong>&#39;relu&#39;,input_dim<strong>=</strong>11))</pre><pre><em># Adding the second hidden layer</em><br>classifier<strong>.</strong>add(Dense(units<strong>=</strong>6,kernel_initializer<strong>=</strong>&#39;he_uniform&#39;,activation<strong>=</strong>&#39;relu&#39;))<br><br><em># Adding the output layer</em><br>classifier<strong>.</strong>add(Dense(units<strong>=</strong>1,kernel_initializer<strong>=</strong>&#39;glorot_uniform&#39;,activation<strong>=</strong>&#39;sigmoid&#39;))</pre><pre>classifier<strong>.</strong>summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*zUI9QdHhvuPxq4HEt09zUw.png" /><figcaption>Layers in the model</figcaption></figure><h3>Complaining the ANN</h3><ol><li><strong>optimizer:</strong> This parameter indicates the optimizer will be used to perform stochastic gradient descent. I tried several optimizers, including RMSProp and adam, and discovered that the adam optimizer is a reliable one that can be used with any neural network.</li><li><strong>loss:</strong> indicates the type of loss function to employ. The value for binary classification should be binary cross-entropy. It should be categorical cross-entropy for multiclass categorization.</li><li><strong>Metrics:</strong> Which performance metrics should be used to calculate performance? We’ve utilized accuracy as a performance metric in this case.</li></ol><p>Thumbs Rules:</p><ul><li><strong><em>We mostly prefer optimizers — → Adam</em></strong></li><li><strong><em>The loss function for Binary — → binary_crossentropy</em></strong></li><li><strong><em>loss function for multiple class — — -&gt; categorical_crossentropy</em></strong></li></ul><pre><em># compiling ANN</em><br>classifier<strong>.</strong>compile(loss<strong>=</strong>&#39;binary_crossentropy&#39;,optimizer<strong>=</strong>&#39;adam&#39;,metrics<strong>=</strong>[&#39;accuracy&#39;])</pre><h3>Fitting the ANN to the Training set</h3><ul><li><strong>epochs:</strong> Number of times to go over the entire training data. When training models we pass through the training data not just once but multiple times.</li><li>We will prefer to give data in <strong>batch size</strong> in training, so it will run</li></ul><p>We will also have to mention How many epochs we will set since in this dataset there are 10,000 records, so no of <strong><em>epoch * batch size — → batch size =10, epochs=100</em></strong></p><p><strong>validation_split</strong> — — -&gt; to test the model separately for the test dataset</p><pre><em>#fitting the ANN to the training set</em><br>model_history<strong>=</strong>classifier<strong>.</strong>fit(X_train,y_train,validation_split<strong>=</strong>0.33,batch_size<strong>=</strong>10,epochs<strong>=</strong>100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hr6SjB7w9P2GuH8YYVM-g.png" /><figcaption>Training of Artificial Neural Network</figcaption></figure><p>We can see that our loss is lowering and our accuracy is growing with each epoch. As you can see, our ultimate accuracy is 85.42, which is quite impressive for such a simple neural network.</p><p>That’s all there is to it:). Using Python, we built our artificial neural network from the ground up.</p><h3><strong>Prediction:</strong></h3><p>Based on the values of independent variables, our neural network is trying to predict whether or not our consumers would leave.</p><pre><em># predicting the model</em><br>y_pred<strong>=</strong> classifier<strong>.</strong>predict(X_test)<br>y_pred<strong>=</strong> (y_pred<strong>&gt;</strong>0.5)<br>y_pred</pre><h4>Printing the confusion matrix, accuracy, and classification report</h4><p>The confusion matrix shows us how many classes were correctly classified vs misclassified. The numbers on the diagonal axis represent the number of correctly classified points, the rest are the misclassified ones.</p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> accuracy_score,confusion_matrix,classification_report<br><br>cm<strong>=</strong> confusion_matrix(y_test,y_pred)<br>print(cm)<br>accuracy<strong>=</strong>accuracy_score(y_test,y_pred)<br>print(&#39;The accuracy of the model is&#39;,accuracy)<br>cl_report <strong>=</strong> classification_report(y_test,y_pred)<br>print(cl_report)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*8iU3Qq_URNDY1KDC9xuthQ.png" /><figcaption>Confusion metrics, Classification report</figcaption></figure><h3><strong>Graphs:</strong></h3><pre>print(model_history<strong>.</strong>history<strong>.</strong>keys())<br><em># summarize history for accuracy</em><br>plt<strong>.</strong>plot(model_history<strong>.</strong>history[&#39;accuracy&#39;])<br>plt<strong>.</strong>plot(model_history<strong>.</strong>history[&#39;val_accuracy&#39;])<br>plt<strong>.</strong>title(&#39;model accuracy&#39;)<br>plt<strong>.</strong>ylabel(&#39;accuracy&#39;)<br>plt<strong>.</strong>xlabel(&#39;epoch&#39;)<br>plt<strong>.</strong>legend([&#39;train&#39;, &#39;test&#39;], loc<strong>=</strong>&#39;upper left&#39;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*se3TzCvL1kVZT6nGO-5nRA.png" /><figcaption>Train and test accuracy graph</figcaption></figure><h3>Conclusion</h3><p>Great job! You just built a Simple Neural Network that predicts customer churn with ~86% accuracy. Here’s what you’ve learned:</p><ul><li>What is ANN</li><li>Handling the categorical variables</li><li>What Are components in ANN</li><li>Build and evaluate the Neural Network.</li></ul><h3><strong>References:</strong></h3><ul><li><a href="https://machinelearningmastery.com/what-is-deep-learning/">Deep Learning &amp; Artificial Neural Networks</a></li><li><a href="https://www.mathworks.com/discovery/deep-learning.html">What Is Deep Learning?</a></li><li><a href="https://skymind.ai/wiki/neural-network">A Beginner’s Guide to Neural Networks and Deep Learning</a></li></ul><h3><strong>About Author:</strong></h3><ul><li><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></li><li><a href="https://github.com/rahkum96">rahkum96 - Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe64c2b9fd83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flight Fare Prediction: Detailed Exploratory Data Analysis (EDA) in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/flight-fare-predictions-b1150fdc45a3?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1150fdc45a3</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 06:37:27 GMT</pubDate>
            <atom:updated>2025-01-20T18:56:25.363Z</atom:updated>
            <content:encoded><![CDATA[<p>Detailed Exploratory Data Analysis (EDA)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ea1QU0yDUHYjtuon" /><figcaption>Image source <a href="https://www.pexels.com/photo/a380-air-airbus-aircraft-358220/">here</a></figcaption></figure><h4><strong>Objective</strong></h4><p>The goal of this article is to predict flight prices based on a variety of variables. The data utilized in this post may be found on Kaggle. Because the price is the target or dependent variable, this will be a regression problem (continuous numeric value).</p><h4><strong>Introduction:</strong></h4><p>The number of people who fly has dramatically increased in recent years. Pricing alters dynamically owing to many variables, making it difficult for airlines to maintain prices. As a result, we will attempt to solve this problem using machine learning. This can assist airlines in determining what rates they can keep. Customers can also use it to forecast future airline prices and plan their trips appropriately.</p><h4><strong>Data Set:</strong></h4><p>Source: <a href="https://www.kaggle.com/nikhilmittal/flight-fare-prediction-mh">https://www.kaggle.com/nikhilmittal/flight-fare-prediction-mh</a></p><p>There are two datasets here: the training set and the test set.</p><h4><strong>Approach:</strong></h4><ol><li>Importing the training data</li><li>Data pre-processing</li><li>Importing test data and data pre-processing</li><li>Creating Independent and Dependent variables</li><li>Features Selections</li><li>Model Building</li><li>Hyperparameter tuning</li><li>Conclusion</li></ol><h3>1. Importing the dataset</h3><p>Since data is in form of an excel file we have to use “pandas.read_excel” to load the data and store it in data frame train_data.</p><pre><em># Import Dataset</em><br>train_data<strong>=</strong>pd<strong>.</strong>read_excel(&quot;Data_Train.xlsx&quot;)</pre><pre><em># lets look at datset of first 5 rows</em><br>train_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXgXb0ZL0X0vTPtddKh5Hw.png" /><figcaption>Training data</figcaption></figure><h3><strong>2. Data Pre-processing:</strong></h3><p>The process of converting raw data into a comprehensible format is known as data preparation. We can’t work with raw data, thus this is a key stage in data mining. Before using machine learning or data mining methods, make sure the data is of good quality.</p><pre># Shape of the data<br>train_data<strong>.</strong>shape</pre><pre># Data information<br>train_data<strong>.</strong>info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*nRFtn86NTj17ag-2acnjnA.png" /><figcaption>Data types</figcaption></figure><p>Number of variables = 11<br>Number of rows = 10683<br>Number of categorical type of feature = 10<br>Number of numerical type of feature = 1</p><h3><strong>2.1 Missing Values:</strong></h3><pre><em>#checking for null values in dataset</em><br>train_data<strong>.</strong>isnull()<strong>.</strong>sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*E9WOBQFhPu5k_zqXDS01bA.png" /><figcaption>Missing values</figcaption></figure><pre><em># we will drop the nan values</em><br>train_data<strong>.</strong>dropna(inplace<strong>=True</strong>)<br>train_data<strong>.</strong>isnull()<strong>.</strong>sum()</pre><p>Since there is only one missing value, we can drop it.</p><h3><strong>2.2 Converting into Datetime:</strong></h3><ul><li>We are going to extract the date and month from the date of the journey</li></ul><p>For this, we require pandas to_datetime to convert the object data type to DateTime data type.</p><ul><li>.dt.day the method will extract only the day from the date.</li><li>.dt.month the method will extract only the month of that date.</li></ul><pre><em># here we will extract date and month from Date of Journey</em><br><em>#day</em><br>train_data[&quot;journey_Date&quot;]<strong>=</strong> pd<strong>.</strong>to_datetime(train_data[&#39;Date_of_Journey&#39;], format<strong>=</strong> &quot;%d/%m/%Y&quot;)<strong>.</strong>dt<strong>.</strong>day<br><br><em>#month</em><br>train_data[&quot;journey_Month&quot;]<strong>=</strong> pd<strong>.</strong>to_datetime(train_data[&#39;Date_of_Journey&#39;], format<strong>=</strong> &quot;%d/%m/%Y&quot;)<strong>.</strong>dt<strong>.</strong>month</pre><pre># Lets look at the first 5 rows<br>train_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjbt2TUrfM4chwI9lbt8Xg.png" /></figure><pre><em># Since we have converted Date_of_Journey column into integers, Now we can drop as it is of no use.</em><br>train_data<strong>.</strong>drop([&#39;Date_of_Journey&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><p>We Extracted the <strong>day </strong>and <strong>month</strong> from the <strong>“<em>Date_of_Journey”</em></strong><em> column and we dropped it.</em></p><pre><em># Departure time is when a plane leaves the gate. </em><br><em># Similar to Date_of_Journey we can extract values from Dep_Time</em><br><br><em># Extracting Hours</em><br>train_data[&#39;Dep_hour&#39;]<strong>=</strong>pd<strong>.</strong>to_datetime(train_data[&#39;Dep_Time&#39;])<strong>.</strong>dt<strong>.</strong>hour  <em>#pd.to_datetime</em><br><br><em>#Extracting minutes</em><br>train_data[&#39;Dep_min&#39;]<strong>=</strong>pd<strong>.</strong>to_datetime(train_data[&#39;Dep_Time&#39;])<strong>.</strong>dt<strong>.</strong>minute<br><br><em>#Now we will drop the dep_time, no use</em><br>train_data<strong>.</strong>drop([&#39;Dep_Time&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><p><strong>Departure<em> time</em></strong><em> is when a plane leaves the gate. </em><br><em>Similar to </em><strong><em>“Date_of_Journey” </em></strong><em>we can extract values from </em><strong><em>“Dep_Time”</em></strong></p><pre><em># Arrival time is when a plane leaves. </em><br><em># Similar to Date_of_Journey we can extract values from Dep_Time</em><br><br><em># Extracting Hours</em><br>train_data[&#39;Arrival_hour&#39;]<strong>=</strong>pd<strong>.</strong>to_datetime(train_data[&#39;Arrival_Time&#39;])<strong>.</strong>dt<strong>.</strong>hour  <em>#pd.to_datetime</em><br><br><em>#Extracting minutes</em><br>train_data[&#39;Arrival_min&#39;]<strong>=</strong>pd<strong>.</strong>to_datetime(train_data[&#39;Arrival_Time&#39;])<strong>.</strong>dt<strong>.</strong>minute<br><br><em>#Now we will drop the dep_time, no use</em><br>train_data<strong>.</strong>drop([&#39;Arrival_Time&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><p><strong><em>Arrival time</em></strong><em> is when a plane leaves. </em><br><em>Similar to </em><strong><em>“Date_of_Journey”</em></strong><em> we can extract values from </em><strong><em>“</em>Arrival_Time”</strong>.</p><p>Let&#39;s look at the data.</p><pre>train_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mOgc4KjM4mOUWUz8WGJ-g.png" /></figure><h4><strong>“Duration” column:</strong></h4><p>Here we are trying to extract the <strong>hours</strong> and<strong> minutes</strong> from the feature <strong>“duration”</strong>.</p><pre><em># Assigning and converting Duration column into list</em><br>duration <strong>=</strong> list(train_data[&quot;Duration&quot;])<br><strong>for</strong> i <strong>in</strong> range(len(duration)):<br>    <strong>if</strong> len(duration[i]<strong>.</strong>split()) <strong>!=</strong>2:  <em># Check if duration contains only hour or mins</em><br>        <strong>if</strong> &quot;h&quot; <strong>in</strong> duration[i]:<br>            duration[i] <strong>=</strong> duration[i]<strong>.</strong>strip() <strong>+</strong> &quot; 0m&quot;   <em># Adds 0 minute</em><br>        <strong>else</strong>:<br>            duration[i] <strong>=</strong> &quot;0h &quot; <strong>+</strong> duration[i]           <em># Adds 0 hour</em><br><br>duration_hours <strong>=</strong> []<br>duration_mins <strong>=</strong> []<br><strong>for</strong> i <strong>in</strong> range(len(duration)):<br>    duration_hours<strong>.</strong>append(int(duration[i]<strong>.</strong>split(sep <strong>=</strong> &quot;h&quot;)[0]))    <em># Extract hours from duration</em><br>    duration_mins<strong>.</strong>append(int(duration[i]<strong>.</strong>split(sep <strong>=</strong> &quot;m&quot;)[0]<strong>.</strong>split()[<strong>-</strong>1]))   <em># Extracts only minutes from duration</em></pre><p><em>Adding “</em><strong><em>duration_hours”</em></strong><em> and “</em><strong><em>duration_mins”</em></strong><em> list to train_data data frame and dropping the column “</em><strong><em>duration” </em></strong><em>from it.</em></p><pre>train_data[&quot;Duration_hours&quot;] <strong>=</strong> duration_hours<br>train_data[&quot;Duration_mins&quot;] <strong>=</strong> duration_mins<br><br><em>#we will remove the DUrtaion clumns</em><br>train_data<strong>.</strong>drop([&#39;Duration&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jbme_mzFOd-o1HlKUY3i8w.png" /></figure><h3>2.3. Handling Categorical Data:</h3><p><strong>Airline, Source, Destination, Route, Total_Stops, Additional_info</strong> are the categorical variables we have in our data. Let’s handle each one by one.</p><ul><li><strong>Nominal data</strong> → are not in any order → <strong>OneHotEncoder</strong> is used in this case</li><li><strong>Ordinal data</strong> → are in order → <strong>LabelEncoder</strong> is used in this case</li></ul><p><strong><em>Trying to find out unique values in column Airline and counts the unique values as well.</em></strong></p><pre>train_data[&#39;Airline&#39;]<strong>.</strong>unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*r19WlAqSFaWK6LVXXKPF1A.png" /></figure><p>We could say that <strong>Jet Airways </strong>has occurred maximum numbers of times followed by IndiGo and Air India.</p><h3><strong>2.3.1 One-hot encoding:</strong></h3><ul><li>Another typical technique for dealing with categorical information is one-hot encoding. It simply adds more characteristics to the categorical feature dependent on the number of unique values. Every category’s unique value will be added as a feature.</li><li>The method of constructing dummy variables is known as one-hot encoding.</li><li>Each category is represented as a single-hot vector in this encoding technique. Let’s take a look at how to do one-hot encoding in Python:</li></ul><pre><em>#OneHotEncoding -----&gt; Nominal data</em><br>Airline <strong>=</strong> train_data[[&quot;Airline&quot;]]<br>Airline <strong>=</strong> pd<strong>.</strong>get_dummies(train_data[&#39;Airline&#39;],drop_first<strong>=True</strong>)<br>Airline<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUTCY4tHZGWNsglK8GgZig.png" /></figure><h3><strong>Airline vs Price:</strong></h3><p>Let’s see how the <strong>Airline</strong> variable is related to the <strong>Price</strong> variable.</p><pre><em># Airline vs Price</em><br>sns<strong>.</strong>catplot(y <strong>=</strong> &quot;Price&quot;, x <strong>=</strong> &quot;Airline&quot;, data <strong>=</strong> train_data<strong>.</strong>sort_values(&quot;Price&quot;, ascending <strong>=</strong> <strong>False</strong>), kind<strong>=</strong>&quot;boxen&quot;, height <strong>=</strong> 6, aspect <strong>=</strong> 3)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RG8hI2AmpqF-e6m0otIag.png" /></figure><p>As can be seen, the airline’s name is important. The most expensive option is ‘<strong>JetAirways Business</strong>.’ The cost of other carriers varies as well.</p><p>We’ll use <strong>one-hot encoding</strong> to handle the Airline variable because it’s Nominal Categorical Data (airline names have no order of any kind).</p><h3><strong>Source vs Destination:</strong></h3><p>Again, the variables <strong>‘Source’</strong> and <strong>‘Destination’</strong> are Nominal Categorical Data. To deal with these two variables, we’ll employ One-Hot encoding once more.</p><pre><em># Source vs Price</em><br><br>sns<strong>.</strong>boxplot(y <strong>=</strong> &quot;Price&quot;, x <strong>=</strong> &quot;Source&quot;, data <strong>=</strong> train_data<strong>.</strong>sort_values(&quot;Price&quot;, ascending <strong>=</strong> <strong>False</strong>))<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*xo4mQPkTJ5Ta8o_ESQ3_XA.png" /></figure><pre><em>#OneHotEncoding -----&gt; Nominal data</em><br>Source <strong>=</strong> train_data[[&quot;Source&quot;]]<br>Source <strong>=</strong> pd<strong>.</strong>get_dummies(train_data[&#39;Source&#39;],drop_first<strong>=True</strong>)<br>Source<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*Rzj4njyVvPZanB_X0f2IGQ.png" /></figure><pre><em># As Destination is Nominal Categorical data we will perform OneHotEncoding</em><br><br>Destination <strong>=</strong> train_data[[&quot;Destination&quot;]]<br><br>Destination <strong>=</strong> pd<strong>.</strong>get_dummies(Destination, drop_first <strong>=</strong> <strong>True</strong>)<br><br>Destination<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*jEnCp6sYa4GjlpAR0PFaJw.png" /></figure><h3><strong>Variable route:</strong></h3><p>The journey’s path is represented by the route variable. I opted to remove this field because the <strong>‘Total Stops’</strong> value captures whether the flight is direct or connected.</p><pre><em># droping column, because Additinal_info has since 80 % has no information </em><br><em># Route---&gt; is related to no of stops</em><br>train_data<strong>.</strong>drop([&quot;Route&quot;, &quot;Additional_Info&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)</pre><h3><strong>Total_Stops Variable:</strong></h3><p>Non-stop refers to a flight with no stops, i.e. a straight flight. It is self-evident that other values have the same meaning. We can see that it’s Ordinal Categorical Data, thus we’ll use <strong>LabelEncoder</strong> to deal with it.</p><pre>train_data[&#39;Total_Stops&#39;]<strong>.</strong>value_counts()<br><em># As this is case of Ordinal Categorical type we perform LabelEncoder</em><br><em>#we replace the values in key values </em><br>train_data<strong>.</strong>replace({&#39;non-stop&#39;:0,&#39;1 stop&#39;:1,&#39;2 stops&#39;:2,&#39;3 stops&#39;:3,&#39;4 stops&#39;:4},inplace<strong>=True</strong>)</pre><pre>train_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Jv8z-N33yN9dKCdQVuUtQ.png" /></figure><h3><strong>Final Dataframe:</strong></h3><p>Now we’ll join all of the One-hot and Label-encoded features to the original data frame to make the final data frame. We’ll also get rid of the old variables that we used to create the new encoded variables.</p><pre><em>#Concatenate dataframe --&gt; train_data + Airline + Source + Destination</em><br>data_train<strong>=</strong>pd<strong>.</strong>concat([train_data,Airline , Source, Destination],axis<strong>=</strong>1)</pre><pre><em># we have drop the varibles</em><br>data_train<strong>.</strong>drop([&quot;Airline&quot;,&quot;Source&quot;,&quot;Destination&quot;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><pre>data_train<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3oR1ok7jaeuONX3wHDshQ.png" /></figure><p>As a result, the final data frame has <strong>30 variables,</strong> including the dependent variable ‘Price.’ For training, there are only <strong>29variables</strong>.</p><h3>3. Test Data:</h3><p>We are going to repeat all these steps for test data as well.</p><p><strong>Importing test data:</strong></p><pre>test_data<strong>=</strong> pd<strong>.</strong>read_excel(&quot;Test_Set.xlsx&quot;)<br>test_data<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pV6Y2MsBQgQpqIW06Uz2Kg.png" /><figcaption>Test data</figcaption></figure><pre><em># Preprocessing</em><br><br><br>print(test_data<strong>.</strong>info())<br><br><br>test_data<strong>.</strong>dropna(inplace <strong>=</strong> <strong>True</strong>)<br>print(test_data<strong>.</strong>isnull()<strong>.</strong>sum())<br><br><em># EDA</em><br><br><em># Date_of_Journey</em><br>test_data[&quot;Journey_day&quot;] <strong>=</strong> pd<strong>.</strong>to_datetime(test_data<strong>.</strong>Date_of_Journey, format<strong>=</strong>&quot;%d/%m/%Y&quot;)<strong>.</strong>dt<strong>.</strong>day<br>test_data[&quot;Journey_month&quot;] <strong>=</strong> pd<strong>.</strong>to_datetime(test_data[&quot;Date_of_Journey&quot;], format <strong>=</strong> &quot;%d/%m/%Y&quot;)<strong>.</strong>dt<strong>.</strong>month<br>test_data<strong>.</strong>drop([&quot;Date_of_Journey&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)<br><br><em># Dep_Time</em><br>test_data[&quot;Dep_hour&quot;] <strong>=</strong> pd<strong>.</strong>to_datetime(test_data[&quot;Dep_Time&quot;])<strong>.</strong>dt<strong>.</strong>hour<br>test_data[&quot;Dep_min&quot;] <strong>=</strong> pd<strong>.</strong>to_datetime(test_data[&quot;Dep_Time&quot;])<strong>.</strong>dt<strong>.</strong>minute<br>test_data<strong>.</strong>drop([&quot;Dep_Time&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)<br><br><em># Arrival_Time</em><br>test_data[&quot;Arrival_hour&quot;] <strong>=</strong> pd<strong>.</strong>to_datetime(test_data<strong>.</strong>Arrival_Time)<strong>.</strong>dt<strong>.</strong>hour<br>test_data[&quot;Arrival_min&quot;] <strong>=</strong> pd<strong>.</strong>to_datetime(test_data<strong>.</strong>Arrival_Time)<strong>.</strong>dt<strong>.</strong>minute<br>test_data<strong>.</strong>drop([&quot;Arrival_Time&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)<br><br><em># Duration</em><br>duration <strong>=</strong> list(test_data[&quot;Duration&quot;])<br><br><strong>for</strong> i <strong>in</strong> range(len(duration)):<br>    <strong>if</strong> len(duration[i]<strong>.</strong>split()) <strong>!=</strong> 2:    <em># Check if duration contains only hour or mins</em><br>        <strong>if</strong> &quot;h&quot; <strong>in</strong> duration[i]:<br>            duration[i] <strong>=</strong> duration[i]<strong>.</strong>strip() <strong>+</strong> &quot; 0m&quot;   <em># Adds 0 minute</em><br>        <strong>else</strong>:<br>            duration[i] <strong>=</strong> &quot;0h &quot; <strong>+</strong> duration[i]           <em># Adds 0 hour</em><br><br>duration_hours <strong>=</strong> []<br>duration_mins <strong>=</strong> []<br><strong>for</strong> i <strong>in</strong> range(len(duration)):<br>    duration_hours<strong>.</strong>append(int(duration[i]<strong>.</strong>split(sep <strong>=</strong> &quot;h&quot;)[0]))    <em># Extract hours from duration</em><br>    duration_mins<strong>.</strong>append(int(duration[i]<strong>.</strong>split(sep <strong>=</strong> &quot;m&quot;)[0]<strong>.</strong>split()[<strong>-</strong>1]))   <em># Extracts only minutes from duration</em><br><br><em># Adding Duration column to test set</em><br>test_data[&quot;Duration_hours&quot;] <strong>=</strong> duration_hours<br>test_data[&quot;Duration_mins&quot;] <strong>=</strong> duration_mins<br>test_data<strong>.</strong>drop([&quot;Duration&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)<br><br><br><em># Categorical data</em><br><br>print(&quot;Airline&quot;)<br>print(&quot;-&quot;<strong>*</strong>75)<br>print(test_data[&quot;Airline&quot;]<strong>.</strong>value_counts())<br>Airline <strong>=</strong> pd<strong>.</strong>get_dummies(test_data[&quot;Airline&quot;], drop_first<strong>=</strong> <strong>True</strong>)<br><br><br><br><br>print(test_data[&quot;Source&quot;]<strong>.</strong>value_counts())<br>Source <strong>=</strong> pd<strong>.</strong>get_dummies(test_data[&quot;Source&quot;], drop_first<strong>=</strong> <strong>True</strong>)<br><br><br><br><br>print(test_data[&quot;Destination&quot;]<strong>.</strong>value_counts())<br>Destination <strong>=</strong> pd<strong>.</strong>get_dummies(test_data[&quot;Destination&quot;], drop_first <strong>=</strong> <strong>True</strong>)<br><br><em># Additional_Info contains almost 80% no_info</em><br><em># Route and Total_Stops are related to each other</em><br>test_data<strong>.</strong>drop([&quot;Route&quot;, &quot;Additional_Info&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)<br><br><em># Replacing Total_Stops</em><br>test_data<strong>.</strong>replace({&quot;non-stop&quot;: 0, &quot;1 stop&quot;: 1, &quot;2 stops&quot;: 2, &quot;3 stops&quot;: 3, &quot;4 stops&quot;: 4}, inplace <strong>=</strong> <strong>True</strong>)<br><br><em># Concatenate dataframe --&gt; test_data + Airline + Source + Destination</em><br>data_test <strong>=</strong> pd<strong>.</strong>concat([test_data, Airline, Source, Destination], axis <strong>=</strong> 1)<br><br>data_test<strong>.</strong>drop([&quot;Airline&quot;, &quot;Source&quot;, &quot;Destination&quot;], axis <strong>=</strong> 1, inplace <strong>=</strong> <strong>True</strong>)<br><br>print()<br>print()<br><br>print(&quot;Shape of test data : &quot;, data_test<strong>.</strong>shape)</pre><p><strong>Final Test data:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RA2TU3p6VSfHT8U_zQO2g.png" /><figcaption>Final Test data</figcaption></figure><h3><strong>4. Creating Independent and dependent variables:</strong></h3><p><strong>Independent variables</strong></p><pre>X<strong>=</strong> data_train[[&#39;Total_Stops&#39;, &#39;journey_Date&#39;, &#39;journey_Month&#39;, &#39;Dep_hour&#39;,<br>       &#39;Dep_min&#39;, &#39;Arrival_hour&#39;, &#39;Arrival_min&#39;, &#39;Duration_hours&#39;,<br>       &#39;Duration_mins&#39;, &#39;Air India&#39;, &#39;GoAir&#39;, &#39;IndiGo&#39;, &#39;Jet Airways&#39;,<br>       &#39;Jet Airways Business&#39;, &#39;Multiple carriers&#39;,<br>       &#39;Multiple carriers Premium economy&#39;, &#39;SpiceJet&#39;, &#39;Trujet&#39;, &#39;Vistara&#39;,<br>       &#39;Vistara Premium economy&#39;, &#39;Chennai&#39;, &#39;Delhi&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;,<br>       &#39;Destination_Cochin&#39;, &#39;Destination_Delhi&#39;, &#39;Destination_Hyderabad&#39;,<br>       &#39;Destination_Kolkata&#39;, &#39;Destination_New Delhi&#39;]]<br>X<strong>.</strong>head()</pre><p><strong>Dependent variable:</strong></p><pre>y<strong>=</strong>data_train[&#39;Price&#39;]</pre><h3>5. Feature Selection</h3><p>Finding out the best feature which will contribute and have good relationships with the target variable. Following are some of the feature selection methods,</p><ul><li>Correlation</li><li>feature importance</li><li>SelectKBest</li></ul><h3><strong>5.1. Correlation:</strong></h3><p>Correlation is a technique for determining the link between two variables, which is useful in real life since it allows us to forecast the value of one variable using other factors that are connected with it. Because two variables are involved, it is a sort of bivariate statistic.</p><pre><em># Heatmap</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(25,25))<br>sns<strong>.</strong>heatmap(data_train<strong>.</strong>corr(),annot <strong>=</strong> <strong>True</strong>, cmap <strong>=</strong> &quot;RdYlGn&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yHFhyLn2X-6H2lKC7whNsQ.png" /><figcaption>Correlation graph</figcaption></figure><p>Finding highly correlated independent variables</p><pre><em>#Removing correlated features</em><br>Threshold<strong>=</strong>0.9</pre><pre><em># find and remove correlated features</em><br><strong>def</strong> correlation(dataset, threshold):<br>    col_corr <strong>=</strong> set()  <em># Set of all the names of correlated columns</em><br>    corr_matrix <strong>=</strong> dataset<strong>.</strong>corr()<br>    <strong>for</strong> i <strong>in</strong> range(len(corr_matrix<strong>.</strong>columns)):<br>        <strong>for</strong> j <strong>in</strong> range(i):<br>            <strong>if</strong> abs(corr_matrix<strong>.</strong>iloc[i, j]) <strong>&gt;</strong> threshold: <em># we are interested in absolute coeff value</em><br>                colname <strong>=</strong> corr_matrix<strong>.</strong>columns[i]  <em># getting the name of column</em><br>                col_corr<strong>.</strong>add(colname)<br>    <strong>return</strong> col_corr</pre><pre><br>correlation(X,Threshold)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*M-1SkdI5sbq6Q_16PILkvA.png" /><figcaption>Highly Correlated features</figcaption></figure><h3>5.2. Feature importance:</h3><p>In machine learning, the purpose of feature selection is to discover the best set of characteristics that allows one to develop usable models of the phenomena being examined.</p><pre><em># Important feature using ExtraTreesRegressor</em><br><br><strong>from</strong> sklearn.ensemble <strong>import</strong> ExtraTreesRegressor<br>selection <strong>=</strong> ExtraTreesRegressor()<br>selection<strong>.</strong>fit(X, y)</pre><p>Graph:</p><pre><em>#plot graph of feature importances for better visualization</em><br><br>plt<strong>.</strong>figure(figsize <strong>=</strong> (12,8))<br>feat_importances <strong>=</strong> pd<strong>.</strong>Series(selection<strong>.</strong>feature_importances_, index<strong>=</strong>X<strong>.</strong>columns)<br>feat_importances<strong>.</strong>nlargest(20)<strong>.</strong>plot(kind<strong>=</strong>&#39;barh&#39;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oVi8dzd29G1FdZ9SJCkjA.png" /><figcaption>Features important graph</figcaption></figure><h3><strong>5.3. SelectKBest:</strong></h3><pre><em># import library</em><br><strong>from</strong> sklearn.feature_selection <strong>import</strong> SelectKBest<br><strong>from</strong> sklearn.feature_selection <strong>import</strong> chi2</pre><pre><em>#Deifne feature selection</em><br>fs<strong>=</strong>SelectKBest(score_func<strong>=</strong>chi2)  <br><em># Applying feature selection</em><br>X_selected<strong>=</strong>fs<strong>.</strong>fit(X,y)</pre><p>Graph:</p><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(15,15))<br>feat_importances <strong>=</strong> pd<strong>.</strong>Series(X_selected<strong>.</strong>scores_, index<strong>=</strong>X<strong>.</strong>columns)<br>feat_importances<strong>.</strong>nlargest(20)<strong>.</strong>plot(kind<strong>=</strong>&#39;barh&#39;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQYrKio9GbN_hDkb2R34Ig.png" /><figcaption>SelectKBasket Graph</figcaption></figure><h3>6. Fitting model using Random Forest</h3><p><em>1. Split the dataset into train and test set to prediction w.r.t X_test</em></p><p><em>2. Scaling is not done in Random forest</em></p><p><em>3. Import model</em></p><p><em>4. Fit the data</em></p><p><em>5.Predict w.r.t X_test</em></p><p><em>6. In regression check RSME Score</em></p><p><em>7. Plot error graph</em></p><p><strong>6.1 Train Test split:</strong></p><pre><em>#Splitting inot train_test</em><br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br>X_train,X_test,y_train,y_test<strong>=</strong>train_test_split(X,y,test_size<strong>=</strong>0.2,random_state<strong>=</strong>0)</pre><p><strong>6.2 Building the model:</strong></p><pre><em>#Building the model</em><br><strong>from</strong> sklearn.ensemble <strong>import</strong> RandomForestRegressor<br>reg<strong>=</strong>RandomForestRegressor()<br>reg<strong>.</strong>fit(X_train,y_train)</pre><p><strong>6.3 Predicting the Model:</strong></p><pre><em>#predicting the model</em><br>y_pred<strong>=</strong>reg<strong>.</strong>predict(X_test)</pre><p><strong>6.4 Evaluating the Model:</strong></p><pre><em>#Accuracy</em><br>print(reg<strong>.</strong>score(X_test,y_test))<br>print(reg<strong>.</strong>score(X_train,y_train))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*cHQls0LLzdI70VTBacYcAg.png" /><figcaption>Accuracy</figcaption></figure><pre><em>#RMSE</em><br><strong>from</strong> sklearn.metrics <strong>import</strong> mean_squared_error<br><strong>from</strong> math <strong>import</strong> sqrt<br>rmse<strong>=</strong>sqrt(mean_squared_error(y_test,y_pred))<br>rmse</pre><p><strong>6.5 Plot the error graph:</strong></p><pre><em>#Plotting the error graph and should be mean=0</em><br>sns<strong>.</strong>distplot(y_test<strong>-</strong>y_pred,kde<strong>=True</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*tNPDe4OEM90KEJWixDghUA.png" /><figcaption>Error Graph</figcaption></figure><p><strong>Scatter Graph:</strong></p><pre><em>#Plotting scatter graph to check linear relations</em><br>plt<strong>.</strong>scatter(y_test,y_pred,alpha<strong>=</strong>0.5)<br>plt<strong>.</strong>xlabel(&#39;y_test&#39;)<br>plt<strong>.</strong>ylabel(&#39;y_pred&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*arRKc3I9ou_lROjjSaq89w.png" /><figcaption>Scatter graph</figcaption></figure><p>With an r2 score of 81 percent, With this model, we can also calculate the minimal values for mean absolute error, mean squared error, and root mean squared error (regression metrics). We will try to improve the accuracy by doing hyperparameter tuning.</p><h3>7. Hyperparameter tuning</h3><ul><li>Choose the following method for hyperparameter tuning</li></ul><ol><li><strong>RandomizedSearchCV</strong></li></ol><ul><li>Assign hyperparameters in form of a dictionary</li><li>Fit the model</li><li>Check best parameters and the best score</li></ul><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> RandomizedSearchCV</pre><pre><strong>import</strong> numpy <strong>as</strong> np<br><br><em>#Randomized Search CV</em><br><br><em># Number of trees in random forest</em><br>n_estimators <strong>=</strong> [int(x) <strong>for</strong> x <strong>in</strong> np<strong>.</strong>linspace(start <strong>=</strong> 100, stop <strong>=</strong> 1200, num <strong>=</strong> 12)]<br><em># Number of features to consider at every split</em><br>max_features <strong>=</strong> [&#39;auto&#39;, &#39;sqrt&#39;]<br><em># Maximum number of levels in tree</em><br>max_depth <strong>=</strong> [int(x) <strong>for</strong> x <strong>in</strong> np<strong>.</strong>linspace(5, 30, num <strong>=</strong> 6)]<br><em># Minimum number of samples required to split a node</em><br>min_samples_split <strong>=</strong> [2, 5, 10, 15, 100]<br><em># Minimum number of samples required at each leaf node</em><br>min_samples_leaf <strong>=</strong> [1, 2, 5, 10]</pre><p><strong>Creating param Grid:</strong></p><pre><em># Create the random grid</em><br><br>random_grid <strong>=</strong> {&#39;n_estimators&#39;: n_estimators,<br>               &#39;max_features&#39;: max_features,<br>               &#39;max_depth&#39;: max_depth,<br>               &#39;min_samples_split&#39;: min_samples_split,<br>               &#39;min_samples_leaf&#39;: min_samples_leaf}</pre><p><strong>optimal parameters:</strong></p><pre><em># Random search of parameters, using 5 fold cross validation, </em><br><em># search across 100 different combinations</em><br><br>rf_random <strong>=</strong> RandomizedSearchCV(estimator <strong>=</strong> reg, param_distributions <strong>=</strong> random_grid,scoring<strong>=</strong>&#39;neg_mean_squared_error&#39;, n_iter <strong>=</strong> 10, cv <strong>=</strong> 5, verbose<strong>=</strong>2, random_stat</pre><p><strong>Fitting the model:</strong></p><pre>rf_random<strong>.</strong>fit(X_train,y_train)</pre><p><strong>Best parameters:</strong></p><pre><em># Finding the best parameter we should give in </em><br>rf_random<strong>.</strong>best_params_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*QGlbK2GM3hCKsBntGb2zGQ.png" /><figcaption>Best Parameter</figcaption></figure><p><strong>Predicting the tunned model:</strong></p><p>Here we are using the best parameter to predict the final model.</p><pre>prediction <strong>=</strong> rf_random<strong>.</strong>predict(X_test)</pre><p><strong>Error graph of tuned model:</strong></p><pre>plt<strong>.</strong>figure(figsize <strong>=</strong> (8,8))<br>sns<strong>.</strong>distplot(y_test<strong>-</strong>prediction)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*5R1_v03hw-cpCPVCs6B8CA.png" /><figcaption>Error graph of the tuned model</figcaption></figure><p><strong>Scatter plot of tuned model:</strong></p><pre>plt<strong>.</strong>figure(figsize <strong>=</strong> (8,8))<br>plt<strong>.</strong>scatter(y_test, prediction, alpha <strong>=</strong> 0.5)<br>plt<strong>.</strong>xlabel(&quot;y_test&quot;)<br>plt<strong>.</strong>ylabel(&quot;y_pred&quot;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*tWyzDgbsiCTiqEIz5m8xlA.png" /></figure><p><strong>Evaluating the tunned model:</strong></p><pre>print(&#39;MAE:&#39;, metrics<strong>.</strong>mean_absolute_error(y_test, prediction))<br>print(&#39;MSE:&#39;, metrics<strong>.</strong>mean_squared_error(y_test, prediction))<br>print(&#39;RMSE:&#39;, np<strong>.</strong>sqrt(metrics<strong>.</strong>mean_squared_error(y_test, prediction)))</pre><pre>#accuracy<br>metrics<strong>.</strong>r2_score(y_test,prediction)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Ec1qv-vWSty32R0BpH09gg.png" /><figcaption>Result</figcaption></figure><p>After hyper tuning, the r2 score for random forest Regressor is 84 percent, whereas, before hyper tuning, the r2 score for random forest Regressor was 81 percent. The value of MAE drops as well, indicating that we were successful in tunning our model.</p><h3><strong>8. Conclusion:</strong></h3><ul><li>So, we have used a random forest model for this data and improved accuracy by doing hyperparameter tuning.</li><li>As a result, we were able to successfully train our regression model, the ‘Random forest model,’ to forecast pricing flights with an r2 score of 84 percent and complete the required work.</li></ul><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1150fdc45a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing Fresco Retail’s Customer Transactions to Predict Return Decisions in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/fresco-retail-project-226ae86f0ea1?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/226ae86f0ea1</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fresco]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 09:41:22 GMT</pubDate>
            <atom:updated>2025-01-20T19:03:36.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GpQ0O5L-CX2ieBbo.png" /><figcaption>Image Source <a href="https://www.mapleridgenews.com/business/freshco-opens-in-maple-ridge-on-thursday/">here</a></figcaption></figure><h4>Problem description:</h4><ul><li>The data analyses Fresco Retail’s customers’ transaction data to predict return decisions using various data points like customer background, payment modes, store types, product nature, etc.</li></ul><p><strong>Objective:</strong></p><ul><li>To study the influence of different transaction data points and their impact on a customer’s final decision to return the product(s) bought in a transaction.</li></ul><h3>Approach:</h3><ul><li>Understand the data variables properly.</li><li>Clean the data</li><li>Conduct EDA (Exploratory Data Analysis) on the cleaned data</li><li>Uni-variate and Bi-variate Analysis</li><li>Feature Engineering</li><li>Identify the most important variables (or data parameters) that affect the final decision</li><li>Develop and Validate Samples</li><li>Model Building</li><li>Improving model accuracy</li><li>Model Comparison</li><li>Prediction</li></ul><ol><li><strong>Import libraries:</strong></li></ol><pre><em># import the library </em><br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> seaborn <strong>as</strong> sns<br><strong>%matplotlib</strong> inline<br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split</pre><pre><em># standarisation: We use the Standardscaler from sklearn library</em><br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler</pre><pre><em># import SMOTE oversampling and other necessary libraries </em><br><strong>from</strong> collections <strong>import</strong> Counter</pre><pre><strong>from</strong> sklearn.linear_model <strong>import</strong> LogisticRegression</pre><pre><strong>from</strong> sklearn.metrics <strong>import</strong> accuracy_score,confusion_matrix,classification_report</pre><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> cross_val_score</pre><pre><strong>from</strong> sklearn.ensemble <strong>import</strong> RandomForestClassifier</pre><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> RandomizedSearchCV</pre><pre><strong>from</strong> sklearn.feature_selection <strong>import</strong> chi2</pre><p><strong>2. Import the dataset:</strong></p><p>Dataset link: <a href="https://github.com/rahkum96/FRESCO-RETAIL-PROJECT/blob/main/Fresco_LargeRetailer.xlsx">https://github.com/rahkum96/FRESCO-RETAIL-PROJECT/blob/main/Fresco_LargeRetailer.xlsx</a></p><pre>df<strong>=</strong> pd<strong>.</strong>read_excel(&#39;Fresco_LargeRetailer.xlsx&#39;,sheet_name<strong>=</strong> &#39;Transaction_Data&#39;)<br>df<strong>.</strong>head()</pre><p>So, we are storing the data in a data frame called ‘df’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mV3LPqrYvoXwJ1164r5og.png" /><figcaption>First five rows of data</figcaption></figure><p>Here we are mapping the data with relevant information from other data sources. So that we could understand the data in a meaningful manner.</p><pre>df[&#39;Month_code&#39;]<strong>.</strong>replace({1:&quot;January&quot;,2:&quot;February&quot;,3:&quot;March&quot;,4:&quot;April&quot;,5:&quot;May&quot;,6:&quot;June&quot;,7:&quot;July&quot;,8:&quot;August&quot;,9:&quot;September&quot;,<br>           10:&quot;October&quot;,11:&quot;November&quot;,12:&quot;December&quot;},inplace<strong>=True</strong>)<br><br>df[&#39;prod_cat_code&#39;]<strong>.</strong>replace({1:&quot;Bags&quot;,2:&quot;Books&quot;,3:&quot;Clothing&quot;,4:&#39;Electronics&#39;,5:&#39;Footwear&#39;,6:&#39;Home and kitchen&#39;},inplace<strong>=True</strong>)<br><br>df[&#39;prod_subcat_code&#39;]<strong>.</strong>replace({1:&#39;Bath&#39;,2:&#39;Academic&#39;,3:&#39;Women&#39;,4:&#39;Mens&#39;,5:&#39;Tools&#39;,6:&#39;Fiction&#39;,7:&#39;DIY&#39;,8:&#39;Kitchen&#39;,9:&#39;Non-Fiction&#39;,<br>                                10:&#39;Kids&#39;,11:&#39;Mobiles&#39;,12:&#39;Audio and video&#39;,13:&#39;Comics&#39;,14:&#39;Computers&#39;,15:&#39;Furnishing&#39;,<br>                                16:&#39;Children&#39;,17:&#39;Personal Appliances&#39;,18:&#39;Cameras&#39;}, inplace<strong>=True</strong>)<br><br>df[&#39;Education_code&#39;]<strong>.</strong>replace({1:&#39;Basic&#39;,2:&#39;Graduation&#39;,3:&#39;Master&#39;,4:&#39;PhD&#39;,5:&#39;Others&#39;}, inplace<strong>=True</strong>)<br><br>df[&#39;Profession_Code&#39;]<strong>.</strong>replace({1:&#39;Self Employed&#39;,2:&#39;Salaried&#39;,3:&#39;Others&#39;},inplace<strong>=True</strong>)<br><br>df[&#39;city_code&#39;]<strong>.</strong>replace({1:&#39;Mumbai&#39;,2:&#39;Bangalore&#39;,3:&#39;New Delhi&#39;,4:&#39;Gurgaon&#39;,5:&#39;Kolkata&#39;,6:&#39;Chennai&#39;,<br>                         7:&#39;Pune&#39;,8:&#39;Hyderabad&#39;,9:&#39;Vishakhapatnam&#39;,10:&#39;Ahmedabad&#39;}, inplace<strong>=True</strong>)<br><br>df[&#39;Return&#39;]<strong>.</strong>replace({<strong>True</strong>:&#39;Yes&#39;,<strong>False</strong>: &#39;No&#39;}, inplace<strong>=</strong> <strong>True</strong>)</pre><p><strong>Data exploration in columns ‘Delivery_chrgs’.</strong></p><ul><li>If there are any missing values or NaN in column<strong> </strong>‘Delivery_chrgs’, It means there was no delivery charge for that order, we will fill the missing values with zero.</li></ul><pre><em># Filling NaN with zero, it means there is no charge of delivery</em><br>df[&#39;Delivery_chrgs&#39;]<strong>=</strong> df[&#39;Delivery_chrgs&#39;]<strong>.</strong>fillna(0)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4s5m6yfQ42aTbmmt4IyRaw.png" /></figure><p><strong>Summary of data:</strong></p><p>a data frame. describe() is a function that describes a data frame. Descriptive statistics exclude null values for the numerical column and include summary statistics such as central tendency, min, max, and shape of a dataset’s distribution. For categorical columns, there are summary options such as count, frequency, and so on.</p><pre><em># Lets check for summary of data</em><br>df<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3vjYRMOWd-X8NmAc-RIJw.png" /></figure><p><strong>By looking at the summary of the table we conclude that</strong></p><ul><li>The rate of the product ranges from Rs 70 to Rs 1500 which is quite okay, There are not such expensive items</li><li>The Maximum delivery charge is Rs 250 and the average charge is Rs 65</li><li>The average products review is 3.8 which is quite good</li><li>We could say that most of customers quantity of bought product are on average 3.</li></ul><p><strong>The data type of each column:</strong></p><ul><li>The function df.info() can be used to get information about a dataset. This will give you the titles of the columns as well as the number of non-null values in each column.</li></ul><pre><em># Lets look at the datatype </em><br>df<strong>.</strong> info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*U1Dq6eCFOE56mqJRQ1W_tw.png" /></figure><h4>EDA (Exploratory Data Analysis):</h4><ul><li>Examine the distribution of data.</li><li>Managing the dataset’s missing values (a most common issue with every dataset)</li><li>Taking care of the outliers</li><li>Duplicate data is removed, and categorical variables are encoded.</li><li>Scaling and Normalizing</li></ul><h4>Dropping the useless columns</h4><ul><li>The transaction id, customer id, and DOB would not help us to build the model so, we will drop it. Here we used axis=1, which means dropping columns.</li></ul><pre>df<strong>.</strong>drop([&#39;transaction_id&#39;,&#39;CustID&#39;,&#39;DOB&#39;], inplace<strong>=True</strong>,axis<strong>=</strong>1)</pre><p><strong>Missing Values Treatment:</strong></p><p>In the dataset, missing values are frequently represented as Nan, null, or None.</p><pre><em># Lets check for missing values </em><br>df<strong>.</strong>isnull()<strong>.</strong>sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*2D1ztemwBzV2LU7dk-9gjA.png" /></figure><p><em>Here we can see that there are missing values in Reviews and Income features.</em></p><p>The shape of data:</p><pre><em># lets check the shape </em><br>df<strong>.</strong>shape</pre><p>The data set contains (19504, 18) rows and columns respectively. Since the data is too large we can drop the NaN value from it. It wouldn&#39;t affect the data.</p><pre><em># Since our data are around 20,000 and we can drop NaN values, it wont affect the data, which less than 0.01%</em><br>df<strong>.</strong>dropna(inplace<strong>=True</strong>)</pre><h4>Data Visualization:</h4><p>Univariate Analysis:</p><p>Let&#39;s look at the target variable which is the “Return”</p><pre>sns<strong>.</strong>countplot(df[&#39;Return&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*jZP45v9HGhCQ01mxHjAywQ.png" /><figcaption>Target variables:</figcaption></figure><p><em>So it seems like most of the products wouldn&#39;t be returned, which is quite good for the FRESCO Retail. But Here data is imbalanced we have to balance it before going to build the model, otherwise, our model will be biased toward maximum data points.</em></p><p><strong><em>Product categories wise column:</em></strong></p><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(15,6))<br>sns<strong>.</strong>countplot(df[&#39;prod_cat_code&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIIhGet3aDhjbGT6l82B-w.png" /></figure><p><em>By looking at the graph we could say that maximum returns are from these two categories of footwear and clothing, or we could customers more likely to buy these products footwear, clothing, and kitchen &amp; home.</em></p><p><strong><em>Product sub_categries wise:</em></strong></p><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(15,6))<br>plt<strong>.</strong>xticks(rotation<strong>=</strong>90)<br>sns<strong>.</strong>countplot(df[&#39;prod_subcat_code&#39;],orient<strong>=</strong> &#39;horizontal&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEKZ_oxcJJlCUWfeiEiORw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*azJa-nzCNJ47HtvnV6oZhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*fllQ8WI0WNP7J38dL6uMeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*e87JwjoiFfQzjKcnM2YDWg.png" /></figure><p><em>The maximum Tax of the product is between 0 to 300.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*Uh2L2EfRmDbyOiYr83SgIA.png" /></figure><p><em>The maximum transaction is done through mobile payments and credit and debit cards.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*sodI2GmILRwAkAe4U6viEw.png" /></figure><p><em>The Maximum no. of products was bought online.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*3P3ADgLTLZgOuzOvwsbLlQ.png" /></figure><p><em>Customers are highly satisfied with the products.</em></p><p><strong>Bi- Variate analysis:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*mV6xpJPAG0_6acHnzzpC-A.png" /></figure><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(15,6))<br>plt<strong>.</strong>xticks(rotation<strong>=</strong>90)<br>sns<strong>.</strong>countplot(df<strong>.</strong>Month_code,hue<strong>=</strong>df<strong>.</strong>Return)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoN1o5eCwqgvmfJu9uB6tA.png" /></figure><p><em>The Months of January, May, October, and November are maximum returns products.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*0K8LIqGCcCprcacfCFHFhA.png" /></figure><p><em>Almost all product of rating 1 was returned.</em></p><pre><em># for the numerical features we plot pairs plot see the how the data points are located</em><br>sns<strong>.</strong>pairplot(df[[&#39;Rate&#39;,&#39;Amount&#39;,&#39;Tax&#39;,&#39;Delivery_chrgs&#39;,&#39;Income&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fekbILkMAzIChP1lCTTOCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UF3DlyDLNRNx5KXF71v_Ng.png" /></figure><h3>Handling categorical variables</h3><p>One can find many ways to handle categorical data. Some of the categorical data are,</p><ul><li><strong>Nominal data</strong> → are not in any order → <strong>OneHotEncoder</strong> is used in this case</li><li><strong>Ordinal data</strong> → are in order → <strong>LabelEncoder</strong> is used in this case.</li></ul><pre>df[&#39;Qty&#39;]<strong>=</strong>df[&#39;Qty&#39;]<strong>.</strong>astype(&#39;str&#39;)<br>df[&#39;Marital_status&#39;]<strong>=</strong> df[&#39;Marital_status&#39;]<strong>.</strong>astype(&#39;str&#39;)<br>df[&#39;Reviews&#39;]<strong>=</strong> df[&#39;Reviews&#39;]<strong>.</strong>astype(&#39;str&#39;)</pre><p>Here, we changed the data type of some features.</p><pre>Months <strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;Month_code&#39;],drop_first<strong>=True</strong>)</pre><pre>product_cat<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;prod_cat_code&#39;],drop_first<strong>=True</strong>)</pre><pre>product_subcat<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;prod_subcat_code&#39;],drop_first<strong>=True</strong>)</pre><pre>qty<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;Qty&#39;],drop_first<strong>=True</strong>)</pre><pre>payment_mode<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;Payment_mode&#39;],drop_first<strong>=True</strong>)</pre><pre>store_type<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;Store_type&#39;],drop_first<strong>=True</strong>)</pre><pre>City_code<strong>=</strong>  pd<strong>.</strong>get_dummies(df[&#39;city_code&#39;],drop_first<strong>=True</strong>)</pre><pre>gender<strong>=</strong>  pd<strong>.</strong>get_dummies(df[&#39;Gender&#39;],drop_first<strong>=True</strong>)</pre><pre>df[&#39;Education_code&#39;]<strong>.</strong>replace({&#39;Others&#39;:0,&#39;Basic&#39;:1 ,&#39;Graduation&#39;:2, &#39;Master&#39;:3,&#39;PhD&#39;:4}, inplace<strong>=True</strong>)</pre><pre>Profession<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;Profession_Code&#39;],drop_first<strong>=True</strong>)</pre><pre>reviews<strong>=</strong> pd<strong>.</strong>get_dummies(df[&#39;Reviews&#39;],drop_first<strong>=True</strong>)</pre><p>Now we will concrete all these converted dummies variables.</p><pre>df<strong>=</strong> pd<strong>.</strong>concat([df,Profession,gender,City_code,store_type,payment_mode,product_subcat,qty,Months,product_cat,reviews],axis<strong>=</strong>1)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc4fsz5T0wbaQ9gJQ89uyw.png" /></figure><p>Now we will drop the useless columns from a data frame.</p><pre><em># we have drop these varibles</em><br>df<strong>.</strong>drop([&#39;Month_code&#39;,&#39;prod_cat_code&#39;,&#39;prod_subcat_code&#39;,&#39;Qty&#39;,&#39;Payment_mode&#39;,&#39;Store_type&#39;,&#39;city_code&#39;,&#39;Gender&#39;,<br>        &#39;Education_code&#39;,&#39;Profession_Code&#39;, &#39;Reviews&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><h3>Features selections</h3><p>In machine learning, the purpose of feature selection is to discover the best set of characteristics that allows one to develop usable models of the phenomena being examined.</p><p>The following categories can be used to categorize feature selection strategies in machine learning:</p><ul><li>Correlation</li><li>chi2</li><li>Feature importance</li></ul><p><strong>Correlation:</strong></p><ul><li>The strength of a linear relationship between two numerical variables is represented by linear correlation. There is no propensity to vary along with the values of the second quantity if there is no correlation between the two variables.</li><li>The relationship is always between -1 and 1 where -1 denotes perfect negative linear correlation +1 denotes perfect positive linear correlation and zero denotes no linear</li></ul><pre>cont_col<strong>=</strong>df[[&#39;Rate&#39;,&#39;Amount&#39;,&#39;Tax&#39;,&#39;Delivery_chrgs&#39;,&#39;Income&#39;]]<br>corr<strong>=</strong> cont_col<strong>.</strong>corr()<br>corr</pre><pre><em># Heatmap</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(10,6))<br>sns<strong>.</strong>heatmap(corr,annot <strong>=</strong> <strong>True</strong>, cmap <strong>=</strong> &quot;RdYlGn&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*TC53P-wFZCvKbTsS-FsqrA.png" /></figure><p><strong>Checking Multicollinearity:</strong></p><p>In a regression model, multicollinearity occurs when two or more independent variables are significantly associated with one another.</p><p>In a regression model, this means that one independent variable may be predicted from another independent variable. Height and weight, for example, household income and water usage, automobile mileage and price, study time and leisure time, and so on.</p><pre>threshold<strong>=</strong>0.90<br><em># find and remove correlated features</em><br><strong>def</strong> correlation(dataset, threshold):<br>    col_corr <strong>=</strong> set()  <em># Set of all the names of correlated columns</em><br>    corr_matrix <strong>=</strong> dataset<strong>.</strong>corr()<br>    <strong>for</strong> i <strong>in</strong> range(len(corr_matrix<strong>.</strong>columns)):<br>        <strong>for</strong> j <strong>in</strong> range(i):<br>            <strong>if</strong> abs(corr_matrix<strong>.</strong>iloc[i, j]) <strong>&gt;</strong> threshold: <em># we are interested in absolute coeff value</em><br>                colname <strong>=</strong> corr_matrix<strong>.</strong>columns[i]  <em># getting the name of column</em><br>                col_corr<strong>.</strong>add(colname)<br>    <strong>return</strong> col_corr</pre><pre><br>correlation(cont_col,threshold)</pre><p>Here we found the “Tax” column was highly correlated with another independent feature, so we will drop the “tax” featured from the dataset.</p><pre>df<strong>.</strong>drop(&#39;Tax&#39;,inplace<strong>=True</strong>,axis<strong>=</strong>1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJVIZkZHrh8Ed6JfB-_FMw.png" /></figure><p><strong>Creating Independent and dependent variables.</strong></p><pre>X<strong>=</strong> df<strong>.</strong>drop(&#39;Return&#39;, axis<strong>=</strong>1) <em>#independent features</em><br>y<strong>=</strong> df[&#39;Return&#39;] <em>#depedndent featues</em></pre><p>Mapping the Target variables:</p><pre>y<strong>=</strong> y<strong>.</strong>replace({&#39;Yes&#39;:1,&#39;No&#39;:0})</pre><p><strong>Chi2 test:</strong></p><p>When establishing the relationship between categorical variables, the chi-square test is used. The difference between expected and observed frequencies in one or more frequency table categories is used to calculate it. A probability of zero implies that two categorical variables are dependent on each other, while a probability of one shows that they are completely independent.</p><p>The degrees of freedom are represented by the subscript c, the observed value is represented by O, and the predicted value is represented by E.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*k2Ha70rbu_eXweDE9awovg.png" /></figure><pre><br>chi_catcols<strong>=</strong> X[[&#39;Marital_status&#39;,<br>       &#39;Salaried&#39;, &#39;Self Employed&#39;, &#39;M&#39;, &#39;Bangalore&#39;, &#39;Chennai&#39;, &#39;Gurgaon&#39;,<br>       &#39;Hyderabad&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;, &#39;New Delhi&#39;, &#39;Pune&#39;, &#39;Vishakhapatnam&#39;,<br>       &#39;MBR&#39;, &#39;TeleShop&#39;, &#39;e-Shop&#39;, &#39;Credit Card&#39;, &#39;Debit Card&#39;,<br>       &#39;Mobile Payments&#39;, &#39;Audio and video&#39;, &#39;Bath&#39;, &#39;Cameras&#39;, &#39;Computers&#39;,<br>       &#39;DIY&#39;, &#39;Fiction&#39;, &#39;Furnishing&#39;, &#39;Kids&#39;, &#39;Kitchen&#39;, &#39;Mens&#39;, &#39;Mobiles&#39;,<br>       &#39;Non-Fiction&#39;, &#39;Personal Appliances&#39;, &#39;Tools&#39;, &#39;Women&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;,<br>       &#39;5&#39;, &#39;August&#39;, &#39;December&#39;, &#39;February&#39;, &#39;January&#39;, &#39;July&#39;, &#39;June&#39;,<br>       &#39;March&#39;, &#39;May&#39;, &#39;November&#39;, &#39;October&#39;, &#39;September&#39;, &#39;Books&#39;, &#39;Clothing&#39;,<br>       &#39;Electronics&#39;, &#39;Footwear&#39;, &#39;Home and kitchen&#39;, &#39;2.0&#39;, &#39;3.0&#39;, &#39;4.0&#39;,<br>       &#39;5.0&#39;]]</pre><p><strong>Chi score:</strong></p><ul><li>Before performing the Chi-Square test we have to make sure data is label encoded.</li></ul><p><strong><em>Define Hypothesis</em></strong></p><ul><li><em>Null Hypothesis (H0): Two variables are independent.</em></li><li><em>Alternate Hypothesis (H1): Two variables are not independent.</em></li></ul><pre><em>#chi score</em><br>chi_scores <strong>=</strong> chi2(chi_catcols,y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*b3dkXMSq5bM4E-A717dJVA.png" /></figure><pre><em>#here first array represents chi square values and second array represnts p-values</em><br>p_values <strong>=</strong> pd<strong>.</strong>Series(chi_scores[1],index <strong>=</strong> chi_catcols<strong>.</strong>columns)<br>p_values<strong>.</strong>sort_values(ascending <strong>=</strong> <strong>False</strong> , inplace <strong>=</strong> <strong>True</strong>)</pre><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(20,5))<br>p_values<strong>.</strong>plot<strong>.</strong>bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_Y2FzzOKXNAsLUKpKkLIg.png" /><figcaption>P-values plot</figcaption></figure><p>If p-values greater than 0.05, we will drop the columns.</p><p><strong><em>Columns dropping:</em></strong></p><p><em>A higher p-value, says that this variable is independent of the response and can not be considered for model training.</em></p><pre><em># we will drop values with higher p- values which more than 0.05</em><br>X<strong>.</strong>drop([&#39;Salaried&#39;, &#39;Self Employed&#39;, &#39;M&#39;, &#39;Bangalore&#39;, &#39;Chennai&#39;, &#39;Gurgaon&#39;,<br>       &#39;Hyderabad&#39;, &#39;Kolkata&#39;, &#39;Mumbai&#39;, &#39;New Delhi&#39;, &#39;Pune&#39;, &#39;Vishakhapatnam&#39;,<br>       &#39;MBR&#39;, &#39;TeleShop&#39;, &#39;e-Shop&#39;, &#39;Credit Card&#39;, &#39;Debit Card&#39;,<br>       &#39;Mobile Payments&#39;, &#39;Audio and video&#39;, &#39;Bath&#39;, &#39;Cameras&#39;, &#39;Computers&#39;,<br>       &#39;DIY&#39;, &#39;Mens&#39;, &#39;Mobiles&#39;],axis<strong>=</strong>1,inplace<strong>=True</strong>)</pre><h4>Feature importance</h4><p>A predictive model’s feature importance can be utilized to improve it. This can be accomplished by using the importance scores to determine which features to delete (those with the lowest scores) and which features to keep (those with the highest ratings) (highest scores). This is a sort of feature selection that can help to simplify the problem being modeled, speed up the modeling process (dimensionality reduction) and, in some situations, improve the model’s performance.</p><pre><em># Important feature using ExtraTreesRegressor</em><br><br><strong>from</strong> sklearn.ensemble <strong>import</strong> ExtraTreesClassifier<br>selection <strong>=</strong> ExtraTreesClassifier()<br>selection<strong>.</strong>fit(X, y)</pre><pre><em><br>#plot graph of feature importances for better visualization</em><br><br>plt<strong>.</strong>figure(figsize <strong>=</strong> (12,8))<br>feat_importances <strong>=</strong> pd<strong>.</strong>Series(selection<strong>.</strong>feature_importances_, index<strong>=</strong>X<strong>.</strong>columns)<br>feat_importances<strong>.</strong>nlargest(20)<strong>.</strong>plot(kind<strong>=</strong>&#39;barh&#39;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMucREXMVOHZGoJFxjKC5g.png" /><figcaption>Graph of Features important.</figcaption></figure><h3>Fitting model using Logistic Regression</h3><ul><li>Split the dataset into train and test set to prediction w.r.t X_test</li><li>Scaling is required in logistic regression</li><li>Oversampling with smote</li><li>Import model</li><li>Fit the data</li><li>Predict w.r.t X_test</li><li>In classification, we check accuracy Score</li><li>Plot error graph</li><li>Model comparison</li></ul><p><strong>Splitting the data:</strong></p><p>Taking a dataset and separating it into two subgroups is the technique. The training dataset is the first subset, which is used to fit the model. The second subset is not used to train the model; instead, the dataset’s input element is given to the model, which then makes predictions and compares them to the predicted values. The test dataset is the name given to the second dataset.</p><ul><li>Train Dataset: This is the data set that is used to fit the machine learning model.</li><li>Test Dataset: This dataset is used to assess how well a machine learning model fits.</li></ul><pre><em>#Split train-test data</em><br>X_train, X_test, y_train, y_test <strong>=</strong> train_test_split(X,y,test_size<strong>=</strong>0.30,random_state<strong>=</strong>0)</pre><p><strong>Scaling the training data:</strong></p><ul><li>Some machine learning algorithms are affected by feature scaling, while others are completely unaffected.</li><li>Machine learning algorithms like <a href="https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/?utm_source=blog&amp;utm_medium=feature-scaling-machine-learning-normalization-standardization">linear regression</a>, <a href="https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/?utm_source=blog&amp;utm_medium=feature-scaling-machine-learning-normalization-standardization">logistic regression</a>, <a href="https://www.analyticsvidhya.com/blog/2017/05/neural-network-from-scratch-in-python-and-r/?utm_source=blog&amp;utm_medium=feature-scaling-machine-learning-normalization-standardization">neural network</a>, etc.</li><li>Another scaling strategy is standardization, in which the values are centered around the mean with a unit standard deviation. As a result, the attribute’s mean becomes zero, and the resulting distribution has a unit standard deviation.</li></ul><p>Here’s the formula for standardization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/0*lLeUMn2Cnc920U-X.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/11/0*ZWn3jqvRDEM-W031.gif" /></figure><p>is the mean of the feature values and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/11/0*heuZs37OkDHfSG0k.gif" /></figure><p>is the standard deviation of the feature values. Note that in this case, the values are not restricted to a particular range.</p><pre><em>#### standarisation: We use the Standardscaler from sklearn library</em><br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler<br>scaler<strong>=</strong>StandardScaler()<br><em>### fit vs fit_transform</em><br>X_train_scaled<strong>=</strong>scaler<strong>.</strong>fit_transform(X_train) <em>#alway give parameter in fit_transform</em></pre><p><strong><em>Scaling the test data:</em></strong></p><ul><li>For, the test data we will only fo transform().</li><li>To get rid of overfitting of data</li></ul><pre>X_test_scaled<strong>=</strong>scaler<strong>.</strong>transform(X_test</pre><h4>SMOTE: Synthetic Minority Oversampling Technique</h4><p>SMOTE is an oversampling technique in which synthetic samples for the minority class are generated. This approach aids in overcoming the problem of overfitting caused by random oversampling. It concentrates on the feature space to produce new examples by interpolating between positive instances that are close together.</p><pre><em># import SMOTE oversampling and other necessary libraries </em><br><strong>from</strong> collections <strong>import</strong> Counter<br><strong>from</strong> imblearn.over_sampling <strong>import</strong> SMOTE<br><strong>import</strong> warnings<br>warnings<strong>.</strong>simplefilter(action<strong>=</strong>&#39;ignore&#39;, category<strong>=</strong>FutureWarning)<em># summarize class distribution</em><br>print(&quot;Before oversampling: &quot;,Counter(y_train))<br></pre><pre><em># define oversampling strategy</em><br>SMOTE <strong>=</strong> SMOTE()<br><br><em># fit and apply the transform</em><br>X_train_SMOTE, y_train_SMOTE <strong>=</strong> SMOTE<strong>.</strong>fit_resample(X_train_scaled, y_train)<br><br><em># summarize class distribution</em><br>print(&quot;After oversampling: &quot;,Counter(y_train_SMOTE))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*mcLIjLYF__VDsN7RBHqaKg.png" /></figure><p><strong>Logistic Regression model:</strong></p><p>Logistic regression is a “supervised machine learning” approach that can be used to model the likelihood of a specific class or occurrence. When the data is linearly separable and the result is binary or dichotomous, this method is applied.</p><p>Case 1: x1 has a predicted value of 0.2, which is less than the threshold, putting it in class 0.</p><p>Case 2: the predicted value for the point x2 is 0.6, which is higher than the threshold, indicating that x2 belongs to a class.</p><ul><li>The sigmoid function can be used to convert any anticipated probability value into a value between 0 and 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*iC0Dz2k-WaWkeKA9.jpg" /><figcaption>Image source <a href="https://dzone.com/articles/machinex-simplifying-logistic-regression">here</a></figcaption></figure><p><strong>Model Building and training:</strong></p><pre><em># Building the model</em><br><strong>from</strong> sklearn.linear_model <strong>import</strong> LogisticRegression<br>clf<strong>=</strong>LogisticRegression()<br>clf<strong>.</strong>fit(X_train_SMOTE,y_train_SMOTE)</pre><p><strong>Predicting the output:</strong></p><pre><em># predicting the model</em><br>y_pred<strong>=</strong>clf<strong>.</strong>predict(X_test_scaled)</pre><p><strong>Computing the accuracy:</strong></p><pre>cm<strong>=</strong>confusion_matrix(y_test,y_pred)<br>print(cm)<br>accuracy<strong>=</strong>accuracy_score(y_test,y_pred)<br>print(&#39;The Model accuracy is&#39;,accuracy)<br>report<strong>=</strong> classification_report(y_test,y_pred)<br>print(report)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*DFCAuaaxLi-o1IE9VG2i7w.png" /><figcaption>Model Evaluation</figcaption></figure><p>Plot the residual graphs:</p><pre>sns<strong>.</strong>distplot(y_test<strong>-</strong>y_pred)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*6d_6kEvKTZfNXhy65i_M2Q.png" /></figure><p><strong>K- Fold Cross-Validation:</strong></p><p>The entire data set is partitioned into k sets of about similar sizes in this resampling procedure. The model is trained on the remaining k-1 sets, with the first set serving as the test set. After fitting the model to the test data, the test error rate is computed.</p><p>The second iteration uses the second set as a test set, while the remaining k-1 sets are utilized to train the data and determine the error. This method is repeated for all k sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*wxmLaf_FQBqZ6Sja.jpg" /><figcaption>Image source <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)">here</a></figcaption></figure><p>Image Source: Wikipedia</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> cross_val_score<br>score<strong>=</strong> cross_val_score(clf,X,y,cv<strong>=</strong>10)<br>print(score)<br>np<strong>.</strong>mean(score)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*QTcnmxnXfnx9xNrLI0B8aw.png" /></figure><h3>Model2: Random Forest</h3><p>The random forest algorithm has the following steps:</p><p>Step 1: In a Random forest, n random records are chosen at random from a data collection of k records.</p><p>Step 2: For each sample, individual decision trees are built.</p><p>Step 3: Each decision tree produces a result.</p><p>Step 4: For classification and regression, the final output is based on Majority Voting or Averaging, accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*4UYiMTN-AtdNpJgT.jpg" /><figcaption>Image source <a href="https://www.analyticsvidhya.com/blog/2021/06/understanding-random-forest/">here</a></figcaption></figure><pre><em># building model by Random forest</em><br><strong>from</strong> sklearn.ensemble <strong>import</strong> RandomForestClassifier<br>classifier<strong>=</strong>RandomForestClassifier()<br>classifier<strong>.</strong>fit(X_train_SMOTE,y_train_SMOTE)</pre><p><strong>Predicting the Model 2:</strong></p><pre>y_pred<strong>=</strong>classifier<strong>.</strong>predict(X_test_scaled)</pre><p><strong>Confusion metrics:</strong></p><pre>cm<strong>=</strong>confusion_matrix(y_test,y_pred)<br>print(cm)<br>accuracy<strong>=</strong>accuracy_score(y_test,y_pred)<br>print(&#39;The Model accuracy is&#39;,accuracy)<br>report<strong>=</strong> classification_report(y_test,y_pred)<br>print(report)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*aFU_fV3uChRCQdxvsJyRSA.png" /></figure><p><em>If we compare the logistic model with random forest the accuracy and precision are quite much better than the logistic model. It means the random forest model is better for this data.</em></p><p><strong>You can find the code </strong><a href="https://github.com/rahkum96/FRESCO-RETAIL-PROJECT"><strong>here</strong></a></p><p>Follow me on LinkedIn:</p><p><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></p><p>GitHub:</p><p><a href="https://github.com/rahkum96">rahkum96 - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=226ae86f0ea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Potential Loan Defaulters Using Machine Learning in Python]]></title>
            <link>https://medium.com/@rahulsisodia06/laon-prediction-dataset-2a869aaae9a4?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a869aaae9a4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[loan-prediction]]></category>
            <category><![CDATA[loans]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 17:22:08 GMT</pubDate>
            <atom:updated>2025-01-20T18:58:41.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*sI9ORW1uDVlfJHCo.png" /></figure><h3>Problem Statement</h3><p>Predict the potential loan defaulters using the Machine Learning model.</p><p>The major aim of this notebook is to predict which of the customers will have their loan approved. I am going to use XGBoost model it for the prediction.</p><p>Make sure you have installed xgboost by-pip install xgboost in command line prompt or anaconda prompt</p><h3>1. Libraries 📕📗📘</h3><pre><strong>import</strong> numpy <strong>as</strong> np <em># linear algebra</em><br><strong>import</strong> pandas <strong>as</strong> pd <em># data processing</em><br><br><em>#ploting libraries</em><br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt <br><strong>import</strong> seaborn <strong>as</strong> sns<br><br><em>#relevant ML libraries</em><br><strong>from</strong> sklearn.preprocessing <strong>import</strong> LabelEncoder<br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br><strong>from</strong> sklearn.metrics <strong>import</strong> confusion_matrix, classification_report, accuracy_score,plot_confusion_matrix, plot_precision_recall_curve<br><br><em>#ML models</em><br><strong>from</strong> xgboost <strong>import</strong> XGBClassifier<br><br><strong>import</strong> warnings<br>warnings<strong>.</strong>simplefilter(action<strong>=</strong>&quot;ignore&quot;, category<strong>=</strong>FutureWarning)</pre><h3>2. Preprocessing and Data Analysis</h3><ul><li>Dataset link: <a href="https://github.com/rahkum96/Loan-Prediction-by-XGBoost-Model/blob/main/Loan%20Prediction_Training%20Data.csv">https://github.com/rahkum96/Loan-Prediction-by-XGBoost-Model/blob/main/Loan%20Prediction_Training%20Data.csv</a></li><li>We are storing the data in data frame Df and looking at the first 5 rows by using the head.</li></ul><pre><em># read in csv file as a DataFrame</em><br>df <strong>=</strong> pd<strong>.</strong>read_csv(&#39;Loan Prediction_Training Data.csv&#39;)<br><em># explore the first 5 rows</em><br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvTH9yh127sgJ4rw9fL42A.png" /></figure><p><strong>Setting Index</strong></p><ul><li>Here we will set the index as ID columns because it has a unique number.</li></ul><pre><em># Setting Id as index </em><br>df<strong>.</strong>set_index(&#39;Id&#39;, inplace<strong>=True</strong>)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YVhuKmJqKDk8OYPpL5b-A.png" /></figure><p><strong>Let&#39;s look at the shape of a dataset</strong></p><pre><em># Lets look at the shape of data</em><br>df<strong>.</strong>shape</pre><p><em>We total 252000 rows and 12 columns in the dataset, our Target feature is ‘Risk_Flag’</em></p><p><strong>Let&#39;s look at the data type of each column</strong></p><pre><em># lets see the features information</em><br>df<strong>.</strong>info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*wCa3gMhSvSRoN2ypz93juA.png" /></figure><h4><em>Categorical columns are:</em></h4><ul><li><em>Married/Single</em></li><li><em>House_Ownership</em></li><li><em>Car_Ownership</em></li><li><em>Profession</em></li><li><em>CITY</em></li><li><em>STATE</em></li></ul><p><strong>Summary of data</strong></p><pre><em># summary of data</em><br>df<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYMWiRg18kSCoXG3gOEPAQ.png" /><figcaption>Summary of dataset</figcaption></figure><p><strong>Missing values:</strong></p><pre><em># checking missing values</em><br>df<strong>.</strong>isnull()<strong>.</strong>sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*CF-CAXUjQI2pgU2jGy6YlQ.png" /></figure><p><em>Okay, we do not have any missing values here.</em></p><h3>3. Data visualization 📊</h3><p>Firstly we need to split our data into categorical and numerical data.</p><p><strong>Creating Categorical and Numerical columns in the dataset:</strong></p><pre><em># Categorical features:</em><br>cat_cols<strong>=</strong> df[[&#39;Married/Single&#39;, &#39;House_Ownership&#39;,&#39;Car_Ownership&#39; ,&#39;Profession&#39;, &#39;CITY&#39;, &#39;STATE&#39;]]<br><br><em># numericasl features</em><br>num_cols<strong>=</strong> df[[&#39;Income&#39;, &#39;Experience&#39;,&#39;Age&#39;,&#39;CURRENT_JOB_YRS&#39;,&#39;CURRENT_HOUSE_YRS&#39;]]</pre><h3>3.1 Univariate analysis:</h3><ul><li>Here we will visualize the data of only one feature, and try to understand the pattern of data</li></ul><p>We’ll start with an independent variable that also happens to be our target variable. We’ll use a bar chart to analyze this category variable, as illustrated below. The bar chart illustrates that out of 252000 persons, 30996 (about 0.123 percent) were authorized for a loan.</p><pre><em># lets visualize the Target variables first,</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(6,6))<br>sns<strong>.</strong>countplot(df[&#39;Risk_Flag&#39;])<br>plt<strong>.</strong>xlabel(&#39;Risk flag&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&#39;count&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>title(&quot;Count of Risk_flag&quot;, fontsize<strong>=</strong>20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*2-HL1hA4j87a-4VUZVZMrg.png" /></figure><p>By looking at the plot we could say that no. of risk flags are pretty much higher than an approved loan. It seems like our dataset is Imbalance, let&#39;s look at the counts below, we will count value_counts()</p><pre>df[&#39;Risk_Flag&#39;]<strong>.</strong>value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*2BxYeBspUGvhulEfaq3izA.png" /></figure><h3>Analysis of Numerical variables</h3><pre><em>#Let&#39;s plot our Numeric data:</em><br><strong>for</strong> i <strong>in</strong> num_cols:<br>    sns<strong>.</strong>histplot(num_cols[i])<br>    plt<strong>.</strong>title(i)<br>    plt<strong>.</strong>figure(figsize<strong>=</strong>(8,10))<br>    sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*nO1ETbHxQa-5j-OST94UmA.png" /></figure><h3>Analysis of categorical variables:</h3><pre><em>#Let&#39;s plot our categorical data:</em><br><strong>for</strong> i <strong>in</strong> cat_cols:<br>    sns<strong>.</strong>countplot(cat_cols[i])<br>    plt<strong>.</strong>title(i)<br>    sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>    plt<strong>.</strong>figure(figsize<strong>=</strong>(10,8))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*j9VzUP0-Xk9M5QVjoc7aiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtsstePFcuk-RFHfejrdMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzLAwtvk9eqbwvQXcGgIkw.png" /></figure><p>It can be concluded from the below bar plots that in our observed data:</p><ul><li>90% of loan applicants are single in the training dataset.</li><li>Nearly 90% are who rented a house</li><li>About 75%- 80% have No car ownership</li></ul><h3>3.2 Bivariate Analysis</h3><p>Bivariate analysis is finding some kind of empirical relationship between two variables. Specifically the dependent vs independent Variables</p><h3>Categorical Independent Vs Target</h3><pre><em># Single/Married vs Risk_Flag</em><br>sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>plt<strong>.</strong>figure(figsize<strong>=</strong>(10,6))<br>sns<strong>.</strong>countplot(&#39;Married/Single&#39;,hue<strong>=</strong>&#39;Risk_Flag&#39;,data<strong>=</strong>df)<br>plt<strong>.</strong>title(&#39;Laon approval for Married/Single&#39;, fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;Married/Singl&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&quot;count&quot;,fontsize<strong>=</strong>16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*R2L1Egk0WJNHmcdrG6x8rQ.png" /></figure><pre><em># House_Ownership vs Risk_Flag</em><br>sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>plt<strong>.</strong>figure(figsize<strong>=</strong>(10,6))<br>sns<strong>.</strong>countplot(&#39;House_Ownership&#39;,hue<strong>=</strong>&#39;Risk_Flag&#39;,data<strong>=</strong>df)<br>plt<strong>.</strong>title(&#39;Laon approval for House_Ownership&#39;, fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;House_Ownership&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&quot;count&quot;,fontsize<strong>=</strong>16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YiQY3cUPcHVykBjdMbzcPQ.png" /></figure><pre><em># Car_Ownership vs Risk_Flag</em><br>sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>plt<strong>.</strong>figure(figsize<strong>=</strong>(10,6))<br>sns<strong>.</strong>countplot(&#39;Car_Ownership&#39;,hue<strong>=</strong>&#39;Risk_Flag&#39;,data<strong>=</strong>df)<br>plt<strong>.</strong>title(&#39;Laon approval for Car_Ownership&#39;, fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;Car_Ownership&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&quot;count&quot;,fontsize<strong>=</strong>16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNu_Z5BZSO9iMG72dfJr3g.png" /></figure><pre><em># Experience vs Risk_Flag</em><br>sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>plt<strong>.</strong>figure(figsize<strong>=</strong>(20,6))<br>sns<strong>.</strong>countplot(&#39;Experience&#39;,hue<strong>=</strong>&#39;Risk_Flag&#39;,data<strong>=</strong>df)<br>plt<strong>.</strong>title(&#39;Laon approval for Experience&#39;, fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;Experience&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&quot;count&quot;,fontsize<strong>=</strong>16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc0AFah0plMfNkzo5Ze2nw.png" /></figure><pre><em># CURRENT_JOB_YRS vs Risk_Flag</em><br>sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>plt<strong>.</strong>figure(figsize<strong>=</strong>(20,6))<br>sns<strong>.</strong>countplot(&#39;CURRENT_JOB_YRS&#39;,hue<strong>=</strong>&#39;Risk_Flag&#39;,data<strong>=</strong>df)<br>plt<strong>.</strong>title(&#39;Laon approval for CURRENT_JOB_YRS&#39;, fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;CURRENT_JOB_YRS&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&quot;count&quot;,fontsize<strong>=</strong>16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpmfSp3Z41KLMGfvGwJCAg.png" /></figure><pre><em># CURRENT_HOUSE_YRS vs Risk_Flag</em><br>sns<strong>.</strong>set(style<strong>=</strong>&quot;whitegrid&quot;)<br>plt<strong>.</strong>figure(figsize<strong>=</strong>(20,6))<br>sns<strong>.</strong>countplot(&#39;CURRENT_HOUSE_YRS&#39;,hue<strong>=</strong>&#39;Risk_Flag&#39;,data<strong>=</strong>df)<br>plt<strong>.</strong>title(&#39;Laon approval for CURRENT_HOUSE_YRS&#39;, fontsize<strong>=</strong>20)<br>plt<strong>.</strong>xlabel(&#39;CURRENT_HOUSE_YRS&#39;,fontsize<strong>=</strong>16)<br>plt<strong>.</strong>ylabel(&quot;count&quot;,fontsize<strong>=</strong>16)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTxb6K5dNI1G8YfQvtW6OQ.png" /></figure><h3>Visualizing correlation via Heatmap</h3><pre><em># Lets see the corelartion between all te numerical variables </em><br>df<strong>.</strong>corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrSLZUut6VrRHeg8a-kcWw.png" /></figure><pre><em>#plotting the correlation matrix</em><br>sns<strong>.</strong>heatmap(df<strong>.</strong>corr(),cmap<strong>=</strong>&#39;cubehelix_r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*E-ud2e04sg6kjYmNs9kGEQ.png" /></figure><p><em>We can see that </em><em>CURRENT_JOB_YRS has correlated with </em><em>Experience (a positive correlation of 0.60). Since we are not using a statistical model, we do not have to check for multicollinearity.</em></p><p><em>If We are using a statistical model like,</em><em>Logitic regressionwe need to remove independent features which are highly correlated to each other.</em></p><h3>4. Independent and Dependent variables</h3><p>First, we’ll partition our data into two variables: X, which represents the attributes we described before, and y, which represents the Risk_Flag , which is the target value we want to predict.</p><pre><em># Independet variables </em><br>X<strong>=</strong> df<strong>.</strong>iloc[:,:<strong>-</strong>1]<br><br><em># Dependent variables </em><br>y<strong>=</strong> df<strong>.</strong>iloc[:,<strong>-</strong>1]</pre><h3>Dropping the features</h3><p>We know that the columns City and State which is not future help in the prediction of the model, we would remove these two features from Independent variables by using drop</p><pre><em># Dropping columns city and state from independet variables<br></em>X<strong>.</strong>drop([&#39;CITY&#39;,&#39;STATE&#39;],inplace<strong>=True</strong>,axis<strong>=</strong>1)</pre><pre><em># Now lets verify it by using head </em><br>X<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mSbQbwD-94anhRK7qKmFw.png" /></figure><h3>Feature Engineering</h3><p>We know the machine learning model doesn&#39;t understand the text, we need to convert columns to numeric by using pandas get_dummies()</p><ul><li>One_hot_encoding will do for the nominal data: We cannot Rank the data, Example like zip-code</li><li>Lavel_encoding we do for ordinal data: we can give a rank, example like Grade, education status</li></ul><p>We doing here One_hot_encoding Because machine learning algorithms understand only numerical data, and we have some of the predictors are categorical type data we will use get_dummies()</p><pre><em># COnverting to dummies variables </em><br>X<strong>=</strong> pd<strong>.</strong>get_dummies(X, columns<strong>=</strong>[&#39;Married/Single&#39;,&#39;House_Ownership&#39;,&#39;Car_Ownership&#39;,&#39;Profession&#39;],drop_first<strong>=True</strong>)<br><em># Now lets verfy it.</em><br>X<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11eSFToITDXPFW_xk0tnDg.png" /></figure><h3>5. Train Test Split</h3><p>We will split the data into training and testing sets, here we considered 30% of data for Testing.</p><pre><em># Splitting the training and test data</em><br>X_train,X_test,y_train,y_test<strong>=</strong>train_test_split(X,y,test_size<strong>=</strong>0.3,random_state<strong>=</strong>42)</pre><h3>6. Building an XGBoost model</h3><p>The XGBoost Advantage</p><p>I’ve always admired the boosting capabilities that this algorithm infuses in a predictive model. When I explored more about its performance and science behind its high accuracy, I discovered many advantages:</p><h4>Regularization:</h4><ul><li>Standard GBM implementation has no regularization like XGBoost, therefore it also helps to reduce overfitting.</li><li>XGBoost is also known as a ‘regularized boosting‘ technique.</li></ul><pre><em># Training the model</em><br><br>XGB <strong>=</strong> XGBClassifier(use_label_encoder<strong>=False</strong>)<br>XGB<strong>.</strong>fit(X_train, y_train)<br><br><em># Predicting the model</em><br>y_predict <strong>=</strong> XGB<strong>.</strong>predict(X_test)<br><br><em>#  prediction Summary by species</em><br>print(classification_report(y_test, y_predict))<br><br><em># Accuracy score</em><br>XGB_SC <strong>=</strong> accuracy_score(y_predict,y_test)<br>print(f&quot;{round(XGB_SC<strong>*</strong>100,2)}% Accurate&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*TtP5FxcnXwxCx_EKJfS_Zg.png" /></figure><p><em>The accuracy of the model is quite good, but it is not performing well with the person who approved the loan(1). This is because our dataset was completely imbalanced. Here we will do try to do hyperparameter tuning.</em></p><p><strong>Confusion metrics:</strong></p><pre><em># Confusion matrix</em><br>print(confusion_matrix(y_test,y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*nnrgYDSDO-0j7JqHhz5vtg.png" /></figure><pre><em># Plotting the confusion matrics</em><br>plot_confusion_matrix(XGB,X_test,y_test,values_format<strong>=</strong>&#39;d&#39;,display_labels<strong>=</strong>[&#39;not approved&#39;,&#39;approved&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*FE3gysZkrpNkGEk0hLTGRw.png" /></figure><p><em>People who did not approve loans (99%) were correctly classified. but not model not performing well with people who had approved the loan, only(14%) correctly classified. XGBoost has a parameter that </em><em>scale_pos_weight that helps with imbalanced data. we try to improve the accuracy by using cross-validation.</em></p><p><em>Now we will evaluate the model since this dataset is completely imbalanced so we will get accuracy by </em><em>roc_auc_score.</em></p><pre><strong>from</strong> sklearn.metrics <strong>import</strong> roc_auc_score<br>print(&#39;The accuracy of model is:&#39;, roc_auc_score(y_test,y_predict))</pre><pre>#The accuracy of model is: 0.5649486095677779</pre><h3>6.1 XGBoost Parameters</h3><h4>scale_pos_weight [default=1]</h4><ul><li>A value greater than 0 should be used in case of high-class imbalance as it helps in faster convergence.</li></ul><p>Since our data is too large, if we do GridsearchCv, it will take time. If you want to try with hyperparameter tunning you could try it. Here I am using it only scale_pos_weight to make data balance.</p><pre><em># find the value of ``scale_pos_weight``</em><br>scale_pos_weight<strong>=</strong>len(y[y<strong>==</strong>0])<strong>/</strong>len(y[y<strong>==</strong>1])<br>scale_pos_weight</pre><h3>6.2 Building the XGBoost model with scale_pos_weight.</h3><pre>XGB <strong>=</strong> XGBClassifier(use_label_encoder<strong>=False</strong>,scale_pos_weight<strong>=</strong>7)<br><br><em># Fitting the model</em><br>XGB<strong>.</strong>fit(X_train, y_train)<br><br><em># Predicting the model</em><br>y_predict <strong>=</strong> XGB<strong>.</strong>predict(X_test)<br><br><em>#  prediction Summary by species</em><br>print(classification_report(y_test, y_predict))<br><br><em># Accuracy score</em><br>XGB_SC <strong>=</strong> accuracy_score(y_predict,y_test)<br>print(f&quot;{round(XGB_SC<strong>*</strong>100,2)}% Accurate&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*LVdqpwwyfixtTIam_GSenA.png" /></figure><p><strong>Confusion metrics:</strong></p><pre><em># Priting the confusion matrix</em><br>print(confusion_matrix(y_test,y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*OMQUidoBmNnMIYy11SqNvA.png" /></figure><pre><em># Plotting the confusion matrics</em><br>plot_confusion_matrix(XGB,X_test,y_test,values_format<strong>=</strong>&#39;d&#39;,display_labels<strong>=</strong>[&#39;not approved&#39;,&#39;approved&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*cjqWDYKad_dlXom9FeBpyg.png" /></figure><p><em>People who did not approve loans (83%) were correctly classified. And also our model is performing well with people who had approved the loan,(80%) correctly classified.</em></p><pre><em># Roc_auc score </em><br>print(&#39;The accuracy of model is:&#39;, roc_auc_score(y_test,y_predict))</pre><pre>#The accuracy of model is: 0.8167016919556359</pre><p><em>The accuracy of the model is improved significantly from 56 % to 81%, since our dataset is Imbalance we have to check accuracy by using roc_auc_score.</em></p><p><strong>Precision recall curve:</strong></p><pre>plot_precision_recall_curve(XGB,X_test,y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*4igSeUXqRIra4LnRJfvEGQ.png" /></figure><h3>7. Conclusion</h3><ul><li>We performed exploratory data analysis on the dataset’s features to see how they are distributed.</li><li>We used charts to do bivariate and multivariate analysis to examine how they impacted each other’s properties.</li><li>Our dataset was Imbalanced we used the XGBoost parameter scale_pos_weight to make data balanced.</li><li>We improved accuracy by using scale_pos_weight from 56% to 81%, since the data was imbalanced we used roc_auc_score for the accuracy.</li><li>The final model accuracy is around 82%.</li></ul><p><strong>Follow me on LinkedIn</strong></p><p><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></p><p><strong>GitHub:</strong></p><p><a href="https://github.com/rahkum96">rahkum96 - Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a869aaae9a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telco Churn Analysis and Modeling in Pyhon]]></title>
            <link>https://medium.com/@rahulsisodia06/telco-churn-analysis-and-modeling-a3c5f408bd9b?source=rss-8d0e847c9dca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3c5f408bd9b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[telco]]></category>
            <dc:creator><![CDATA[Rahul Sisodia]]></dc:creator>
            <pubDate>Mon, 29 Nov 2021 12:10:56 GMT</pubDate>
            <atom:updated>2025-01-20T18:53:51.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*JgifbLhsG2eutLK3" /><figcaption>Image source <a href="https://www.ibm.com/blogs/business-partners/ibm-telco-network-cloud-ecosystem/">here</a></figcaption></figure><p><strong>Problem Statement</strong></p><p>There are promotional charges called Acquisition Cost and Retention Cost in a telco company. The cost of acquiring new consumers is referred to as acquisition cost. Meanwhile, the expense of retaining existing clients is known as Retention Cost.</p><p>We are frequently inaccurate in our predictions of which customers would churn and which ones will stay due to human limitations. As a result, the allocation of money may be incorrect, resulting in a higher amount of funds being issued.</p><p>Furthermore, some sources claim that the acquisition cost is 5 times higher than the retention cost. If we anticipate a client who will churn incorrectly, but it turns out that we predicted a customer who will stay, we will have to spend more than we should.</p><h4>Goal</h4><p>Machine Learning has a goal so that cost allocation can be done as precisely as possible.</p><p>Make sure you have installed xgboost by- pip install xgboost in command line prompt or anaconda prompt.</p><pre><em>#Importing the libraries</em><br><strong>import</strong> pandas <strong>as</strong> pd <br><strong>import</strong> numpy <strong>as</strong> np <br><strong>import</strong> xgboost <strong>as</strong> xgb <br><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split <br><strong>from</strong> sklearn.metrics <strong>import</strong> roc_auc_score, balanced_accuracy_score, make_scorer <br><strong>from</strong> sklearn.model_selection <strong>import</strong> GridSearchCV <br><strong>from</strong> sklearn.metrics <strong>import</strong> confusion_matrix, plot_confusion_matrix <br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> seaborn <strong>as</strong> sns <br>pd<strong>.</strong>set_option(&#39;display.max_columns&#39;, 500) </pre><h3>1. Import the dataset</h3><p>Now we will import the data set from <a href="https://community.ibm.com/community/user/businessanalytics/blogs/steven-macko/2019/07/11/telco-customer-churn-1113">https://community.ibm.com/community/user/businessanalytics/blogs/steven-macko/2019/07/11/telco-customer-churn-1113</a></p><pre><em># load the dataset in df and lest look at the first 5 rows of df</em><br>df<strong>=</strong> pd<strong>.</strong>read_excel(&#39;Telco_customer_churn.xlsx&#39;)<br>df<strong>.</strong>head()</pre><p>We imported the data and stored it in df Data Frame.</p><h3>Executive Summary</h3><p>Telco Co. provided select, historical data on 7,043 customers including an indicator as to whether each customer churned. After analyzing and transforming the data, we optimized several classification models. Each model was trained on 75% of the historical data and then asked to predict churn scores on the remaining 25% of test data. Each model was compared with the previous best model with model XG Boost performing the best</p><pre><em># Lets look at the shape of dataset</em><br>df<strong>.</strong>shape</pre><pre><em># Lets describe the dataset</em><br>df<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FNBMJgshj2ghMikOvoI5A.png" /><figcaption>Data Summary</figcaption></figure><pre><em># Lets look at the data type of each columns in dataset</em><br>df<strong>.</strong>info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*VI04mctFUHbR5ywMEt2MUw.png" /><figcaption>Data information</figcaption></figure><p>So, the Df dataset contains 7043 rows, 33 columns</p><h3>2. Data Pre-processing</h3><p>People already left the Telco company so, we will remove these columns from the data set.</p><pre><em># Removing these columns so, we did axis=1, and inplace= True, means not making the copy of dataset</em><br>df<strong>.</strong>drop([&#39;Churn Reason&#39;,&#39;CLTV&#39;,&#39;Churn Score&#39;,&#39;Churn Label&#39;], axis<strong>=</strong>1, inplace<strong>=</strong> <strong>True</strong>)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22FTeDkzNXI110LeUU_kLw.png" /><figcaption>After Removing garbage columns</figcaption></figure><p>Some of the columns contain only single values which From the data frame above, several columns have one unique value, namely the column [Count, Country, State]. In addition, I will not use the CustomerID column because the customerID does not determine the probability that someone will churn or not.</p><blockquote>Zip code, Lat Long, Latitude, Longitude will also be deleted. I won’t use it to build Machine Learning.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWYPd0sHUYdeBCZg17t2cg.png" /></figure><pre>df<strong>.</strong>drop([&#39;Count&#39;,&#39;City&#39;,&#39;Country&#39;,&#39;State&#39;,&#39;CustomerID&#39;,&#39;Zip Code&#39;, &#39;Lat Long&#39;, &#39;Latitude&#39;, &#39;Longitude&#39;],<br>       axis<strong>=</strong>1, inplace<strong>=</strong> <strong>True</strong>)<br><em># Lets see first 5 rows </em><br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hl4euHMtX5mkY0te5Af53g.png" /></figure><pre><em># Replacing the space from column name </em><br>df<strong>.</strong>columns<strong>=</strong> df<strong>.</strong>columns<strong>.</strong>str<strong>.</strong>replace(&#39; &#39;,&#39;_&#39;) <em>#replacing space with undescore</em><br>df<strong>.</strong>columns</pre><pre><em># Now replacing white spaces with underscore</em><br>df<strong>.</strong>replace(&#39; &#39;, &#39;_&#39;, regex<strong>=True</strong>, inplace <strong>=True</strong>)<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*on53XERuE4Kg-GKEAiTRpg.png" /></figure><p><strong>Checking for missing values</strong></p><pre><em># checking missing values </em><br>df<strong>.</strong>isnull()<strong>.</strong>sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*tacHfHFfyvGyyQup3DHrxA.png" /><figcaption>Missing values</figcaption></figure><p>We do not find any missing values</p><p><strong>Exploring the Columns in DataFrame:</strong></p><pre><em># Lets look at the column of df[&#39;Total_Charges&#39;]</em><br>df[df[&#39;Total_Charges&#39;]<strong>==</strong>&quot;_&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAVr0eCnixc08DTSTycxRQ.png" /></figure><pre><em># replacing the colum Total_Charges with zero</em><br>df[&#39;Total_Charges&#39;]<strong>=</strong> np<strong>.</strong>where(df[&#39;Total_Charges&#39;]<strong>==</strong>&quot;_&quot;,0,df[&#39;Total_Charges&#39;])</pre><p><strong>Changing the data type of column Total_Charges</strong></p><pre><em># lets change the datatype of column Total_Charges to numeric</em><br>df[&#39;Total_Charges&#39;]<strong>=</strong> pd<strong>.</strong>to_numeric(df[&#39;Total_Charges&#39;])<br>df[&#39;Total_Charges&#39;]<strong>.</strong>dtype</pre><h3>3. EDA</h3><p>Exploratory data analysis is the preliminary examination of data to uncover links between measurements in the data and to gain insight into trends, patterns, and interactions among distinct entities contained in the data set using statistics and visualization tools (EDA).</p><h3>3.1 Univariate analysis:</h3><p>Because uni means one and variate means variable, there is only one dependable variable in univariate analysis. The goal of a univariate analysis is to derive data, characterize and summarise it, and examine any patterns that may exist. It investigates each variable separately in a dataset. There are two types of variables that can be used: categorical and numerical.</p><p>Central Tendency (mean, mode, and median), Dispersion (range, variance), Quartiles (interquartile range), and Standard deviation are some of the patterns that may be easily discovered using univariate analysis.</p><pre>df[&#39;Churn_Value&#39;]<strong>.</strong>value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*CehWAf3UtWJBBL4p5J57SA.png" /></figure><p><strong>Let&#39;s visualize the target variable</strong></p><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(10,5))<br>plt<strong>.</strong>pie(df[&#39;Churn_Value&#39;]<strong>.</strong>value_counts(), labels<strong>=</strong>df[&#39;Churn_Value&#39;]<strong>.</strong>unique(), autopct<strong>=</strong>&#39;%.2f%%&#39;)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*N6XIm8l4JzqALs_lJ25LZw.png" /><figcaption>Pie chart: Target Variable</figcaption></figure><p>By looking at columns df[‘Churn_Value’] we conclude that data are imbalance, we have to handle the imbalance data before building the machine learning model</p><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(5,5))<br>sns<strong>.</strong>countplot(df<strong>.</strong>Gender)<br>plt<strong>.</strong>title(&#39;Male counts Vs female count &#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*BiQpk4SLicLXphVzD5wYJA.png" /></figure><pre>sns<strong>.</strong>histplot(df<strong>.</strong>Monthly_Charges)<br>plt<strong>.</strong>title(&#39;Histogram of Monthly_Charges&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*ibSEIjkFfKx9XFMvpxMBUg.png" /></figure><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(5,5))<br>sns<strong>.</strong>countplot(df<strong>.</strong>Senior_Citizen)<br>plt<strong>.</strong>title(&#39;Bar plot of Senior_Citizen &#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*DCqq5_ARJyen_x4cb62IUg.png" /></figure><h3>3.2 Bivariate Analysis</h3><p>There are two variables here, as bi means two and variate imply variable. The study is focused on the root of the problem as well as the relationship between the two variables. Bivariate analysis is classified into three types.</p><ul><li><strong>Bivariate Analysis of two Numerical Variables </strong>(Numerical-Numerical) we do <strong>Scatter plot</strong>, <strong>Correlation.</strong></li><li><strong>Bivariate Analysis of one numerical and one categorical variable</strong> (Numerical-Categorical), we do <strong>ANOVA</strong></li><li><strong>Bivariate Analysis of two categorical Variables</strong> (Categorical-Categorical), we do <strong>Chi2 Test.</strong></li></ul><pre><em># column Senior_Citizen</em><br>df[&#39;Senior_Citizen&#39;]<strong>.</strong>value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*83Xdbv_EdmNRl0DlgogLGw.png" /></figure><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(8,6))<br>sns<strong>.</strong>catplot(x<strong>=</strong>&#39;Gender&#39;, hue<strong>=</strong>&#39;Churn_Value&#39;, col<strong>=</strong>&#39;Senior_Citizen&#39;, kind<strong>=</strong>&#39;count&#39;, data<strong>=</strong>df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InBByYVONtMIHMgwS6GsCQ.png" /></figure><p>From the visualization above, we can see that the churn and retain ratio for senior citizens, both male, and female is almost the same. Likewise, the churn and retain ratio for non-senior citizens. But if we look, the churn ratio has increased in senior citizens when compared to non-senior citizens.</p><pre>by_gender_senior <strong>=</strong> df<strong>.</strong>groupby([&#39;Senior_Citizen&#39;, &#39;Gender&#39;])[&#39;Churn_Value&#39;]<strong>.</strong>value_counts(normalize<strong>=True</strong>)<strong>.</strong>to_frame()<strong>.</strong>rename(columns<strong>=</strong>{&#39;Churn_Value&#39;: &#39;Ratio&#39;})<strong>.</strong>reset_index()<strong>.</strong>sort_values(&#39;Senior_Citizen&#39;)<br>by_gender_senior</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*uBiP5e3f1Ya-hCCoXEZd1A.png" /></figure><pre>sns<strong>.</strong>catplot(x<strong>=</strong> &#39;Gender&#39;, hue<strong>=</strong> &#39;Churn_Value&#39;,col<strong>=</strong>&#39;Partner&#39;, kind<strong>=</strong> &#39;count&#39;, data<strong>=</strong> df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KElJ0M_0d5jFwUMBeCOKw.png" /></figure><p>From the visualization above, both females and males who do not have a partner are more likely to churn.</p><pre>sns<strong>.</strong>catplot(x<strong>=</strong>&#39;Payment_Method&#39;, hue<strong>=</strong>&#39;Churn_Value&#39;, kind<strong>=</strong>&#39;count&#39;, data<strong>=</strong>df)<br>plt<strong>.</strong>xticks(rotation<strong>=</strong>45)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*zP3O6rm7oTOorhFIL6PotA.png" /></figure><pre>pd<strong>.</strong>crosstab(df[&#39;Payment_Method&#39;], df[&#39;Churn_Value&#39;], normalize<strong>=</strong>0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*Z7Bted2eGsF3IbtjotFUsg.png" /></figure><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(16,5))<br>plt<strong>.</strong>subplot(1,2,1)<br>plt<strong>.</strong>title(&#39;Monthly Charge distribution&#39;)<br>sns<strong>.</strong>distplot(df[df[&#39;Churn_Value&#39;] <strong>==</strong> 1][&#39;Monthly_Charges&#39;], label<strong>=</strong>&#39;Churn&#39;)<br>plt<strong>.</strong>subplot(1,2,2)<br>plt<strong>.</strong>title(&#39;Monthly Charge distribution Split by Gender&#39;)<br>sns<strong>.</strong>distplot(df[(df[&#39;Churn_Value&#39;] <strong>==</strong> 1) <strong>&amp;</strong> (df[&#39;Gender&#39;] <strong>==</strong> &#39;Male&#39;)][&#39;Monthly_Charges&#39;], label<strong>=</strong>&#39;Male&#39;)<br>sns<strong>.</strong>distplot(df[(df[&#39;Churn_Value&#39;] <strong>==</strong> 1) <strong>&amp;</strong> (df[&#39;Gender&#39;] <strong>==</strong> &#39;Female&#39;)][&#39;Monthly_Charges&#39;], label<strong>=</strong>&#39;Female&#39;)<br>plt<strong>.</strong>legend()<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yi_1eq3KuUT9MxNq6IRM6Q.png" /></figure><h3><strong>4. Creating an Independent and dependent dataset</strong></h3><pre><em># Creating independent and depedent variable </em><br>X<strong>=</strong> df<strong>.</strong>iloc[:,:<strong>-</strong>1] <em>#Independent variable </em><br>y<strong>=</strong> df[&#39;Churn_Value&#39;] <em>## Dependent variable</em><br>X<strong>.</strong>head()</pre><h3>5. Feature Engineering</h3><ul><li>One_hot_encoding will do for the nominal data: We cannot Rank the data, Example like zip-code</li><li>Lavel_encoding we do for ordinal data: we can give a rank, example like Grade, education status</li></ul><p>We doing here <strong>One_hot_encoding</strong> Because machine learning algorithms understand only numerical data, and we have some of the predictors are categorical type data we will use get_dummies()|</p><pre>X_encoded<strong>=</strong> pd<strong>.</strong>get_dummies(X,columns<strong>=</strong>[&#39;Gender&#39;,&#39;Senior_Citizen&#39;,&#39;Partner&#39;,&#39;Dependents&#39;,&#39;Phone_Service&#39;,<br>                                    &#39;Multiple_Lines&#39;,&#39;Internet_Service&#39;,&#39;Online_Security&#39;,&#39;Online_Backup&#39;,<br>                                    &#39;Device_Protection&#39;,&#39;Tech_Support&#39;,&#39;Streaming_TV&#39;,&#39;Contract&#39;,&#39;Paperless_Billing&#39;,<br>                                    &#39;Payment_Method&#39;,&#39;Streaming_Movies&#39;])</pre><pre># Creating copy and stored in X variables</pre><pre>X<strong>=</strong>X_encoded<strong>.</strong>copy()<br>X<strong>.</strong>shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*0FKySrgmaG5c_Np1V0LOzg.png" /></figure><h3>6. Building an XGBoost model</h3><h4>The XGBoost Advantage</h4><p>I’ve always loved the predictive model boosting capabilities that this technique provides. When I looked at its performance and the physics behind its high accuracy, I identified several benefits:</p><h4>Regularization:</h4><ul><li>Standard GBM implementation has no regularization like XGBoost, therefore it also helps to reduce overfitting.</li><li>XGBoost is also known as a ‘regularized boosting‘ technique.</li></ul><p>We will split the data into training and testing sets, but before going to split let&#39;s see how much percentage of people leaving the company, We will do this simply by adding all the <strong>y=1</strong> values divided by the total length of data.</p><pre>sum(y)<strong>/</strong>len(y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*RjUuhblg9RZKszx3ZzrPnQ.png" /></figure><p><strong><em>So, see that only 27% of people are left the company, so it concludes the dataset are pretty much imbalanced</em></strong></p><pre><em># Spliting the data</em><br>X_train,X_test,y_train,y_test<strong>=</strong> train_test_split(X,y,random_state<strong>=</strong>42,stratify<strong>=</strong>y)</pre><p>Now let&#39;s verify that stratify worked as expected.</p><pre>sum(y_train)<strong>/</strong>len(y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*RjUuhblg9RZKszx3ZzrPnQ.png" /></figure><pre>sum(y_test)<strong>/</strong>len(y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*RjUuhblg9RZKszx3ZzrPnQ.png" /></figure><p><em>verify that </em><em>stratify worked as expected, y_train and y_test has the same percentage</em></p><p><strong>Building the XGBoost model</strong></p><pre><em># Lets build the Xgboost model without cross validation</em><br>clf_xgb<strong>=</strong> xgb<strong>.</strong>XGBClassifier(objective<strong>=</strong>&#39;binary:logistic&#39;,max_depth<strong>=</strong>5,learning_rate<strong>=</strong> 0.1,<br>                           colsample_bytree <strong>=</strong> 0.5,<br>                           subsample<strong>=</strong>0.90, reg_lambda<strong>=</strong> 10,use_label_encoder<strong>=False</strong>)</pre><p><strong>Fitting the model</strong></p><ul><li>Here early_stopping_rounds=10: means if the prediction is not improving after building 10 more tree</li><li>If none of the 10 built trees not improving the prediction then, it will stop.</li></ul><pre>clf_xgb<strong>.</strong>fit(X_train,y_train,early_stopping_rounds<strong>=</strong>10,eval_metric<strong>=</strong>&#39;aucpr&#39;,eval_set<strong>=</strong>[(X_test,y_test)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*Nu2_GpJ2z1Tr9G3jdEedag.png" /></figure><p><strong>Predicting the model:</strong></p><p>Here we will predict the model on X_test data.</p><pre>y_pred<strong>=</strong> clf_xgb<strong>.</strong>predict(X_test)</pre><p><strong>Confusion matrix</strong></p><p>It’s a performance metric for machine learning classification problems with two or more classes as output. There are four different combinations of predicted and actual values in this table.</p><p>It is extremely useful for measuring Recall, Precision, Specificity, Accuracy, and most importantly AUC-ROC curves.</p><pre><em># ploting the confusion matrics</em><br>plot_confusion_matrix(clf_xgb,X_test,y_test,values_format<strong>=</strong>&#39;d&#39;,display_labels<strong>=</strong>[&#39;did not left&#39;,&#39;left&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*oL9yAvl-vfgWk4oCdq8qJg.png" /></figure><p>People who did not leave the company the model (91%) were correctly classified. but not model not performing well with people who had left the company, only(48%) correctly classified. XGBoost has a parameter that scale_pos_weight that helps with imbalanced data. we try to improve the accuracy by using cross-validation.</p><p>Now we will evaluate the model since this dataset is completely imbalanced so we will get accuracy by roc_auc_score.</p><pre>print(&#39;The accuracy of the model is:&#39;,roc_auc_score(y_test,y_pred))<br><strong>from</strong> sklearn.metrics <strong>import</strong> classification_report<br>print(classification_report(y_test,y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*MXFKssMQ9hDTYIomF_W-IA.png" /></figure><h3>7. XGBoost Parameters</h3><p><strong>max_depth [default=6]</strong></p><ul><li>The maximum depth of a tree, the same as GBM.</li><li>Used to control over-fitting as higher depth will allow the model to learn relations very specific to a particular sample.</li><li>Should be tuned using CV.</li><li>Typical values: 3–10</li></ul><p><strong>max_leaf_nodes</strong></p><ul><li>The maximum number of terminal nodes or leaves in a tree.</li><li>Can be defined in place of max_depth. Since binary trees are created, a depth of ’n’ would produce a maximum of 2^n leaves.</li><li>If this is defined, GBM will ignore max_depth.</li></ul><h4>gamma [default=0]</h4><ul><li>A node is split only when the resulting split gives a positive reduction in the loss function. Gamma specifies the minimum loss reduction required to make a split.</li><li>Makes the algorithm conservative. The values can vary depending on the loss function and should be tuned.</li></ul><h4>max_delta_step [default=0]</h4><ul><li>In the maximum delta step, we allow each tree’s weight estimation to be. If the value is set to 0, it means there is no constraint. If it is set to a positive value, it can help make the update step more conservative.</li><li>Usually, this parameter is not needed, but it might help in logistic regression when the class is extremely imbalanced.</li><li>This is generally not used but you can explore further if you wish.</li></ul><h4>subsample [default=1]</h4><ul><li>Same as the subsample of GBM. Denotes the fraction of observations to be random samples for each tree.</li><li>Lower values make the algorithm more conservative and prevent overfitting but too small values might lead to under-fitting.</li><li>Typical values: 0.5–1</li></ul><h4>colsample_bytree [default=1]</h4><ul><li>Similar to max_features in GBM. Denotes the fraction of columns to be random samples for each tree.</li><li>Typical values: 0.5–1</li></ul><h4>colsample_bylevel [default=1]</h4><ul><li>Denotes the subsample ratio of columns for each split, in each level.</li><li>I don’t use this often because subsample and colsample_bytree will do the job for you. but you can explore further if you feel so.</li></ul><h4>lambda [default=1]</h4><ul><li>L2 regularization term on weights (analogous to Ridge regression)</li><li>This is used to handle the regularization part of XGBoost. Though many data scientists don’t use it often, it should be explored to reduce overfitting.</li></ul><h4>alpha [default=0]</h4><ul><li>L1 regularization term on weight (analogous to Lasso regression)</li><li>Can be used in case of very high dimensionality so that the algorithm runs faster when implemented</li></ul><h4>scale_pos_weight [default=1]</h4><ul><li>A value greater than 0 should be used in case of high-class imbalance as it helps in faster convergence.</li></ul><h3>7.1 Gridsearch Cv</h3><p>Grid Search calculates the performance for each combination of all the specified hyperparameters and their values and then chooses the optimum value for the hyperparameters. Based on the number of hyperparameters involved, this makes the processing time-consuming and costly.</p><p>It requires four arguments: estimator, param grid, cv, and scoring. The following is a list of the arguments:</p><ol><li>estimator–a model built using Scikit-learn</li></ol><p>2. param grid — A dictionary containing lists of parameter values and parameter names as keys.</p><p>3. scoring — the criterion for evaluating performance. For example, for regression models, ‘r2’ is used, while for classification models, ‘precision’ is used.</p><p>4. cv — The number of folds for K-fold cross-validation is an integer.</p><pre>param_grid<strong>=</strong>{&#39;max_depth&#39;:[3,4,5],<br>            &#39;gamma&#39;:[0,0.25,1.0],<br>            &#39;learning_rate&#39;:[0.1,0.5,1.0],<br>            &#39;reg_lambda&#39;:[1,10,20],<br>            &#39;scale_pos_weight&#39;:[1,3,5],<br>    <br>}</pre><p><strong>FInding optimal parameter</strong></p><pre>optimal_param<strong>=</strong> GridSearchCV(estimator<strong>=</strong>xgb<strong>.</strong>XGBClassifier(objective<strong>=</strong>&#39;binary:logistic&#39;,seed<strong>=</strong>42,<br>                                                        subsample<strong>=</strong>0.9,colsample_bytree<strong>=</strong>0.5,use_label_encoder<strong>=False</strong>),<br>                            param_grid<strong>=</strong>param_grid,<br>                            scoring<strong>=</strong>&#39;roc_auc&#39;,<br>                            verbose<strong>=</strong>2, <br>                            cv<strong>=</strong>3)</pre><p><strong>Fitting the GridSearch</strong></p><ul><li>It will take some time to find the best parameter, for me, it took around 10 minutes.</li></ul><pre><em># fitting the gridsearch</em><br>optimal_param<strong>.</strong>fit(X_train,y_train,early_stopping_rounds<strong>=</strong>10,eval_metric<strong>=</strong>&#39;auc&#39;,eval_set<strong>=</strong>[(X_test,y_test)],verbose<strong>=False</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxt1rU44l1KfcMy0ZcEmrw.png" /></figure><p><strong>Finding Best parameter</strong></p><pre><em># Printing the best parameter</em><br>print(optimal_param<strong>.</strong>best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JbvDY7b07CFlKumDY8PEQ.png" /><figcaption>Best parameters</figcaption></figure><h3>Building model, evaluating the model</h3><pre><em># After getting the best parameter, now we will biuld the final classifier model</em><br>clf_classifier<strong>=</strong> xgb<strong>.</strong>XGBClassifier(objective<strong>=</strong>&#39;binary:logistic&#39;,<br>                                  gamma<strong>=</strong>1.0,<br>                                  learning_rate<strong>=</strong>0.1,<br>                                  max_depth<strong>=</strong>3,<br>                                  reg_lambda<strong>=</strong>10,<br>                                  scale_pos_weight<strong>=</strong>3,<br>                                  subsample<strong>=</strong>0.9, <br>                                  colsample_bytree<strong>=</strong>0.50,<br>                                  use_label_encoder<strong>=False</strong>)</pre><p><strong>Fitting the model</strong></p><pre><em># fitting the model</em><br>clf_classifier<strong>.</strong>fit(X_train,y_train,early_stopping_rounds<strong>=</strong>10,eval_metric<strong>=</strong>&#39;aucpr&#39;,eval_set<strong>=</strong>[(X_test,y_test)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*8F9p0VQaUDhJWi-Ue1qYJg.png" /></figure><p><strong>Predicting The final model</strong></p><pre><em># Predicting the model</em><br>y_pred<strong>=</strong> clf_classifier<strong>.</strong>predict(X_test)</pre><p><strong>Plotting confusion metrics of the final model</strong></p><pre><em># Plotting the confusion matrics</em><br>plot_confusion_matrix(clf_classifier,X_test,y_test,values_format<strong>=</strong>&#39;d&#39;,display_labels<strong>=</strong>[&#39;did not leave&#39;,&#39;left&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*j0-kvv8IcVjv4Lee8OmSpw.png" /></figure><p>We see the total people <strong>1294</strong> and people did not leave the company <strong>937</strong>(72%) correctly classified. out of <strong>467</strong> and left the company <strong>385</strong>(83%) correctly classified.</p><p><strong>Evaluating the final Model</strong></p><pre><em># Priting the accuracy and the model and lassification report</em><br>print(&#39;The accuracy of the model:&#39;,roc_auc_score(y_test,y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*mLL6C0ZUXeQm3nqSGrrA8g.png" /></figure><pre>print(classification_report(y_test,y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*KaJJS1ul_-Lj_M7sW5yR5g.png" /></figure><pre><strong>from</strong> sklearn.metrics <strong>import</strong> plot_precision_recall_curve<br>plot_precision_recall_curve(clf_classifier,X_test,y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*Ygbhiu_ko_0BFieCULTzJQ.png" /></figure><p><strong>We improve the correctly classified, who left the company from 52 % to 82%</strong></p><h3>8. Model Interpretations</h3><p>Target Variable: Churn_Value</p><ul><li>Contract duration (strong): Month-to-month contracts churn significantly more than one- or two-year contracts.</li><li>Internet services (moderate): Internet Fiber or DSL services churned at a higher pace than other services.</li><li>Dependents (Moderate): Customers who support dependents (kids/elders) churned less.</li><li>(Low) Paperless billing: Customers who opted for paperless billing had a higher attrition rate.</li><li>(Low) Streams: Indicates whether the consumer is utilizing the Internet service to stream TV or movies.</li><li>(Low) Automatic payment: Customers who had automatic payments set up were less likely to churn.</li><li>(Low) Partner: Customers who were married had a lower turnover rate.</li><li>Customers’ monthly charges are indexed against the average customer.</li></ul><h3>Conclusion</h3><ul><li>The model’s AUC of 78 percent implies that it is correct in approximately 4 out of 5 customer scenarios.</li><li>Recall indicates the model correctly predicts 83 percent of customer turnover cases.</li><li>Nearly one in every two false positives is predicted by the model, which has a precision of 54 percent.</li></ul><p>References:</p><p><a href="https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/">XGBoost Parameters | XGBoost Parameter Tuning</a></p><p>Follow me on LinkedIn</p><p><a href="https://www.linkedin.com/in/rahulsisodia06/">Rahul Sisodia - Ivy Professional School - New Delhi, Delhi, India | LinkedIn</a></p><p>GitHub:</p><ul><li><a href="https://github.com/rahkum96">rahkum96 - Overview</a></li><li><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3c5f408bd9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>