Showing posts with label Machine Learning. Show all posts
Showing posts with label Machine Learning. Show all posts

Tuesday, 30 July 2019

Logistic Regression using R - How to handle class bias?

Logistic Regression using R - How to handle class bias?

Doing this blog as a revision into some primitive topics in Machine Learning.

Since, almost all my current work is done using R, I will implement logistic regression using this language.

We will be using adult data set. After all is set, now we dive straight into the code. Further explanations shall not be provided as most of the code is self-explanatory in nature.

> idata <- read.csv("adult_csv.csv")
> summary(idata)
      age                   workclass         fnlwgt               education     education.num  
 Min.   :0.000   Private         :33906   Min.   :  12285   HS-grad     :15784   Min.   : 1.00  
 1st Qu.:1.000   Self-emp-not-inc: 3862   1st Qu.: 117551   Some-college:10878   1st Qu.: 9.00  
 Median :2.000   Local-gov       : 3136   Median : 178145   Bachelors   : 8025   Median :10.00  
 Mean   :1.771                   : 2799   Mean   : 189664   Masters     : 2657   Mean   :10.08  
 3rd Qu.:3.000   State-gov       : 1981   3rd Qu.: 237642   Assoc-voc   : 2061   3rd Qu.:12.00  
 Max.   :4.000   Self-emp-inc    : 1695   Max.   :1490400   11th        : 1812   Max.   :16.00  
                 (Other)         : 1463                     (Other)     : 7625                  
               marital.status            occupation            relationship                   race      
 Divorced             : 6633   Prof-specialty : 6172   Husband       :19716   Amer-Indian-Eskimo:  470  
 Married-AF-spouse    :   37   Craft-repair   : 6112   Not-in-family :12583   Asian-Pac-Islander: 1519  
 Married-civ-spouse   :22379   Exec-managerial: 6086   Other-relative: 1506   Black             : 4685  
 Married-spouse-absent:  628   Adm-clerical   : 5611   Own-child     : 7581   Other             :  406  
 Never-married        :16117   Sales          : 5504   Unmarried     : 5125   White             :41762  
 Separated            : 1530   Other-service  : 4923   Wife          : 2331                             
 Widowed              : 1518   (Other)        :14434                                                    
     sex         capitalgain      capitalloss      hoursperweek         native.country    class      
 Female:16192   Min.   :0.0000   Min.   :0.0000   Min.   :0.000   United-States:43832   <=50K:37155  
 Male  :32650   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:2.000   Mexico       :  951   >50K :11687  
                Median :0.0000   Median :0.0000   Median :2.000                :  857                
                Mean   :0.2003   Mean   :0.1149   Mean   :1.951   Philippines  :  295                
                3rd Qu.:0.0000   3rd Qu.:0.0000   3rd Qu.:2.000   Germany      :  206                
                Max.   :4.0000   Max.   :4.0000   Max.   :4.000   Puerto-Rico  :  184                
                                                                  (Other)      : 2517  
> head(idata)
  age        workclass fnlwgt education education.num     marital.status        occupation  relationship  race
1   2        State-gov  77516 Bachelors            13      Never-married      Adm-clerical Not-in-family White
2   3 Self-emp-not-inc  83311 Bachelors            13 Married-civ-spouse   Exec-managerial       Husband White
3   2          Private 215646   HS-grad             9           Divorced Handlers-cleaners Not-in-family White
4   3          Private 234721      11th             7 Married-civ-spouse Handlers-cleaners       Husband Black
5   1          Private 338409 Bachelors            13 Married-civ-spouse    Prof-specialty          Wife Black
6   2          Private 284582   Masters            14 Married-civ-spouse   Exec-managerial          Wife White
     sex capitalgain capitalloss hoursperweek native.country class
1   Male           1           0            2  United-States <=50K
2   Male           0           0            0  United-States <=50K
3   Male           0           0            2  United-States <=50K
4   Male           0           0            2  United-States <=50K
5 Female           0           0            2           Cuba <=50K
6 Female           0           0            2  United-States <=50K

Checking class bias now, on column class,

