Classifieur Perceptron¶

In [1]:
import numpy as np
import pandas as pa
import matplotlib.pyplot as plt
In [2]:
X = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
y = np.array([[-1, 1, 1, 1]])

#X = np.array([[0, 0, 1], [1, 1, 1]])
#y = np.array([[-1, 1]])

plt.grid()
plt.scatter(X[:, 0], X[:, 1], c=y[0])
Out[2]:
<matplotlib.collections.PathCollection at 0xffff3f27dfd0>
No description has been provided for this image
In [3]:
def perceptron(X, y):
    n = len(X)
    d = len(X[0]) - 1
    w = np.zeros(d+1)
    k = 0
    error = True
    cpt = 0
    while error:
        error = False
        for i in range(n):
            cpt += 1
            x = X[i, :]
            if y[0][i] * np.vdot(w, x) <= 0:
                w = w + y[0][i] * x
                k += 1
                error = True
    print('k: ', k)
    print('cpt: ', cpt)
    return w
        
X_tmp, y_tmp = X, y        
perceptron(X_tmp, y_tmp)
k:  9
cpt:  24
Out[3]:
array([ 2.,  2., -1.])
In [4]:
def line(w, x):
    return - (1. / w[1]) * (w[0] * x + w[2])
In [5]:
plt.grid()
plt.scatter(X[:, 0], X[:, 1], c=y[0])
x = np.linspace(0,1,10)
w = perceptron(X_tmp, y_tmp)
y = line(w, x)
plt.plot(x, y, color='red')
k:  9
cpt:  24
Out[5]:
[<matplotlib.lines.Line2D at 0xffff3f27ca10>]
No description has been provided for this image
In [ ]: