Wednesday, February 25, 2015

A peek into literacy in India: Statistical Learning with R

In this post I take a peek into the literacy landscape across India as a whole using R language.  The dataset from Open Government Data (OGD) platform India was used for this purpose. This data is based on the 2011 census. The XL sheets for the states were downloaded for data for each state. The Union Territories were not included in the analysis.
A thin slice of the data from each data set was taken from the data for each individual state (Note: This could also have been done from the consolidated india.xls XL sheet which I came to know of, much later).
I calculate the following for age group
Males (%) attending education institutions = (Males attending educational institutions * 100)/ Total males
Females (%) attending education institutions = (Females attending educational institutions * 100)/ Total Females
This is then plotted as a bar chart with the age distribution. I then overlay the national average for each state over the barchart to check whether the literacy in the state is above or below the national average. The implementation in R is included below
The code and data can be forked/cloned from GitHub at india-literacy
The results based on the analysis is given below.
  1. Kerala is clearly the top ranker with the literacy rates for both males and females well above the average
  2. The states with above average literacy are – Kerala, Himachal Pradesh, Uttarakhand, Tamil Nadu, Haryana, Himachal Pradesh, Karnataka, Maharashtra, Punjab, Uttarakhand
  3. The states with just about average literacy – Karnataka, Andhra Pradesh, Chattisgarh, Gujarat, Madhya Pradesh, Odisha, West Bengal
  4. The states with below average literacy – Uttar Pradesh, Bihar, Jharkhand, Arunachal Pradesh, Assam, Jammu and Kashmir, Jharkhand, Rajasthan
 
A brief implementation of the basic code in R is shown bwelow
# Read the Arunachal Pradhesh literacy related data
arunachal = read.csv("arunachal.csv")
# Create as a matrix
arunachalmat = as.matrix(arunachal)
arunachalTotal = arunachalmat[2:19,7:28]
# Take transpose as this is necessary for plotting bar charts
arunachalmat = t(arunachalTotal)
# Set the scipen option to format the y axis (otherwise prints as e^05 etc.)
getOption("scipen")
opt <- 20="" br="" options="" scipen="">getOption("scipen")
#Create a vector of total Males & Females
arunachalTotalM = arunachalmat[3,]
arunachalTotalF = arunachalmat[4,]
#Create a vector of males & females attending education institution
arunachalM = arunachalmat[6,]
arunachalF = arunachalmat[7,]
#Calculate percent of males attending education of total
arunachalpercentM = round(as.numeric(arunachalM) *100/as.numeric(arunachalTotalM),1)
barplot(arunachalpercentM,names.arg=arunachalmat[1,],main ="Percentage males attending educational institutions in Arunachal Pradesh",
xlab = "Age", ylab= "Percentage",ylim = c(0,100), col ="lightblue", legend= c("Males"))
points(age,indiapercentM,pch=15)
lines(age,indiapercentM,col="red",pch=20,lty=2,lwd=3)
legend( x="bottomright",
legend=c("National average"),
col=c("red"), bty="n" , lwd=1, lty=c(2),
pch=c(15) )
#Calculate percent of females attending education of total
arunachalpercentF = round(as.numeric(arunachalF) *100/as.numeric(arunachalTotalF),1)
barplot(arunachalpercentF,names.arg=arunachalmat[1,],main ="Percentage females attending educational institutions in Arunachal Pradesh ",
xlab = "Age", ylab= "Percentage", ylim = c(0,100), col ="lightblue", legend= c("Females"))
points(age,indiapercentF,pch=15)
lines(age,indiapercentF,col="red",pch=20,lty=2,lwd=3)
legend( x="bottomright",
legend=c("National average"),
col=c("red"), bty="n" , lwd=1, lty=c(2),
pch=c(15) )
A) Overall plot for India
a) India - Males
india-males
b) India - females
india-females
The plots for each individual state is given below
1) Literacy in Tamil Nadu
Tamil Nadu is slightly over the national average. The women seem to do marginally better than the males
a) Tamil Nadu - males
tn-males
b) Tamil Nadu - females
tn-females
2) Literacy in Uttar Pradesh
UP is slightly below the national average. Women are comparatively below men here
a) Uttar Pradesh - males
UP-males
b) Uttar Pradesh - females
UP-females
3) Literacy in Bihar
Bihar is well below the national average for both men and women
a) Bihar - males
bihar-males
b) Bihar - females
bihar-females
4. Literacy in Kerala
Kerala is the winner all the way in literacy with almost 100% literacy across all age groups
a) Kerala - males