> table(idata$class)
<=50K  >50K 
37155 11687

There is a class bias, a condition observed when the proportion of one event is much smaller than proportion of other event.
Thus, we must sample the observations in approximately equal proportions to get better models.

CREATING TRAINING AND TESTING SAMPLES

#training data
input_ones <- idata[which(idata$class == ">50K"), ]  # all <=50k values
input_zeros <- idata[which(idata$class == "<=50K"), ]  # all <=50k values
set.seed(100)  # for repeatability of samples
input_ones_training_rows <- sample(1:nrow(input_ones), 0.7*nrow(input_ones))  # >50k values for training
input_zeros_training_rows <- sample(1:nrow(input_zeros), 0.7*nrow(input_ones))  # <=50k values training. 
training_ones <- input_ones[input_ones_training_rows, ]  
training_zeros <- input_zeros[input_zeros_training_rows, ]
trainingData <- rbind(training_ones, training_zeros)  # row bind  
# Create Test Data
test_ones <- input_ones[-input_ones_training_rows, ]
test_zeros <- input_zeros[-input_zeros_training_rows, ]
testData <- rbind(test_ones, test_zeros)  # row bind 

One simple optional step is to create Weight of Evidence (WOE) for categorical variables.
This is a very simple, yet useful method - Read more here.

idata_woe <- idata
str(idata_woe)

table(idata_woe$class)

library(car)
library(dplyr)

idata_woe$class <- dplyr::recode(idata_woe$class,"<=50K" = 0,">50K" = 1)
#idata_woe$class <- car::recode(idata_woe$class,"<=50K" = 0,">50K" = 1) - this is not working
idata_woe

i <- 10
q <- quantile(idata_woe$class,
              probs = c(1:(i-1)/i),
              na.rm = TRUE,
              type=3)
cuts <- unique(q)


WOE_Class <- table(findInterval(idata_woe$class,vec = cuts,rightmost.closed = FALSE),idata_woe$class)
WOE_Class <- as.data.frame.matrix(WOE_Class)
WOE_Class$`0`<-rowSums(WOE_Class)
WOE_Class$WOE <- log((WOE_Class$`1`*sum(WOE_Class$`0`))/(WOE_Class$`0`*sum(WOE_Class$`1`)))
> WOE_Class
      0     1      WOE
1 37155     0     -Inf
2 11687 11687 1.430113

Now that we have already calculated WOE, it is only logical that we calculate the Information Value (IV) also,

library(scorecard)

iv(idata_woe, y="class")
> iv(idata_woe, y="class")
          variable info_value
 1:   relationship 1.52771659
 2: marital.status 1.34867700
 3:            age 0.89506214
 4:    capitalgain 0.89314987
 5:     occupation 0.76787908
 6:      education 0.73690518
 7:  education.num 0.73690518
 8:   hoursperweek 0.40824961
 9:         fnlwgt 0.33755308
10:            sex 0.30052143
11:      workclass 0.17056215
12:    capitalloss 0.11592250
13: native.country 0.07509682
14:           race 0.06784214

