Tuesday, 23 May 2017

Implement Simple Linear Regression With Python

Linear regression is a prediction method that is more than 200 years old.
Simple linear regression is a great first machine learning algorithm to implement as it requires you to estimate properties from your training dataset, but is simple enough for beginners to understand.
In this tutorial, you will discover how to implement the simple linear regression algorithm from scratch in Python.
After completing this tutorial you will know:
  • How to estimate statistical quantities from training data.
  • How to estimate linear regression coefficients from data.
  • How to make predictions using linear regression for new data.
Let’s get started.
How To Implement Simple Linear Regression From Scratch With Python
Photo by Kamyar Adl, some rights reserved.

Description

This section is divided into two parts, a description of the simple linear regression technique and a description of the dataset to which we will later apply it.

Simple Linear Regression

Linear regression assumes a linear or straight line relationship between the input variables (X) and the single output variable (y).
More specifically, that output (y) can be calculated from a linear combination of the input variables (X). When there is a single input variable, the method is referred to as a simple linear regression.
In simple linear regression we can use statistics on the training data to estimate the coefficients required by the model to make predictions on new data.
The line for a simple linear regression model can be written as:
where b0 and b1 are the coefficients we must estimate from the training data.
Once the coefficients are known, we can use this equation to estimate output values for y given new input examples of x.
It requires that you calculate statistical properties from the data such as mean, variance and covariance.
All the algebra has been taken care of and we are left with some arithmetic to implement to estimate the simple linear regression coefficients.
Briefly, we can estimate the coefficients as follows:
where the i refers to the value of the ith value of the input x or output y.
Don’t worry if this is not clear right now, these are the functions will implement in the tutorial.

Swedish Insurance Dataset

We will use a real dataset to demonstrate simple linear regression.
The dataset is called the “Auto Insurance in Sweden” dataset and involves predicting the total payment for all the claims in thousands of Swedish Kronor (y) given the total number of claims (x).
This means that for a new number of claims (x) we will be able to predict the total payment of claims (y).
Here is a small sample of the first 5 records of the dataset.
Using the Zero Rule algorithm (that predicts the mean value) a Root Mean Squared Error or RMSE of about 72.251 (thousands of Kronor) is expected.
Below is a scatter plot of the entire dataset.
Swedish Insurance Dataset
Swedish Insurance Dataset
You can download the raw dataset from here or here.
Save it to a CSV file in your local working directory with the name “insurance.csv“.
Note, you may need to convert the European “,” to the decimal “.”. You will also need change the file from white-space-separated variables to CSV format.

Tutorial

This tutorial is broken down into five parts:
  1. Calculate Mean and Variance.
  2. Calculate Covariance.
  3. Estimate Coefficients.
  4. Make Predictions.
  5. Predict Insurance.
These steps will give you the foundation you need to implement and train simple linear regression models for your own prediction problems.

1. Calculate Mean and Variance

The first step is to estimate the mean and the variance of both the input and output variables from the training data.
The mean of a list of numbers can be calculated as:
Below is a function named mean() that implements this behavior for a list of numbers.
The variance is the sum squared difference for each value from the mean value.
Variance for a list of numbers can be calculated as:
Below is a function named variance() that calculates the variance of a list of numbers. It requires the mean of the list to be provided as an argument, just so we don’t have to calculate it more than once.
We can put these two functions together and test them on a small contrived dataset.
Below is a small dataset of x and y values.
NOTE: delete the column headers from this data if you save it to a .CSV file for use with the final code example.
We can plot this dataset on a scatter plot graph as follows:
Small Contrived Dataset For Simple Linear Regression
Small Contrived Dataset For Simple Linear Regression
We can calculate the mean and variance for both the x and y values in the example below.
Running this example prints out the mean and variance for both columns.
This is our first step, next we need to put these values to use in calculating the covariance.

2. Calculate Covariance

The covariance of two groups of numbers describes how those numbers change together.
Covariance is a generalization of correlation. Correlation describes the relationship between two groups of numbers, whereas covariance can describe the relationship between two or more groups of numbers.
Additionally, covariance can be normalized to produce a correlation value.
Nevertheless, we can calculate the covariance between two variables as follows:
Below is a function named covariance() that implements this statistic. It builds upon the previous step and takes the lists of x and y values as well as the mean of these values as arguments.
We can test the calculation of the covariance on the same small contrived dataset as in the previous section.
Putting it all together we get the example below.
Running this example prints the covariance for the x and y variables.
We now have all the pieces in place to calculate the coefficients for our model.

3. Estimate Coefficients

