Perceptron Logic Gates¶

Import Libraries¶

In [1]:
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
import numpy as np
from itertools import product

The 4 Possible Input Pairs On A Logic Gate¶

In [2]:
data = [[0, 0], [0, 1], [1, 0], [1, 1]]

AND GATE¶

The 4 Outcomes¶

In [3]:
labels = [0,0,0,1]

Build The Perceptron¶

In [4]:
classifier = Perceptron(random_state = 20)
classifier.fit(data,labels)
Out[4]:
Perceptron(random_state=20)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Perceptron(random_state=20)

Visualising The Perceptron¶

In [5]:
x_values = np.linspace(0, 1, 100)
y_values = np.linspace(0, 1, 100)
point_grid = list(product(x_values, y_values))
In [6]:
distances = classifier.decision_function(point_grid)
abs_distances = [abs(pt) for pt in distances]

distances_matrix = np.reshape(abs_distances, (100,100))
In [7]:
heatmap = plt.pcolormesh(x_values, y_values,distances_matrix)

plt.colorbar(heatmap)
plt.scatter([point[0] for point in data],[point[1] for point in data], c=labels)

plt.show()

Testing The Perceptron¶

In [8]:
tests = classifier.predict([[0.1,0.1],[0.5,0.5],[0.9,0.9],[0.99,0.1]])
In [9]:
print(tests)
[0 0 1 0]

OR GATE¶

Repeated Code (with Outputs Now Changed To Represent An Or Gate)¶

In [10]:
labels = [0,1,1,1]
In [11]:
classifier = Perceptron(random_state = 20)
classifier.fit(data,labels)
Out[11]:
Perceptron(random_state=20)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Perceptron(random_state=20)
In [12]:
x_values = np.linspace(0, 1, 100)
y_values = np.linspace(0, 1, 100)
point_grid = list(product(x_values, y_values))
In [13]:
distances = classifier.decision_function(point_grid)
abs_distances = [abs(pt) for pt in distances]

distances_matrix = np.reshape(abs_distances, (100,100))
In [14]:
heatmap = plt.pcolormesh(x_values, y_values,distances_matrix)

plt.colorbar(heatmap)
plt.scatter([point[0] for point in data],[point[1] for point in data], c=labels)

plt.show()
In [15]:
tests = classifier.predict([[0.1,0.1],[0.5,0.5],[0.9,0.9],[0.99,0.1]])
In [16]:
print(tests)
[0 1 1 1]