kerala-females
b) Kerala -females
kerala-females
 
5. Literacy in Andhra Pradesh
AP just meets the national average for literacy.
a) Andhra Pradesh - males
andhra-males
b) Andhra Pradesh - females
andhra-females
6. Literacy in Arunachal Pradesh
Arunachal Pradesh is below average for most of the age groups
a) Arunachal Pradesh - males
arunachal-males
b) Arunachal Pradesh - females
arunachal-females
7. Literacy in  Assam
Assam is below national average
a) Assam - males
assam-males
b) Assam - females
assam-females
 
8. Literacy in Chattisgarh
Chattisgarh is on par with the national average for both men and women
a) Chattisgarh - males
chattisgarh-males
b) Chattisgarh - females
chattisgarh-females
 
9. Literacy in Gujarat
Gujarat is just about average
a) Gujarat - males
gujarat-males
b) Gujarat - females
gujarat-females
10. Literacy in Haryana
Haryana is slightly above average
a) Haryana - males
haryana-males
b) Haryana - females
haryana-females11.  Literacy in Himachal Pradesh
Himachal Pradesh is cool and above average.
a) Himachal Pradesh - males
himachal-males
 
b) Himachal Pradesh - females
himachal-females
12. Literacy in Jammu and Kashmir
J & K is marginally below average
a) Jammu and Kashmir - males
jk-males
b) Jammu and Kashmir - females
jk-females
 
13. Literacy in Jharkhand
Jharkhand is some ways below average
a) Jharkhand - males
jharkand-males
b) Jharkhand - females
jharkand-feamles
14. Literacy in Karnataka
Karnataka is on average for men. Womem seem to do better than men here
a) Karnataka - males
karnataka-males
b) Karnataka - females
karnataka-females
15. Literacy in Madhya Pradesh
Madhya Pradesh meets the national average
a) Madhya Pradesh - males
mp-males
b) Madhya Pradesh - females
mp-females
16. Literacy in Maharashtra
Maharashtra is front-runner in literacy
a) Maharashtra - females
maharashtra
b) Maharastra - females
maharashtra-feamles
 
17. Literacy in Odisha
Odisha meets national average
a) Odisha - males
odisha-males
b) Odisha - females
odisha-females
 
18. Literacy in  Punjab
Punjab is marginally above average with women doing even better
a) Punjab - males
punjab-males
b) Punjab - females
punjab-females19. Literacy in Rajasthan
Rajasthan is average for males and below average for females
a) Rajasthan - males
rajashthan-males
b) Rajasthan - females
rajasthan-females20. Literacy in Uttarakhand
Uttarakhand rocks and is above average
a) Uttarakhand - males
uttarkhan-males
b) Uttarakhand - females
uttarkhand-females
21. Literacy in West Bengal
West Bengal just about meets the national average.
a) West Bengal - males
wb-males
 
b) West Bengal - females
wb-females
The code can be cloned/forked from GitHub  india-literacy. I have done my analysis on the overall data. The data is further sub-divided across districts in each state and further into urban and rural. Many different ways of analysing are possible. One method is shown here
Conclusion
  1. Kerala is clearly head and shoulders above all states when it comes to literacy
  2. Many states are above average. They are Kerala, Himachal Pradesh, Uttarakhand, Tamil Nadu, Haryana, Himachal Pradesh, Karnataka, Maharashtra, Punjab, Uttarakhand
  3. States with average literacy are – Karnataka, Andhra Pradesh, Chattisgarh, Gujarat, Madhya Pradesh, Odisha, West Bengal
  4. States which fall below the national average are – Uttar Pradesh, Bihar, Jharkhand, Arunachal Pradesh, Assam, Jammu and Kashmir, Jharkhand, Rajasthan