We must estimate the values for two coefficients in simple linear regression.
The first is B1 which can be estimated as:
We have learned some things above and can simplify this arithmetic to:
We already have functions to calculate covariance() and variance().
Next, we need to estimate a value for B0, also called the intercept as it controls the starting point of the line where it intersects the y-axis.
Again, we know how to estimate B1 and we have a function to estimate mean().
We can put all of this together into a function named coefficients() that takes the dataset as an argument and returns the coefficients.
We can put this together with all of the functions from the previous two steps and test out the calculation of coefficients.
Running this example calculates and prints the coefficients.
Now that we know how to estimate the coefficients, the next step is to use them.

4. Make Predictions

The simple linear regression model is a line defined by coefficients estimated from training data.
Once the coefficients are estimated, we can use them to make predictions.
The equation to make predictions with a simple linear regression model is as follows:
Below is a function named simple_linear_regression() that implements the prediction equation to make predictions on a test dataset. It also ties together the estimation of the coefficients on training data from the steps above.
The coefficients prepared from the training data are used to make predictions on the test data, which are then returned.
Let’s pull together everything we have learned and make predictions for our simple contrived dataset.
As part of this example, we will also add in a function to manage the evaluation of the predictions called evaluate_algorithm() and another function to estimate the Root Mean Squared Error of the predictions called rmse_metric().
The full example is listed below.
Running this example displays the following output that first lists the predictions and the RMSE of these predictions.
Finally, we can plot the predictions as a line and compare it to the original dataset.
Predictions For Small Contrived Dataset For Simple Linear Regression
Predictions For Small Contrived Dataset For Simple Linear Regression

5. Predict Insurance

We now know how to implement a simple linear regression model.
Let’s apply it to the Swedish insurance dataset.
This section assumes that you have downloaded the dataset to the file insurance.csv and it is available in the current working directory.
We will add some convenience functions to the simple linear regression from the previous steps.
Specifically a function to load the CSV file called load_csv(), a function to convert a loaded dataset to numbers called str_column_to_float(), a function to evaluate an algorithm using a train and test set called train_test_split() a function to calculate RMSE called rmse_metric() and a function to evaluate an algorithm called evaluate_algorithm().
The complete example is listed below.
A training dataset of 60% of the data is used to prepare the model and predictions are made on the remaining 40%.
Running the algorithm prints the RMSE for the trained model on the training dataset.
A score of about 38 (thousands of Kronor) was achieved, which is much better than the Zero Rule algorithm that achieves approximately 72 (thousands of Kronor) on the same problem.

Extensions

The best extension to this tutorial is to try out the algorithm on more problems.
Small datasets with just an input (x) and output (y) columns are popular for demonstration in statistical books and courses. Many of these datasets are available online.

Friday, 19 May 2017

Introduction to ARM7 Based Microcontroller (LPC2148)

Increasingly, embedded systems developers and system-on-chip designers select specificmicroprocessor cores and a family of tools, libraries, and off-the-shelf components toquickly develop new microprocessor-based products and applications. ARM is one of the major options available for embedded system developer.

Over the last few years, the ARM architecture has become the most pervasive 32-bitarchitecture in the world, with wide range of ICs available from various IC manufacturers. ARM processors are embedded in products ranging from cell/mobilephones to automotive braking systems. A worldwide community of ARM partners andthird-party vendors has developed among semiconductor and product design companies,including hardware engineers, system designers, and software developers.

ARM7 is one of the widely used micro-controller family in embedded system application. This section is humble effort for explaining basic features of ARM-7.

ARM is a family of instruction set architectures for computer processors based on a reduced instruction set computing (RISC) architecture developed by British company ARM Holdings.
A RISC-based computer design approach means ARM processors require significantly fewer transistors than typical processors in average computers. This approach reduces costs, heat and power use. These are desirable traits for light, portable, battery-powered devices—including smartphones, laptops, tablet and notepad computers), and other embedded systems. A simpler design facilitates more efficient multi-core CPUs and higher core counts at lower cost, providing higher processing power and improved energy efficiency for servers and supercomputers.

SOME FACTS YOU MUST KNOW
In 2005, about 98% of all mobile phones sold used at least one ARM processor. The low power consumption of ARM processors has made them very popular: 37 billion ARM processors have been produced as of 2013, up from 10 billion in 2008. The ARM architecture (32-bit) is the most widely used architecture in mobile devices, and most popular 32-bit one in embedded systems.
According to ARM Holdings, in 2010 alone, producers of chips based on ARM architectures reported shipments of 6.1 billion ARM Based processors, representing 95% of smartphones, 35% of digital televisions and set-top boxes and 10% of mobile computers. It is the most widely used 32-bit instruction set architecture in terms of quantity produced.

LET’S START WITH LPC 2148
LPC2148 is the widely used IC from ARM-7 family. It is manufactured by Philips and it is pre-loaded with many inbuilt peripherals making it more efficient and a reliable option for the beginners as well as high end application developer.
Let us go through the features of LPC214x series controllers.