Now, we have the information value (meaning the strength of relation between “class” and other parameters.
We now start building the logistic regression model,

logitMod <- glm(class ~ relationship + age + capitalgain + occupation + education.num, data=trainingData, family=binomial(link="logit"))
predicted <- plogis(predict(logitMod, testData))  # predicted scores
# or
predicted <- predict(logitMod, testData, type="response")  # predicted scores
summary(logitMod)

Result is as follows,

> summary(logitMod)

Call:
glm(formula = class ~ relationship + age + capitalgain + occupation + 
    education.num, family = binomial(link = "logit"), data = trainingData)

Deviance Residuals: 
    Min       1Q   Median       3Q      Max  
-3.3583  -0.5408   0.0015   0.6281   3.3139  

Coefficients:
                            Estimate Std. Error z value Pr(>|z|)    
(Intercept)                 -4.43416    0.18263 -24.280  < 2e-16 ***
relationshipNot-in-family   -2.26671    0.05846 -38.776  < 2e-16 ***
relationshipOther-relative  -2.52271    0.19614 -12.862  < 2e-16 ***
relationshipOwn-child       -3.43974    0.14067 -24.452  < 2e-16 ***
relationshipUnmarried       -2.66316    0.09625 -27.670  < 2e-16 ***
relationshipWife             0.31766    0.09130   3.479 0.000503 ***
age                          0.34161    0.02041  16.734  < 2e-16 ***
capitalgain                  0.95230    0.03972  23.974  < 2e-16 ***
occupationAdm-clerical       1.08011    0.13682   7.895 2.91e-15 ***
occupationArmed-Forces       2.89421    1.34843   2.146 0.031844 *  
occupationCraft-repair       1.29746    0.13042   9.949  < 2e-16 ***
occupationExec-managerial    2.08246    0.13025  15.988  < 2e-16 ***
occupationFarming-fishing    0.23595    0.17661   1.336 0.181539    
occupationHandlers-cleaners  0.58579    0.18067   3.242 0.001185 ** 
occupationMachine-op-inspct  0.83323    0.14885   5.598 2.17e-08 ***
occupationOther-service      0.16679    0.16294   1.024 0.306012    
occupationPriv-house-serv   -0.02904    0.74544  -0.039 0.968925    
occupationProf-specialty     1.70451    0.13280  12.836  < 2e-16 ***
occupationProtective-serv    1.72939    0.17889   9.667  < 2e-16 ***
occupationSales              1.56500    0.13284  11.781  < 2e-16 ***
occupationTech-support       1.48003    0.16098   9.194  < 2e-16 ***
occupationTransport-moving   1.21363    0.14650   8.284  < 2e-16 ***
education.num                0.29476    0.01128  26.127  < 2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 22680  on 16359  degrees of freedom
Residual deviance: 13115  on 16337  degrees of freedom
AIC: 13161

Number of Fisher Scoring iterations: 6

Cheers!

Saturday, 26 January 2019

Markov Chains - A Mathematical Treatise

Markov Chains

We have a set of stated, = {}. A Markov process starts in one of these states and moves successively from one state to another. Each move is called a step . If the chain is currently in state , then it moves to state at the next step with a probability denoted by , and this probability does not depend upon which states the chain was in before the current state.These probabilities are called transition probabilities. The process can remain in the state it is in, and this occurs with probability . Initially a probability is defined by specifying a particular state as the starting state.

Say, we stay in Patna (Capital of the State of Bihar, India), and at my home we usually eat either Roti (), Rice (), Parantha ()) or Bread () for dinner. There are also some days when we eat one particular dinner on two or three or more consecutive days.

Now, we define transition probabilities of using a Transition Matrix which is given as,

From the above matrix, it can be seen that and similarly, .

In the similar lines of the above concept, a Transition Diagram can also be drawn.

Let us dig further into the concept now. Imagine today we eat Rice at home and two days from today we eat Bread. This is written as . We see that if we ate Rice today then the event of us eating Bread two days from today is a disjoint union of the following,

  1. We ate Rice tomorrow and Bread day after.
  2. We ate something else tomorrow and Bread day after.
  3. We ate Bread tomorrow and Bread day after.

Therefore, we can write as ,

The has pointed towards a more generalized concept of Dot product of two vectors.

Considering there are states in the Markov chain,

This study was for , meaning we are yet to define this in a more generalized manner. Obviously, looking at the present scenario of high-end computing software packages available, this attempt seems to be a waste of efforts, but then knowing the math is always good fun!

Before doing that, we will again go into the basic definition as defined above and try to make an iterative approach into the problem.

We have assumed that our meal starts at state Rice, so, for us,

is the state of our system at state or the beginning of the system.

Similarly, if we want to find we will do it as,

In the similar lines,

This means, for generalization’s sake,

Using some very basic Linear Algebra methods to compute ,

Recall :

Here, is a Diagonal matrix and is a matrix whose columns correspond to the Eigen-vectors of .

I leave the computation to your own practice.

There for,

Since, is a diagonal matrix, which is obviously of form,

