Tag: datascience

Image Classification – Pastas

What do you do when you are new in Italy and unable to determine what kind of pasta is being served to you?

Solutions is simple – Put on your nerd cap and let the machine distinguish it for you!

So what data do we have ? We have data of 4 different kinds of pastas, for each type of pasta we have around 1000 images

  • Ragu
  • Carbonara
  • Lasagna
  • gnocchi

This slideshow requires JavaScript.

Our task is to load the images, convert it into a matrix of numbers (possibly change the shape of the matrix by using some engineering tools) and classify the pastas.

First of all you can download the data from here

The complete code is here

So what do we need to

  1. First we need to read all the images in python, and to this we need to iterate over the food file
  2. Once the images are loaded we convert them into numerical matrices (After all they are numeric pixel values that represent a particular color)
  3. We also shape the data by removing some unnecessary pixel values
  4. Great so now we have our data – time to split it in train and testing
  5. Finally we run different kinds of svm models however we cannot exceed 48% accuracy 😦
  6. But no reason to be upset Artificial neural networks to the rescue
  7. What are ANN – Artificial neural networks are one of the main tools used in machine learning. As the “neural” part of their name suggests, they are brain-inspired systems which are intended to replicate the way that we humans learn. Neural networks consist of input and output layers, as well as (in most cases) a hidden layer consisting of units that transform the input into something that the output layer can use. They are excellent tools for finding patterns which are far too complex or numerous for a human programmer to extract and teach the machine to recognize.

ANN’s were able to give us 60% accuracy , which is a significant increase from SVM’s.

However in order to boost our accuracy, now we try to convert our images from color to gray scale and try to highlight any particular unique shape or feature of the image. This process is known as Histogram of Gradient.

However this didn’t help us get better results.

One shortcut solution we could have used is to use a pre trained neural network, train it on our data and get better results, like vgg16

So what are you waiting for – Buon Appetito!!!!

Advertisements

Classification Models – Employee attrition

Modeling for prediction

In order to find a model which could help with the prediction process we ran several data mining models

17

 

From the previous results its clear that decision tree stole the show!

However lets think practically

  • It is often required to explain the business why we think a person could leave, in this case we need a model whose output we can explain. In our case a decision tree or logistic regression
  • Sometimes HR would just like to run our model on random data sets , so its not always possible to Balance our datasets using techniques like smote
  • Our model should just be able to predict better than random but imagine the cost of entertaining an employee who was not going to leave but our system tagged him – This is a future improvement for our model
  • XGBoost model created a nice ensemble of trees for us, whose accuracy could increase more than the decision tree if we get more data

 

We successfully created an early warning system  which immediately tells the Human Resources department if an employee is prune to leave or not.

We achieved this early warning system based on several data mining techniques in order to be  very accurate on supervised classification modelling

EDA and Data Cleaning

Well the data is here

So we first start with EDA

  • Data is imbalance by class we have 83% who have not left the company and 17% who have left the company
  • The age group of IBM employees in this data set is concentrated between 25-45 years
  • Attrition is more common in the younger age groups and it is more likely with females As Expected it is more common amongst single Employees
  • People who leave the company get lower opportunities to travel the company
  • People having very high education tend to have lower attrition
  • The correlation plot was as expected
  • Link to eda workbook in python is here
  • From the Tableau plots we can conclude that below mentioned category are having higher attrition rate:
    • Sales department among all the departments
    • Human Resources and Technical Degree in Education
    • Single’s in Marital status (Will not use this due to GDPR)
    • Male in comparison to females in Gender (Will not use this due to GDPR)
    • Employee with job satisfaction value 1
    • Job level 1 in job level
    • Life balance having value 1
    • Employee staying at distant place
    • Environment Satisfaction value 1

 

First of all we have categorical data and if we want to run machine learning algorithms in python we need to be able to convert categorical variables(nominal) to dummy variables and ordinal ones to integer values.

Once we are done with that we need to embrace the fact that our data is biased so in order to equalize the class balance we make use of the Synthetic minority oversampling technique (SMOTE). You can google about it.

The code file is located here for your reference ->   https://github.com/mmd52/3XDataMining/blob/master/DataCleaning_And_Smote.ipynb

IBM Employee HR Attrition

Its a new day, a client walks in and says he needs your help.