• 8 to 40 kB of on-chip static RAM and 32 to 512 kB of on-chip flash program memory.128 bit wide interface/accelerator enables high speed 60 MHz operation.
• In-System/In-Application Programming (ISP/IAP) via on-chip boot-loader software.Single flash sector or full chip erase in 400 ms and programming of 256 bytes in 1ms.
• EmbeddedICE RT and Embedded Trace interfaces offer real-time debugging with theon-chip RealMonitor software and high speed tracing of instruction execution.
• USB 2.0 Full Speed compliant Device Controller with 2 kB of endpoint RAM.In addition, the LPC2146/8 provides 8 kB of on-chip RAM accessible to USB by DMA.
• One or two (LPC2141/2 vs. LPC2144/6/8) 10-bit A/D converters provide a total of 6/14analog inputs, with conversion times as low as 2.44 us per channel.
• Single 10-bit D/A converter provides variable analog output.
• Two 32-bit timers/external event counters (with four capture and four comparechannels each), PWM unit (six outputs) and watchdog.
• Low power real-time clock with independent power and dedicated 32 kHz clock input.
• Multiple serial interfaces including two UARTs (16C550), two Fast I2C-bus(400 kbit/s), SPI and SSP with buffering and variable data length capabilities.
• Vectored interrupt controller with configurable priorities and vector addresses.
• Up to 45 of 5 V tolerant fast general purpose I/O pins in a tiny LQFP64 package.
• Up to nine edge or level sensitive external interrupt pins available.
• On-chip integrated oscillator operates with an external crystal in range from 1 MHz to30 MHz and with an external oscillator up to 50 MHz.
• Power saving modes include Idle and Power-down.
• Individual enable/disable of peripheral functions as well as peripheral clock scaling foradditional power optimization.
• Processor wake-up from Power-down mode via external interrupt, USB, Brown-OutDetect (BOD) or Real-Time Clock (RTC).
• Single power supply chip with Power-On Reset (POR) and BOD circuits:
– CPU operating voltage range of 3.0 V to 3.6 V (3.3 V ± 10 %) with 5 V tolerant I/Opads.

* adopted from datasheet of LPC 2148. Each inbuilt peripheral will be explained in brief later on.

The list of feature is enough to explain why it has covered such a huge market for high end applications such as mobile phones, tablets etc.

FIRST STEP- HARDWARE REQUIREMENT

Here is the pin configuration of LPC 2148.
LPC2148 Pin Diagram
Now let us start with the hardware requirement of LPC2148.
LPC2148 need minimum below listed hardware to work properly.

1.                  Power Supply
2.                  Crystal Oscillator
3.                  Reset Circuit
4.                  RTC crystal oscillator (This is not necessary if you are not using RTC. However this is considered as necessary requirement)
5.                  UART

1. Power Supply
LPC2148 works on 3.3 V power supply. LM 117 can be used for generating 3.3 V supply. However, basic peripherals like LCD, ULN 2003 (Motor Driver IC) etc. works on 5V. So AC mains supply is converted into 5V using below mentioned circuit and after that LM 117 is used to convert 5V into 3.3V.
Power Supply Block Diagram

Block diagram for power supply is given below.
         
Transformer:It is used to step down 230V AC to 9V AC supply and provides isolation between power grids and circuit.

Rectifier: It is used to convert AC supply into DC.

Filter:It is used to reduce ripple factor of DC output available from rectifier end.

Regulator:It is used to regulate DC supply output.
Circuit for this is as shown below.


Here, Regulator IC 7805 is used to provide fix 5V dc supply.

Now we can use LM 117 for generating 3.3V supply from 5V using below circuit.


Calculations


2. Reset Circuit

Reset button is essential in a system to avoid programming pitfalls and sometimes to manually bring back the system to the initialization mode. Circuit diagram for reset is as shown below.

MCP 130T is a special IC used for providing stable RESET signal to LPC 2148.
Reset Circuit

3. Oscillator Circuit
Oscillations, the heartbeat, are provided using a crystal and are necessary for the system to work.


The value of capacitors C20 & C21 depends upon the frequency of crystal Y3. General circuit and its equivalent circuit is as shown below.


Recommended values are as shown in table.


We can also use external oscillator for providing system clock. Circuit for this application is as given below.

4. RTC Oscillator Circuit
It provides clock for RTC operation.


5. UART
LPC 2148 has inbuilt ISP which means we can program it within the system using serial communication on COM0. It has also COM1 for serial communication. MAX 232/233 IC must be used for voltage logic conversion. Related connections are as given below.


Once above listed circuit design is ready, we are ready to go further.

What is Power Line Communication?