Perceptron
A perceptron is a fundamental machine learning algorithm used for binary classification tasks. It is designed to predict whether an input belongs to one of two possible classes, often represented as 0 or 1. This simplicity makes the perceptron one of the least complex algorithms in the realm of machine learning, yet it serves as a foundational building block for more advanced models.
Training a Perceptron
Online Learning
In the book Introducing Data Science: Big data, machine learning, and more, using Python tools, the perceptron is described as being trainable using a method known as online learning. This approach allows the perceptron to update its weights incrementally with each new observation it encounters. This method is particularly useful in scenarios where data arrives in a stream or when computational resources are limited, as it allows the model to learn continuously and adapt to new data without the need to retrain from scratch.
An example of training a perceptron using online learning is illustrated in Listing 4.1. This listing demonstrates how the perceptron updates its weights based on each new piece of data it processes. The process involves adjusting the weights to minimize the error in predictions, thereby improving the model's accuracy over time.
Listing 4.1. Training a perceptron by observation
In this example, the perceptron is applied to a binary classification problem, such as predicting whether a customer will make a purchase or not. The perceptron learns from each customer interaction, updating its prediction model to better classify future customers based on their attributes.
Perceptron Algorithm
In Machine Learning Algorithms in Depth, the perceptron is described as a type of linear classifier that employs a mistake-driven learning algorithm. The perceptron iteratively updates its parameters based on classification errors, adjusting the decision boundary until it successfully separates the classes, provided the data is linearly separable.
The perceptron algorithm is implemented as follows:
Listing 5.1 Perceptron Algorithm
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import randint
from sklearn.datasets import load_iris
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
class perceptron:
def __init__(self, num_epochs, dim):
self.num_epochs = num_epochs
self.theta0 = 0
self.theta = np.zeros(dim)
def fit(self, X_train, y_train):
n = X_train.shape[0]
dim = X_train.shape[1]
k = 1
for epoch in range(self.num_epochs):
for i in range(n):
idx = randint.rvs(0, n-1, size=1)[0] #A
if (y_train[idx] * (np.dot(self.theta, X_train[idx,:]) + self.theta0) <= 0): #B
eta = pow(k+1, -1) #C
k += 1
self.theta = self.theta + eta * y_train[idx] * X_train[idx, :] #D
self.theta0 = self.theta0 + eta * y_train[idx] #D
#end if
print("epoch: ", epoch)
print("theta: ", self.theta)
print("theta0: ", self.theta0)
#end for
#end for
def predict(self, X_test):
n = X_test.shape[0]
dim = X_test.shape[1]
y_pred = np.zeros(n)
for idx in range(n):
y_pred[idx] = np.sign(np.dot(self.theta, X_test[idx,:]) + self.theta0)
#end for
return y_pred
if __name__ == "__main__":
iris = load_iris() #E
X = iris.data[:100,:]
y = 2*iris.target[:100] - 1 #F
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
#perceptron (binary) classifier
clf = perceptron(num_epochs=5, dim=X.shape[1])
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
cmt = confusion_matrix(y_test, y_pred)
acc = np.trace(cmt)/np.sum(np.sum(cmt))
print("percepton accuracy: ", acc)
#generate plots
plt.figure()
sns.heatmap(cmt, annot=True, fmt="d")
plt.title("Confusion Matrix"); plt.xlabel("predicted"); plt.ylabel("actual")
plt.savefig("./figures/perceptron_acc.png")
plt.show()
#A sample random point
#B hinge loss
#C update learning rate
#D update theta and theta0
#E load dataset
#F map to {+1,-1} labels
Perceptron Update Rule
The perceptron is a mistake-driven algorithm: it starts with θ=0 and successively adjusts the parameter θ for each training example until there are no more classification mistakes, assuming the data is linearly separable. The perceptron update rule can be summarized as follows:
Equation 5.3 Perceptron Update Rule
In this rule, the index k denotes the number of times the parameter updates, which corresponds to the number of mistakes. The update for θ0 is similar to the update for θ, but with x=1. If the training examples are linearly separable, the perceptron algorithm converges after a finite number of iterations. The order of input data points affects how the parameter θ is learned, so randomizing (shuffling) the training dataset can be beneficial. Additionally, introducing a learning rate can aid in the convergence of θ.
Classification Results
After running the perceptron algorithm on the Iris dataset, the classification accuracy results on the test dataset are visualized in the confusion matrix below:
Figure 5.5 Perceptron Binary Classifier Confusion Matrix (Iris Dataset)
The perceptron algorithm can be formulated as stochastic gradient descent that minimizes a hinge loss function. This loss function penalizes the magnitude of disagreement zi=yi(θ∙xi+θ0) between the label yi and the prediction h(xi;θ). Combining these expressions with the stochastic gradient descent update, where eta is the learning rate, we derive the perceptron algorithm.
Equation 5.6 Perceptron Update Rule
| Book Title | Overview of Perceptron | Training Methodology | Examples and Applications | Additional Features |
|----------------------------------------------------------------------------|----------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [Introducing Data Science: Big data, machine learning, and more, using Python tools](https://www.manning.com/books/introducing-data-science) | Describes perceptron as a simple yet foundational algorithm for binary classification. | Focuses on online learning, updating weights incrementally with each new observation. | Example of predicting customer purchases using online learning. [more](https://www.manning.com/books/introducing-data-science) | Highlights the efficiency of perceptron in environments with continuous data generation. |
| [Machine Learning Algorithms in Depth](https://www.manning.com/books/machine-learning-algorithms-in-depth) | Discusses perceptron as a linear classifier using a mistake-driven learning algorithm. | Implements perceptron with stochastic gradient descent and hinge loss minimization. | Example using the Iris dataset, with results visualized in a confusion matrix. [more](https://www.manning.com/books/machine-learning-algorithms-in-depth) | Explains the impact of data order and introduces learning rate for convergence. |
FAQ (Frequently asked questions)
What is a perceptron?
What type of classification does a perceptron perform?
What is shown in Listing 4.1?
How is a perceptron trained using online learning?
What is an example of training a perceptron?
How is a perceptron trained?
What is online learning in the context of perceptrons?
How is the perceptron graph represented in terms of dimensions?
What is a perceptron in neural networks?
How does a perceptron classify input data?
What does the decision boundary in a perceptron graph do?
What is the purpose of the fully_connected_layer function in a perceptron?
How does the Perceptron function work in the given code?
How do perceptrons use a hyperplane for classification?
Can perceptrons model logical functions?
What is required to model more complex functions like XOR with perceptrons?
How can a perceptron model the logical OR function?
What role does a perceptron play in neural networks?
What is a perceptron?
How does a perceptron learn?
How is the perceptron algorithm implemented in Python?
What dataset is used in the perceptron algorithm example?
How is the perceptron model evaluated in the example?
What is the purpose of the 'fit' method in the perceptron class?
How are the labels mapped in the perceptron example?