[polldaddy rating="7295683"]

Monday, February 23, 2015

Statistical learning with R: A look at literacy in Tamil Nadu

In this post I make my first foray into data mining using the R language. As a start, I picked up the data from the Open Government Data (OGD Platform of India from the Ministry of Human Resources. There are many data sets under Education. To get started I picked the data set on Tamil Nadu which deals with the population attending educational institutions by age, sex and institution type. Similar data is available for all states.
I wanted to start off on a small scale, primarily to checkout some of the features of the R language. R is clearly the language of choice for processing large amounts of data. R has close to 4000+ packages that can do various things like statistical, regression analysis etc. However I found this is no easy task. There are a zillion ways in which you can take cross-sections of a large dataset. Some of them will provide useful insights while others will lead you nowhere.
Data science, which is predicted to be the technology of the future based on with the mountains of data being generated daily, will in my opinion, will be more of an art and less of a science. There will be wizards who will be able to spot remarkable truths in the mundane data while others will not be that successful.
Anyway back to my attempt to divine intelligence in the Tamil Nadu(TN)  literacy data. The data downloaded was an Excel sheet with 1767 rows and 28 columns. The first 60 rows deal with the overall statistics of literacy in Tamil Nadu state as a whole. Further below are the statistics on the individual districts of Tamil nadu.
Each of this is further divided into urban and rural parts. The data covers persons from the age of 4 upto the age of 60 and whether they attended school, college, vocational institute etc. To make my initial attempt manageable I have just focused on the data for Tamil Nadu state as a whole including the breakup of the urban and rural data.
My analysis is included below. The code and the dataset for this implementation is in R language and can be cloned from GitHub at tamilnadu-literacy-analysis
Analysis of Tamil Nadu (total)
The total population of Tamil Nadu based on an age breakup is shown below
1) Total population Tamil Nadu 
tntotal
2) Males  & Females attending education institutions in TN
tneduThere are marginally more males attending educational institutions. Also the number of persons attending educational institutions seems to drop from 11 years of age. There is a spike around 20-24 years and people go to school and college at this age. See pie chart 8) below
3) Percentage of males attending educational institution of the total males
percenteduM
4) Percentage females attending educational institutions in TN 
percenteduF
There is a very similar trend between males and females. The attendance peaks between 9 - 11 years of age and then falls to roughly 50% around 15-19 years and rapidly falls off
5) Boys and girls attending school in TN
tnschool
For some reason there is a marked increase for boys and girls around 20-24. Possibly people repeat classes around this age
6) Persons attending college in TN
tncollege
7) Educational institutions attended by persons between 15- 19 years
tnschool-1
8) Educational institutions attended by persons between 20-24 tnschool-2
As can be seen there is a large percentage (30%)  of people in the 20-24 age group who are in school. This is probably the reason for the spike in "Boys and girls attending school in TN" see 2) for the 20-24 years of age
Education in rural Tamil Nadu
1) Total rural population Tamil Nadu 
ruraltotal
2) Males  & Females attending education institutions in  rural TNruraledu3) Percentage of rural males attending educational institution
percentruralM
4) Percentage females attending educational institutions in rural TN of total females
percentruralF
The persons attending education drops rapidly to 40% between 15-19 years of age for both males and females
5) Boys and girls attending school in rural TN
ruralschool
6) Persons attending college in rural TN
ruralcollege
7) Educational institutions attended by persons between 15- 19 years in rural TN
rural-1
8) Educational institutions attended by persons between 20-24 in rural TN
rural-2
As can be seen there is a large percentage (39%)  of rural people in the 20-24 age group who are in school
Education in urban Tamil Nadu
1) Total population in urban Tamil Nadu 
urbantotal
2) Males  & Females attending education institutions in urban TNurbanedu3) Percentage of males attending educational institution of the total males in urban TNpercentruralM4) Percentage females attending educational institutions in urban TN
percenturbanF
5) Boys and girls attending school in urban TN
urbanschool
6) Persons attending college in urban TN
urbancollege
7) Educational institutions attended by persons between 15- 19 years in urban TN
urban-1
8) Educational institutions attended by persons between 20-24 in urban TN
urban-2
 
