Python Perceptron (Re-visited)

I feel like I’ve been staring at RStudio for way too long, so I’ve decided to give Python (SciKit-Learn) another go. I really need to recommend Anaconda Python for this, it contains everything you need for Scientific Python coding, including…

  • Python 2.7 (3.x is available)
  • SciKit-Learn – Everything machine learning related
  • Pandas – Dataframes (all kinds of dataframe stuff)
  • Matlibplot – The plotting library
  • iPython Notebook – A web based IDE, I like using this
  • Spyder – A nice IDE, I’m still getting to grips with it

Seriously, just get Anaconda Python, it is FREE.

I have done  previous post on the exact same problem however this uses DataFrames and is hopefully a little neater. There is some tweaks to plotting the hyperplane / decision boundary.

Lets get started

 Load in the data

Wow look at the DataFrame in action. We have 3 columns, A, B and Targets. A and B are just the input values. The target is a dichotomous value of 0 or 1, this could represent No or Yes, Product A or Product B, Dead or Alive, etc.

Plot the data (optional)

I always like to plot the data, I think its good practice to see what you are doing.

You should see this. If not, you might have forgotten the inline thing (above) or your install of Python is missing something.

Perceptron 1
Plotted data

Build the model and train

View the coefficients (optional)

I like to see what is going on

Plot the hyperplane / decision boundary

You should see this…

Perceptron 2
A scatter graph showing the data and the hyperplane. Everything to the right it a 1, everything to the left is a 0.

Using the system to make a prediction (and a confusion matrix)

Really we should be passing different data to it here, but here we can see the code to use the perceptron to predict the outcome only based on the inputs (in our case A and B).

The code also outputs a confusion matrix, it looks horrible.


Try this data to…

  • Use in the prediction of this model, how well does the system perform?
  • Rebuild the full model using this data
    • See how the hyperplane has moved?


One thought on “Python Perceptron (Re-visited)

Leave a Reply