Our client is ABC a leading firm and is doing well in the sector. It is recently facing a steep increase in its employee attrition . Employee attrition has gone up from 14% to 25% in the last 1 year . We are asked to prepare a strategy to immediately tackle this issue such that the firm’s business is not hampered and also to propose an efficient employee satisfaction program for long run. Currently, no such program is in place . Further salary hikes are not an option.

data is here

Well this is a nice business problem, so lets do some more research on it – >

The attrition problem is not only unique to ABC but to other IT companies such as XYZ, India’s second largest IT services company, that is also battling high attrition, with a peak attrition of 20.4 % in the October-December quarter of FY15.

Now that we know the market situation what can we do ?

This slideshow requires JavaScript.

 

From this decision tree it should be clear that we will create an early warning system to help the company identify those employees which are more probable to leave the company.

In the following posts we will go through

  1. EDA
  2. Data cleansing
  3. Classification models

 

But why is a company so affected by employee attrition

  • Cost of training a new employee
  • cost of acquiring a new employee
  • But most importantly an employee is a asset that adds value to a company, and when an employee leaves a value percentage of the company is diminished with it, at the end a company spends an enormous sum trying to replace this employee and recreating the value it lost.

Data – Cash Forecasting

Now the data we are talking about is usually highly confidential and one of the major reasons why we will be working with dummy data.

The data we have is that of a single ATM, for various time periods.

Our fields are Holiday (Binary) where 1 indicates an holiday and 0 indicates a normal working day.

Up time defines how long was the ATM up. At times ATM’s could not be functional because of power outage, network connectivity or physical issues.

Peak period (Binary) where 1 indicates peak period and 0 indicates non peak period.

Dispense cash is dispensed cash against a particular day.

This slideshow requires JavaScript.

Now in general for a normal ATM the weekly trend would be a spike in dispense on the start of weeks mostly Monday and a drop during end of the week ie Saturdays and Sundays.

For a monthly trend the spike would be at the beginning and end of the month and a drop somewhere in between. And this seems logical to, think of salaried people as an example, they get their salaries at the end of the month and probably use it to plan their month ahead, or business men would like to pay their dues or salaries to their employees at the end of the month and therefore withdraw cash.

Above you can see a few basic insights regarding cash dispense.

You can download the dummy data set that I have created from here

Cash Forecasting – Understanding difficulty associated with

Every ATM that is placed anywhere would have different dispensation trends then the other. An ATM in a rural area would have a different and smaller dispensation trend as compared to a busy suburban area. This means a different model for every ATM. WAIT WHAT?? So much over head, no way anyways doing that right. Well yes no ones going to do that.

Solution to this problem is classifying ATM’s based on their locality, Imagine creating various bands, where Band1 is a metropolitan area where users dispense cash frequently from and band5 being the lowest where cash dispense is the lowest.

Now that solves a very minor problem, but still if we see cash dispense trends they would waiver in spite of being in the same band. HMM.. problem still not solved. Now we categorise ATM’s based on their age and on average how much they dispense.

So for our case study we will only be considering ATM’s that have an age greater than 6 months and on average dispense between 0 – 100,000 $.

Cash Forecasting – Overview

How do ATM’s in general work is a great question to ask? Well banks at times prefer not to manage their ATM’s as it involves a lot of overhead such as transportation of cash, maintenance of ATM machines, rent and most importantly security.

In order to avoid this over head a lot of banks outsource this task. The companies who overtake this responsibility , make their revenue based on every transaction made. Say for every non cash transaction from the ATM managed by them they get x$ and for every cash transaction they get y$  where y>x .

So why do we need to predict cash ?? well these companies rent a place, put their ATM’s at that place keep a service engineer to maintain that machine and pump enough security, but where they need to be careful is interest cost. What interest cost? lets say for today’s date I decided to keep 100$ in my ATM, I would borrow this money from a bank, to whom I would pay interest every day for the cash that is not withdrawn by the customer’s.

The obvious solution for this is to load ATM’s with the smallest amount of money possible, however this leads to two problems, First is loss of revenue from a potential customer, and second one is brand loss, and brand loss is very bad.

That means we do not want to load to much money to avoid paying interest cost on idle money, and neither do we want to put to less in order to avoid loss of revenue and brand loss. In order to find this perfect balance we need to create a forecasting model on how much money to load in the ATM’s, in order to make the business profitable.

One underlying constraint is transportation. We cannot transport and load money in ATM’s on a daily basis to avoid transportation costs, that is why transportation will happen only once in two to three days.