As can be seen there is a large percentage (25%) of rural people in the 20-24 age group who are in school
The R implementation and the Tamil Nadu dataset can be cloned from my repository in GitHub at tamilnadu-literacy-analysis 
The above analysis is just one of a million possible ways the data can be analyzed and visually represented. I hope to hone my skill as progress along in similar analysis.
Hasta la vista! I'll be back.
Watch this space!
[polldaddy rating="7295683"]

An Octave primer

Here is a simple Octave Primer. Octave is a powerful language for implementing Machine Learning algorithms. As I have mentioned its strength is its simplicity. I am including some basic commands with which you can get by implementing fairly complex code
%%Matrix
A matrix can be created as a = [1 2 3; 4 7 8; 12 35 14]; % This is 3 x 3 matrix
Matrix multiplication can be done between m x n * n x k matrix as follows
a = [4 56 3; 2 3 4]; b = [23 1; 3 12; 34 12]; % a = 3 x 2 matrix b = 2 x 3 matrix
c = a*b; %% c = 3 x 2 * 2 * 3 = 3 x 3 matrix
c =
362 712
191 86
%%Inverse of a matrix can be obtained by
d = pinv(c);
octave-3.2.4.exe:37> d = pinv(c)
d =
-8.2014e-004 6.7900e-003
1.8215e-003 -3.4522e-003
%%Transpose of a matrix
e = c'; % e is the transpose of done
octave-3.2.4.exe:38> e = c'
e =
362 191
712 86
The following operations are done on all elements of a matrix or a vector
k = 5;
a = [1 2; 3 4; 5 6]; k = 5.23;
c = k * a;
d = a - 2
e = a / 5
f = a .* a % Dot product
g = a .^2; % Square each elements
%% Select slice of matrix
b = a(:,2); % Select column 2 of matrix a (all rows)
c = a(2,:) % Select row of matrix 'a' (all columns)
d = [7 8; 8 9; 10 11; 12 13]; % 4 rows 2 columns
d(2:3,:); %Select from rows 2 to 3 (all columns)
octave-3.2.4.exe:41> d
d =
7 8
8 9
10 11
12 13
octave-3.2.4.exe:43> d(2:3,:)
ans =
8 9
10 11
%% Appending rows to matrix
a = [ 4 5; 5 6; 5 7; 9 8]; % 4 x 2
b = [ 1 3; 2 4]; % 2 x 2
c = [ a; b] % stack a over b
d = [b ; a] % stack b over a*b

octave-3.2.4.exe:44> a = [ 4 5; 5 6; 5 7; 9 8] % 4 x 2
a =
4 5
5 6
5 7
9 8
octave-3.2.4.exe:45> b = [ 1 3; 2 4] % 2 x 2
b =
1 3
2 4
octave-3.2.4.exe:46> c = [ a; b] % stack a over b
c =
4 5
5 6
5 7
9 8
1 3
2 4
octave-3.2.4.exe:47> d = [b ; a] % stack b over a*b
d =
1 3
2 4
4 5
5 6
5 7
9 8
%% Appending columns
a = [ 1 2 3; 3 4 5]; b = [ 1 2; 3 4];
c = [a b];
d = [b a];
octave-3.2.4.exe:48> a = [ 1 2 3; 3 4 5]
a =
1 2 3
3 4 5
octave-3.2.4.exe:49> b = [ 1 2; 3 4]
b =
1 2
3 4
octave-3.2.4.exe:50> c = [a b]
c =
1 2 3 1 2
3 4 5 3 4
octave-3.2.4.exe:51> d = [b a]
d =
1 2 1 2 3
3 4 3 4 5
%%Size of a matrix
[c d ] = size(a);

Creating a matrix of all zeros or ones
d = ones(3,2);
e = zeros(4,3);

