Title: Perceptron In Scikit
Slug: perceptron_in_scikit
Summary: Perceptron Learning using Python and scikit-learn.
Date: 2016-11-04 12:00
Category: Machine Learning
Tags: Other
Authors: Chris Albon
A perceptron learner was one of the earliest machine learning techniques and still from the foundation of many modern neural networks. In this tutorial we use a perceptron learner to classify the famous iris dataset. This tutorial was inspired by Python Machine Learning by Sebastian Raschka.
In [1]:
# Load required libraries
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np
In [2]:
# Load the iris dataset
iris = datasets.load_iris()
# Create our X and y data
X = iris.data
y = iris.target
In [3]:
# View the first five observations of our y data
y[:5]
Out[3]:
In [4]:
# View the first five observations of our x data.
# Notice that there are four independent variables (features)
X[:5]
Out[4]:
In [5]:
# Split the data into 70% training data and 30% test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
In [6]:
# Train the scaler, which standarizes all the features to have mean=0 and unit variance
sc = StandardScaler()
sc.fit(X_train)
Out[6]:
In [7]:
# Apply the scaler to the X training data
X_train_std = sc.transform(X_train)
# Apply the SAME scaler to the X test data
X_test_std = sc.transform(X_test)
In [8]:
# Create a perceptron object with the parameters: 40 iterations (epochs) over the data, and a learning rate of 0.1
ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0)
# Train the perceptron
ppn.fit(X_train_std, y_train)
Out[8]:
In [9]:
# Apply the trained perceptron on the X data to make predicts for the y test data
y_pred = ppn.predict(X_test_std)
In [10]:
# View the predicted y test data
y_pred
Out[10]:
In [11]:
# View the true y test data
y_test
Out[11]:
In [12]:
# View the accuracy of the model, which is: 1 - (observations predicted wrong / total observations)
print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))