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

Sunday, 9 September 2018

Catalan's Conjecture - A learning exercise for the bored mind - Contd.

Before we move to Mihailescu’s proof, let us cover some more mathematical concepts (so that we feel superior to the people around us, just kidding :smile:),

There is an interesting theorem that Mihailescu uses in his proof, called the Stickelberger’s theorem,


Stickelberger’s theorem:

This is a result of algebraic number theory, which gives more information about Galois Module structure of class groups of Cyclotomic Fields.
This theorem consists of Stickelberger’s element and Stickelberger’s ideal.
I will now state the complete definition of the theorem and then visit its corners as we move along,

Let denote the -th cyclotomic field . It is a Galois extension of with Galois Group isomorphic to the multiplicative group of integers modulo .

The Stickelberger element (of level or of ) is an element in thr group ring and the Stickelberger ideal is an ideal in the group ring . (Note: ).

The definition of both the Stickelberger element and ideal are, let denote a primitive -th root of unity . The isomorphism from to is given by sending to by the relation
The Stickelberger element of level is given by,

The Stickelberger ideal of level is given by,


Inkeri, used the concept of Wiefrich pair (explain in the previous blogpost of this series) in the context of Catalan’s equation as follows:

A Wieferich pair is a pair of primes such that and

He showed that if the Catalan’s equation holds, then either is a Wieferich pair, or divides , the class number of cyclotomic field , or divides , the class number of cyclotomic field , there were other developments in this direction too.

Bugeaud and Hanrot proved a class number criterion concerning Catalan’s equation, which implies that the Catalan’s Equation ( ) has no solutions in non-zero integers and if and are primes such that one of them is smaller than 43. This was a huge achievement , I recommend you to have a look at the paper at [5].

Mihailescu proved that the Catalan equation has no solutions if and are odd and does not divide . By this result the Catalan conjecture became a theorem. And later Mihailescu succeeded in finding a more elegant proof of Catalan’s conjecture in the case where does divide . Thus, Catalan’s conjecture is a theorem with an algebraic proof in which no computer calculations
are needed.



In this section e wll discuss some breakthrough results by Mihailescu. The most important one is that divides .

The following lemma will be used for that, an element of a ring is called nilpotent if and integer such that .

Lemma 1: The ring does not contain nilpotent elements, if , satisfy the congruence

Theorem 1: For , the element is a in . We also have that divides and divides .

The proofs of the above Lemma and Theorem are beyond the scope of this blog; regardless to say that the pre-requisites are already covered in detail. For the interested, you can refer Catalan’s Conjecture - A cyclotomic field.

Cheers!

Tuesday, 10 April 2018

Catalan's Conjecture - A learning exercise for the bored mind.

I was going through a video by Numberphile where they were talking about the Catalan’s conjecture.
This is another conjecture which is simple to state; however extremely difficult to prove; just like Collatz conjecture, about which I already have a blog in place.
At the very outset of the blog; let me bring it to your knowledge that this blog is just for learning and understanding and contains “very little”-to-“null” original work on the subject. However, this blog will be exhaustive and will contain a lot of references that will help a newbie (like myself) get into the depths of the conjecture and fully understand concepts used in its proof.
Let us now define the conjecture;
This statement was conjectured by Eugene Catalan (1814–1894) and was sent to the editor of Journal fur die Reine und Angewandte Mathematik.
The conjecture is as follows,
and are two powers of natural numbers whose values are consecutive (i.e., 8 and 9); the conjecture is for a mathematical statement such as,

The only solution of is for , and , is , , , .
Catalan’s conjecture was proven true by Preda Mihăilescu in 2002; the proof involves the theory of cyclotomic fields and Galois Modules.
So, as you see now, the breadth of the subject blew up! On second were talking about squares and cubes and now we are talking of Cyclotomic fields and Galois Modules!
Nevertheless, I will try and cover each topic in brief and quench our mathematical thirst!
Let us consider (with and ; for the sake of eliminating any confusion between and an english “a”), unless otherwise stated, and can be negative integers as well. Now, we re-write as follows,

The GCD of the two factors on the left hand side of the equation (after considering ) is either or (How did this happen?).

Some concepts before we move ahead:
The Wieferich pairs
In mathematics,
a Wieferich pair is a pair of prime number and that satisfy,

Let us write as, for,
This suggests a traditional approach of factorizing the left hand side
in , the ring of integers in the th cyclotomic
field

Ring:
A ring in the mathematical sense is a set together with two binary
operators and (Addition and multiplication), satisfying the
following conditions:
1. Additive associativity: For all , ,
2. Additive commutativity: For all , ,
3. Additive identity: There exists an element in such that for all a in , .
4. Additive inverse: For every a in there exists such that ,
5. Left and right distributivity: For all , and ,
6. Multiplicative associativity: For all , ( ring satisfying this property is sometimes
explicitly termed an associative ring). Conditions 1-5 are always
required. Though non-associative rings exist, virtually all texts also
require condition 6.
7. Multiplicative commutativity: For all , ( ring satisfying this property is termed a commutative ring),
8. Multiplicative identity: There exists an element such that for all , (a ring satisfying this
property is termed a unit ring, or sometimes a “ring with identity”),
9. Multiplicative inverse: For each , there exists an element such that , where is the identity element.