Therefore, will be,

Hence, we can easily compute .

The Python implementation of this concept is relatively simple once we understand the math behind it.

All the best with that.

Cheers!

Resources:

  1. Matrix Diagonalization

  2. Eigen Values and Eigen Vectors

  3. Markov Chains

  4. Markov Chains

Friday, 24 November 2017

Moore-Penrose Pseudoinverse

Generalization of the inverse of a matrix.

I believe, we pay too much attention to implementation, and too less
attention in the study of the concept that is implemented. I have been
on then teams of many Data Science and Machine Learning projects, and
I would always reiterate on one simple idea; that is, “If you do not
know the math, you don’t know it at all.”
This is a piece of philosophy I deeply believe in. With the advent of packages like numpy, matplotlib, scikit-learn etc., implementing a machine learning model with a moderately difficult data set and problem is fairly simple.
The magic then stays in being able to tweak the algorithm and getting something new (or weird) out of the model. And, for you to be capable of doing so, you will have to know the mechanism behind it.
The Moore-Penrose pseudoinverse in the soul of PCA (Principal Component Analysis), one of the most popularly used Dimensionality reduction techniques.


How do we define the inverse of a matrix?
Provided that the matrix is a square matrix and non-singular, we simple divide the adjoint of the matrix with its determinant.
Mathematically, for and , the inverse of is defined as,




Of course, the above method is computationally very expensive. Hence, we can get the inverse of the matrix recursively using the Fadeev-LeVerrier equation ( Read about that in this blog of mine).


Now, how do we deal with matrices that are non-square? How do you find the inverse of a matrix that looks like this,

This is where the Generalization of inverse of a matrix happens, named the Moore-Penrose Pseudoinverse.


For every , there exists a pseudoinverse . ( is read as “A dagger”).
is mathematically defined as,

This is dimensionally consistent. Please check and verify.


Now, say we have,

It is impossible to find by the conventional method . So, we use the Generalized Inverse at .
So,

So, comes out to be . So, comes out to be .
Hence,
which is the pseudoinverse or the generalized inverse.


For a square matrix (i.e., ),

In detail,



Some properties of the generalized inverse are,
1.
2.
3.
One important point to remember is, always exists and is unique.



Cheers!

Tuesday, 25 April 2017

Preparation of exam.

Preparation Notes - Hell lot of Math and Algorithms; very helpful.

Note : These notes are made during my preparation for my exams. They might be crude and may not be in their best form of presentation. Read at your own risk.


Subject : IC 021 - Computational Techniques in Control Engineering

Professor : Dr. A Ramakalyan.

Difficulty : Runs to Heavens and goes around it times.

Books:
1. B N Datta’s Numerical Methods for Linear Control Systems. - referenced as [1]
2. Gilbert Strang’s Linear ALgebra and it’s applications. - referenced as [2]
3. S Kumaresen’s Linear Algebra - A Geometric Approach. - referenced as [3]


1. Computing [1]

  1. There are many ways of doing this, one of the very popular one is the Taylor Series method.
    We simply expand as per the Taylor series.
    Hence, can be written as,

    • The drawbacks to this method are that a large number of terms is needed for convergence, and even when convergence occurs, the answer can be totally wrong.
  2. Hence, I will now get into the Pade’s Scaling and Squaring algorithm for this task.
    Suppose that, is a power series presented as,

    Then the Pade’s Scaling and Squaring Algorithm, given an approximation of as ,

    The and are chosen such that the terms containing are cancelled out in . The order of Pade’s approximation is . The ratio is unique and the coefficients and always exist.

    Similarly, Pade’s approximation for is given by,

    Where,

    and

    • It can be shown (Exercise 5.16) that if p and q are large, or if A is a matrix having all its eigenvalues with negative real parts, then is nonsingular.
    • The difficulty of Round off errors in Pade’s method can be controlled by Scaling and squaring.
    • Since is same as , the idea is it to find out in terms of powers of so that can be computed accurately and then find with repetitive squaring.
    • This method has favorable numerical properties when .

      Let be chosen such that , then Moler and Van Loan(1978) have shown that there exists an such that ,

      Where , with

      Given an error tolerance of we should choose such that

      The Algorithm is as follows:
      Input : ,
      Output : with

      Step 1: Choose such that , set .
      Step 2: Choose and smallest non-negative integer satisfying,

      Step 3: Set
      Step 4: For do

      Step 5: Solve for : .
      Step 6: For do,
    • The algorithm requires about flops.
    • The algorithm is numerically stable when A is normal. When A is non-normal, an analysis of the stability property becomes difficult, because, in this case e a may grow before it decays during the squaring process; which is known as “hump” phenomenon.
      Example at Page 143 of [1]
  3. We have another effective method called the Matrix decomposition method uses the Real Schur form to do so.

    Let be transformed to a real Schur matric using an orthogonal similarity transformation:

    Then,

    Note that is upper-triangular.

    The algorithm is:
    Step 1: Transform to using the iteration algorithm.

    Step 2: Compute :
    for do,

    end.

    for do
    for do
    set

    end
    end
    Step 3: Now we have then we compute