%Appending an intercept term to a matrix
a = [1 2 3; 4 5 6]; %2 x 3
b = ones(2,1);
a = [b a];
%% Plotting
Creating 2 vectors
x = [1 3 4 5 6];
y = [5 6 7 8 9];
plot(x,y);

%%Create labels
xlabel("X values); ylabel("Y values);
axis([1 10 4 10]); % Set the range of x and y
title("Test plot);
%%Creating a 3D scatter plot
If we have 3 column csv file then we can load the data as follows
data = load('values.csv');
X = data(:, 1:2);
y = data(:, 3);
scatter3(X(:,1),X(:,2),y,[],[240 15 15],'x'); % X(:,1) - x axis X(:,2) - yaxis y[] - z axis
%% Drawing a 3D mesh
x = linspace(0,xrange + 20,10);
y = linspace(1,yrange+ 20,10);
[XX, YY ] = meshgrid(x,y);

[a b] = size(XX)
Draw the mesh
for i=1:a,
for j= 1:b,
ZZ(i,j) = [1 (XX(i,j)-mu(1))/sigma(1) (YY(i,j) - mu(2))/sigma(2) ] * theta;
end;
end;
mesh(XX,YY,ZZ);
%% Creating different polynomial equations
Let X be a feature vector
then
X = [X X.^2 X^3] %X X^2 X^3
This can be created using a for loop as follows
for i= 1:n
xtemp = xinput .^i;
x = [x xtemp];
end;
 
Finally while doing multivariate regression if we wanted to create polynomial terms of higher we could do as follows. Let us say we have a feature vector X made of 3 features x1, x2,
Let us say we wanted to create a polynomial of the form x1^2 x1.x2 x2^2 then we could create X as
X = [X(:,1) .^2 X(:,1) . X(:,2) X(:,2) .^2]
As you can see Octave is really powerful language for Machine Learning and has just a few handful of constructs with which one can implement powerful Machine Learning algorithms

How to program – Some essential tips

If one follows the arrow of time from the early 1980s to the present day, the number of programming problems have not only proliferated but have also become more difficult. Fortunately  programming in itself has  become more manageable with massive increases in computing horsepower, smarter tools and instant availability of information on the internet, typically with the click of a mouse.
Learning to program is no easy task, but can be done with the right mix of attitude, curiosity and interest. Becoming adept at programming, however, is something else. An interesting essay in this context is Peter Norvig’s ‘Teach yourself programming in 10 years’
Back in the 1980s when I wrote my first Fortran program on my college Mainframe, programming was a lengthy exercise, spanning several days.
1
My first program was to plot a sine wave of characters on a computer printout. Running this program required the following several steps
  1. Enter the program on a teletype terminal and create a stack of Hollerith (punched) cards
  2. Submit the stack of cards to the computer center
  3. The computer center would do a batch execute in the evening on the Mainframe
  4. God forbid, if your program has a syntax error. If you did find an error, go back to step 1, the next day.
  5. Assuming everything is fine, the computer center would run your program and your output (printout) would be placed in the appropriate pigeon hole which you would need to pick up the next day.
The whole exercise to write a small-sized program could take anywhere between a couple of days to a whole week.
In the early 1990s things got a little better where one could code, compile, link and execute sitting at one’s desk. However while the programming itself got much simpler than before, certain tasks were still difficult.  Till the late 90s programs of any sort had to be written using a regular text editor (vi , emacs etc.)  You would then have to go through the process of compiling, linking and executing.
An angry compiler would typically spew forth venom at missing semi-colons, undeclared variables, and uninitialized values. This would happen till you are able to iron out all syntax errors.  Then you would link, get undefined symbols and have to include appropriate libraries etc. And then finally you would execute your code, only to have it crash. The process of debugging would then start.
Luckily technology has made life a whole lot easier except for the last step where you could still  run into an execution errors . In these days an IDE (Interactive Development Environment) like Eclipse will flag syntax errors, missing definitions/declarations etc. as you write your code. Moreover Eclipse can also indicate which libraries (imports) you would need to include in your package for it to build. The only missing step in IDEs of these days is the ability to predict possible execution errors in your program.  I wouldn’t be surprised, if in future, like Microsoft Word,  the IDE is able to tell you if a programming construct does not make sense.
So things have gotten a lot easier for the programmer. The following tips for are particularly useful as you progress along in programming
  1. These days when you are learning a new programming language it is not necessary to know the language from cover to cover by reading a book. In those days when we learnt C it was necessary to know everything from bit structures, macros, pragma etc. The reason being that every syntax or execution error one had to rush to get the textbook and thumb through it for the answer. Not so, in these days of Google. You have the world's library at your fingertips.
  2. To get started it is necessary to learn just the most important programming constructs of the language say structure, class, car, cdr besides the usual suspects like loops, conditions and case constructs
  3. Download and install an IDE for the language. In most case Eclipse will work
  4. Try to write a simple program and test out your code.
  5. To do any sort of programming these days you will necessarily need to make 3 friends
    1. Google
    2. Stackoverflow
    3. Git & GitHub
  6. Honing your Googling skills is very important. There are answers to almost any sort of programming problems out there. You would be surprised to know that there are many others who did exactly the same stupid mistake that you did out there. Also googling will take you to interesting tutorials, blogs, articles that discuss different aspects of the programming language and the problem you are trying to solve
  7. Stackoverflow is really a God send to all programmers. There are so many questions on so many aspects of every programming language on earth there. If you spend time searching Stackoverflow you are bound to find answers, code snippets that you can readily use in your code
  8. Post your questions in stackoverflow when you don’t find the answers there. You are bound to get quick answers. Thanks to the gamification of Stackoverflow (points, upvotes,badges  etc) that has been created on Stackoverflow.
  9. Git & GitHub: I would suggest that you download and install GitHub for Windows. This will provide you with version control on your desktop. You can modify code while being to switch back to an earlier version with Git. Read up a good tutorial on Git for Windows
  10. Once you have working code you push it onto GitHub and share with other programmers
Now that you have the basic setup here are few other extremely important tips
  1. The most important criteria for programming is ‘attitude’. Initially you are bound to get frustrated, angry, irritated etc. But it is necessary to look at the errors that you get with the right attitude. Know that an error is telling you something. Usually the answers to your mistake are in the ‘error message’ itself. Look at it closely and try to understand it. You will learn a lot more when you learn from errors than from copy-pasting from somebody else’s code, even if works right the first time around!
  2. Make sure you do something different each time. As Einstein said “ If you keep doing the same thing, you will keep getting the same result’
  3. There are different ways to debug your code. You could use the debugger and single step through the code and keep checking the values of the variables. I personally prefer print statements to localize where things are going wrong. I then try to narrow down the problem to a few lines of code and try to take it apart.
Hopefully the above tips are useful. Programming can be creative activity and will be indispensable in our future.
Above all have fun coding, there are so many possibilities these days!

Monday, February 16, 2015

Applying the principles of Machine Learning

While working with multivariate regression there are certain essential principles that must be applied to ensure the correctness of the solution while being able to pick the most optimum solution. This is all the more important when the problem has a large number of features. In this post I apply these important principles to a regression data set which I was able to pull of the internet. This data set was taken from the UCI Machine Learning repository and deals with Boston housing data.  The housing data provides the cost of house in Boston suburbs given the number of rooms, the connectivity to main highways, and crime rate in the area and several other data.  There are a total of 506 data points in this data set with a total of 13 features.
This seemed a reasonable dataset to start to try out the principles of Machine Learning I had picked up from Coursera’s ML course.
Out of a total of 13 features 2 features ’ZN’ and ‘CHAS’ proximity to  Charles river were dropped as the values were mostly zero in these columns . The remaining 11 features were used to map to the output variable of the price.
The following key rules have been applied on the
  • The dataset was divided into training samples (60%), cross-validation set (20%) and test set (20%) using a random index
  • Try out different polynomial functions while performing gradient descent to determine the theta values
  • Different combinations of ‘alpha’ learning rate and ‘lambda’ the regularization parameter were tried while performing gradient descent
  • The error rate is then calculated on the cross-validation and test set
  • The theta values that were obtained for the lowest cost for a polynomial was used to compute and plot the learning curve for the different polynomials against increasing number of training and cross-validation test samples to check for bias and variance.
  • The plot of the cost versus the polynomial degree was plotted to obtain the best fit polynomial for the data set.
A multivariate regression hypothesis can be represented as
hθ(x) = θ0 + θ1x1 + θ2x2 + θ3x3 + θ4x4 + …
And the cost can is determined as
J(θ0, θ1, θ2, θ3..) = 1/2m ∑ (hΘ (xi) -yi)2
The implementation was done using Octave. As in my previous posts some functions have not been include to comply with Coursera’s Honor Code. The code can be cloned from GitHub at machine-learning-principles
a) housing compute.m. In this module I perform gradient descent for different polynomial degrees and check the error that is obtained when using the computed theta on the cross validation and test set
max_degrees =4;
J_history = zeros(max_degrees, 1);
Jcv_history = zeros(max_degrees, 1);
for degree = 1:max_degrees;
[J Jcv alpha lambda] = train_samples(randidx, training,cross_validation,test_data,degree);
end;
b) train_samples.m – This module uses gradient descent to check the best fit for a given polynomial degree for different combinations of alpha (learning rate) and lambda( regularization).
for i = 1:length(alpha_arr),
for j = 1:length(lambda_arr)
alpha = alpha_arr{i};
lambda= lambda_arr{j};
% Perform Gradient descent
% Compute error for training sample for computed theta values
% Compute the error rate for the cross validation samples
% Compute the error rate against the test set
end;
end;
c) cross_validation.m – This module uses the theta values to compute cost for the cross validation set
d) test-samples.m – This modules computes the error when using the trained theta on the test set
e) poly.m - This module constructs polynomial vectors based on the degree as follows
function [x] = poly(xinput, n)
x = [];
for i= 1:n
xtemp = xinput .^i;
x = [x xtemp];
end;
e) learning_curve.m – The learning curve module plots the error rate for increasing number of training and cross validation samples. This is done as follows. For the theta with the lowest cost as determined by gradient descent
for i from 1 to 100
  • Compute the error for ‘i' training samples
  • Compute the error for ‘i’ cross-validation
  • Plot the learning curve to determine the bias and variance of the polynomial fit