A brief history of the past developments on this conjecture is a must to be read and understood; the significance comes due to the period of 150 years for which it remained an open problem,
  • Only after six years after Catalan formally defined the conjecture, a result was proposed by French mathematician, Victor Lebesgue. He stated that, for the equation, ; where is a prime; has no solutions for positive values of and . A proof of the same will be discussed in brief in the later part of the blog.
  • After Lebesgue’s work, all development solely consisted of small exponents, and then Naggel showed in 1921 that the difference between a third power and an other perfect power never is equal to 1.
  • In 1932, Selberg proved that, has no solution in positive integers when . A stronger result to this was proved by Ko Cho in 1965, that stated that the equation has no solutions for positive integers when .
  • Cassels made some observations for where and are odd-primes. He proved that is this equality holds for positive integers and , then divides and divides . For the case , this had already been shown by Naggel
  • Inkeri defined the concept of a Wieferich pair [the definition and explanation of the same is given above] in the concept of Catalan equation as follows:
    If the Catalan’s equation holds, then either is a Wieferich Pair, or divides , the class number of the cyclotomic field , or divides , the class number of the cyclotomic field

Cyclotomic Field:
In number theory, a cyclotomic field is a number field obtained by adjoining a complex primitive root of unity to , the field of rational numbers. The -th cyclotomic field (where ) is obtained by adjoining a primitive -th root of
Primitive root of unity
In mathematics, a root of unity, occasionally called a de Moivre number, is any complex number that gives when raised to some positive integer power .

  • Some time later Mihailescu proved that the Catalan equation has no solutions if and are odd and does not divide . By this result the Catalan conjecture became a theorem


More on Cyclotomic Fields:
Let be an odd-prime number. Let be the -th cyclotomic polynomial in i.e., . Consider the field extension of , where denotes a primitive -th root of unity. This is a field extension of degree and it is reducible in . We denote by from now on.
This field extension is Galois with Galois Group,

Since the map,


is an isomorphism
The automorphism acts in all embeddings as complex conjugation. Therefore, we call complex conjugation.
The fixed field of complex conjugation is , which is called the maximal real subfield of . We denote by . The field extension of has degree and it is Galois with Galois theory.
Another important concept that is

Mihailescu’s proof

To be contd…in the next blogpost!

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!

Friday, 17 November 2017

The Linear Quadratic Regulator

Optimal Control and Linear-Quadratic-Regulator (LQR)

Today, I will not write an introductory passage to write off my blog. Because, writing an introduction to Optimal Control in itself will required a blog. However, I will add in small tidbits as and when needed.
To understand the topic, we need some basic definitions with us.

1.
A control system can be represented in terms of State Space, as follows,

In the above formulation,
is the state vector; .
is the output vector; .
is the input vector; .
is the System Matrix; .
is the Input Matrix; .
is the Output Matrix; .
is the Feed-forward Matrix; .
Now, for a system to be controllable, we first define a matrix , called the controllability matrix, such that,

The system is controllable if has full row rank (i.e. rank() ).

We will assume that we deal with Controllable systems only.

Usually, a single input system’s state feedback controller is designed using the Eigen-value method, or Pole Placement method.

2.
Pole placement method is the methodology of finding the control vector in the form
So, the state space representation changes as,

is found as,

Here, are the desired pole locations. Note that is defined as

However, for a multi-input system the feedback gain i.e. is not unique.
Linear Quadratic Control strategy is used to deal with this issue.

Now, we dive into the Linear Quadratic Regulator (LQR) formulation, for an -input and -state system with ,. Consider a system,

Our aim is to find an open loop control , for such that we minimize:

where and are symmetric positive semi-definite matrices.
is a symmetric positive definite matrix. Note that , and are fixed and given data.
The controller aim is to basically keep close to 0 especially at , which is the final time.
In ,
  • works against the transient response.
  • works against the finite state.
  • works against the control effort.
The above formulation can regulate the output near .
Note that, we can define, and as where,
We can now have a theorem as follows,
For a system with fixed initial and final conditions, ; and clearly . We define our time horizon as such that . We find such that our cost function, is minimized. is defined as,

Here, the first term of is the final cost and the second term is the recurring cost.


Now, we will formulate some important functions that will convert the which is a constrained optimal control problem to a unconstrained optimal control problem. [THIS MAY NOT MAKE SENSE TO YOU, WHICH IS NATURAL. HOLD ON].

Note that, ( ) is called the Lagrangian.
is the Hamiltonian operator. Defined in terms of and as in . Or it can be defined as,

The above definition is in terms of as defined in the theorem. So, we define in the same lines. Just for convenience of computation.

can be written as
Equation , and together form a set of differential equations (in and , obviously) with split boundary conditions at and . Now, we can easily define in terms of or/and .
As mentioned earlier, the solution is found by converting from a constrained optimal problem to a constrained optimal problem using a Lagrange multiplier function :

Notice that,

Therefore,

As the Hamiltonian Function is defined in , thus,

The necessary condition for an optimal solution is of the modified cost with respect to all variations of the system be minimal at all times from to .
We will define analytically in the next post and formulate the Riccati Equation that will lay the foundation to some amazing control strategies.
Cheers!

Sunday, 5 November 2017

i!

Define the Factorial of a Complex number.

In usual sense, factorial is defined as,

Now, the not so usual definition is based on the famous Gamma Function,

There is an unique and very useful property,

To extend into the complex domain, we will first have to go through Analytic Continuation, please read about Analytic Continuation here.
Therefore, after analytic continuation, we can write it as,

For,
So, now, clearly,

By

Clearly,

For easier computation, please catch that,

Let’s break it down,


If you have reached this far, you obviously know how to solve the above integral.
Cheers!