2.Lyapunov Stability theorem: [1]

Lyapunov Stability theorem,
The system :

is asymptotically stable , for any symmetric positive definite matrix , there exists a unique symmetric positive definite matrix satisfying the equation:


Kronecker Product and Lyapunov:

For example,
if

and,

Then, the Kronecker product will look like,

It is evident that,

Now, we formulate the using the Kronecker product. Note that is negative semi-definite. is positive definite and symmetric.

Vectorisation of a matrix Stack all elements of
the matrix into one column.

Going directly to the final answer,

Verify it once.

If is stable then has unique solution.


Schur method of Lyapunov:
Method proposed by Bartels and Stewart. It is based on the reduction of to .

Step 1: Reduce the problem.
For,

is reduced to,

Where,
, and .

Step 2: Solution of the reduced form.
Let,


and
Assume that the columns through have been computed, and consider the following two cases,

Case 1: . Then is determined by solving the quasi-triangular system,

If, in particular, R is upper triangular, that is there are no “Schur bumps” on the diagonal, then each , can be obtained
by solving an upper triangular system as follows:


Case 2: this shows a Schur Bump.

Example at Page 274


If doesn’t have Eigen Values in the Limit circle , we modify as,

Use this in the Discrete Lyapunov which is given by,

The resulting equation is,

You will get a similar equation to that of the normal Lyapunov equation.


3. Modified QR algorithms:[4]

  1. Modified Gram-Schmidt method:
    for

    end

    for

    -for

    -end
    end
    It requires operations.
    Practice example from the above link

  2. Original algorithm of QR decomposition:
    Aim is to write matrix in terms of .
    Here, is an orthogonal matrix with orthonormal columns; and is an upper-triangular matrix.

    Now, we take an example,

    We will first find , and as the three orthonormal vectors using the GS-strategy.
    Now, we will define , and as,

    We define a partial basis as which will be updated at each step.

    For the first step,
    we find as,

    similarly, we find as follows,

    Now, we update ,

    Now, we find as follows,

    Hence, the partial basis is,

This partial basis is the orthogonal set, hence we now make it orthonoamal,

Hence,
norm of first column,
Similarly,

and

Hence, the orthonormal is,

Now, we have, and ; we now find ; which by theory has to be upper-triangular,

Make up the algorithm from the above steps.


4. Condition Number:[5]

As a rule of thumb, if the condition number , then you may lose up to digits of accuracy on top of what would be lost to the numerical method due to loss of precision from arithmetic methods.

A problem with a low condition number is said to be well-conditioned, while a problem with a high condition number is said to be ill-conditioned. The condition number is a property of the problem.

Condition number is mathematically defined as,

We define the -norm as follows,
For a matrix

The -norm is,


So, for a given matrix,

We get,

Hence,

and,

Therefore,

Thus, the matrix (or system) is ill-conditioned.


The question paper that came for this exam was pretty sadistic.
Give it a try, if you can and tell me how awesome it feels. I will score around 30/50.