This is included below
for i = 1: 100
xsample = xtrain(1:i,:);
ysample = ytrain(1:i,:);
size(xsample);
size(ysample);
[xsample] = poly(xsample,degree);
xsample= [ones(i, 1) xsample];
[c d] = size(xsample);
theta = zeros(d, 1);
% Minimize using fmincg
J = computeCost(xsample, ysample, theta);
Jtrain(i) = J;
xsample_cv = xcv(1:i,:);
ysample_cv = ycv(1:i,:);
[xsample_cv] = poly(xsample_cv,degree);
xsample_cv= [ones(i, 1) xsample_cv];
J_cv = computeCost(xsample_cv, ysample_cv,theta)
Jcv(i) = J_cv;
end;
Finally a plot is done been different lambda and the cost.
The results are included below
A) Polynomial degree 1
Convergence graph
convergence-1
Learning curve
learning-curve-1
The above figure does show a stronger bias. Note: the learning curve was done with around 100 samples
B) Polynomial degree 2
Convergence graph
convergence-2
Learning curve
learning-curve-2
The learning curve for degree 2 shows a stronger variance.
C) Polynomial degree 3
Convergence graph
convergence-3
Learning curve
learning-curve-3
D) Polynomial degree 4
Convergence graph
convergence-4
E) Learning curve
learning-curve-4
This plot is useful to determine which polynomial degree will give the best fit for the dataset and the lowest cost
degree-cost-1
Clearly from the above it can be seen that degree 2 will give a good fit for the data set.
F) Lambda vs Cost function
lambda-cost-1
The above code demonstrates some key principles while performing multivariate regression
The code can be cloned from GitHub at machine-learning-principles
[polldaddy rating="7295683"]