Decision Tree and Interpretation on Telecom Data

We saw that logistic Regression was a bad model for our telecom churn analysis, that leaves us with Decision tree.

Again we have two data sets the original data and the over sampled data. We run decision tree model on both of them and compare our results.

So running decision tree on the normal data set yielded better results as compared to running on the over sampled data set

Accuracy Kappa Precision Recall Auc
Data 0.9482 0.7513 0.68421 0.90698 0.837
Over Sampled Data 0.8894 0.5274 0.5965 0.5862 0.7656

Unfortunately the decision tree plot was too big for me to put it in this post.

As decision tree is giving the highest level of accuracy , we will select it as the clear winner for our telecom churn analysis problem.

Another major advantage of decision tree is that it could be explained graphically very easily to the end business user on why a particular choice is being made.

You can find the code for decision tree here->

https://github.com/mmd52/Telecom_Churn_Analysis/blob/master/Decision_Tree.R

This was a dummy database and may not have yielded the best results , but is a perfect exercise for practice.

Determining Feature Importance For Telecom Data

We have a complete data set  -> Check

Feature engineering done -> Check

How many variables do we have?    20 variables

How many should we ideally use ?   Not more that 10 ideally

How to determine which variables to include and which not to ?   Its simple do Boruta!!

Whats Boruta?

Boruta is a feature selection algorithm. Precisely, it works as a wrapper algorithm around Random Forest. You can read about it here ->  https://www.analyticsvidhya.com/blog/2016/03/select-important-variables-boruta-package/   Analytics vidhya has given a pretty good explanation about it here.

Now keep one important thing in mind we have two train sets 1)Normal train set  2)Smote Train set.

So upon running boruta on the normal train set, boruta confirmed the variables International_Plan,Voice_Mail_Plan ,No_Vmail_Messages,Total_Day_minutes,
Total_Day_charge,Total_Eve_Minutes,Total_Eve_Charge,Total_Night_Minutes,
Total_Night_Charge , Total_Intl_Minutes,Total_Intl_Calls,Total_Intl_Charge,
No_CS_Calls as important.

And upon running Boruta on Smote data set, Boruta confirmed all the variables as important, you can find the boruta code below

https://github.com/mmd52/Telecom_Churn_Analysis/blob/master/Boruta_Imp_FE.R

Churn Analysis On Telecom Data

One of the major problems that telecom operators face is customer retention. Because of which majority of the Telecom operators want to know which customer is most likely to leave them, so that they could immediately take certain actions like providing a discount or providing a customised plan, so that they could retain the customer.

However accuracy required while building a churn analysis model needs to be very high, imagine if our model has a accuracy of just 75% and the total number of customers who want to leave are just 5% , this leaves a margin of 20% of customers who were wrongly classified as customers who will leave the operator. If an operator has 10000 customers,And 2500 customers are predicted to leave , the operator may have to release lets assume a 1$ credit to all that’s a cost of 2500$, where as credits that required to be released was only for 5% of the customer’s that is a cost of 500$, hence the operator spent 2000$ for no reason. If the operator has high number of customers it would lead to a huge loss.

Coming to the data quotient, there is no freely available telecom data as far as I know available, however the website https://www.sgi.com/tech/mlc/db/ provides data for churn analysis, this data is not real but represents real world scenarios and is good from the perspective of understanding and learning.

The data on the website is classified into train and test has no NA’s means no feature engineering as such to be done before running models on it.

Now comes the question of which models to run on it. Some would say since we need very high accuracy hence we will run xgboost or random forest, however the downside we have here is that we cannot explain to the operator on what basis is XGBOOST or random forest determining why will the customer leave him. Even if we manage to explain its very complicated and will not be accepted.

Because of this we will have to take support on models that can be easily explained to the customer. This leaves us with two models for classification .i.e. customer leaves -> 0 or customer is retained -> 1. So the models are Logistic regression and decision tree.

Why Logistic Regression ?  well because we can explain to the operator why customer is leaving him thanks to the logit equation.

Why Decision Tree? well because there is a neat flow of how our tree makes decision by breaking variables and deciding yes and no based on entropy and impurity.

Further in this post category I will show feature engineering to Running models, to interpretation.

The data available from the website is a bit complex to save to a CSV file so if you need you can download the train and test data from below.

Also explanation of variables is not provided as it is fairly simple.

https://github.com/mmd52/Telecom_Churn_Analysis