%matplotlib inline
from numpy import *
X = random.randn(100,2)
# Avec 'list comprehension':
y = array([1 if dot(ex,[3,2])>0 else -1 for ex in X])
# ou la meme chose avec une boucle for:
# y = []
# for ex in X:
# if dot(ex,[3,2]) > 0:
# y.append(1)
# else:
# y.append(-1)
X[:10] , y[:10]
def affiche(X,y):
Xpos = X[y > 0]
Xneg = X[y < 0]
import matplotlib.pyplot as plt
plt.scatter(Xpos[:,0],Xpos[:,1],c='blue')
plt.scatter(Xneg[:,0],Xneg[:,1],c='red')
affiche(X,y)
def phi(ex):
return ex
def perceptron(T):
nexs = len(X)
eta = 0.2
natts = len(phi(X[0]))
w = zeros( natts )
for k in range(T):
i = random.randint(0,nexs)
ex= phi( X[i] )
if y[i]*dot(w,ex) <= 0:
w = w + eta*y[i]*ex
print "erreur de classif"
else:
print "ok"
return w
perceptron(30)
def phi(ex):
return array( [1.0] + list(ex) + [i*j for i in ex for j in ex] )
phi([2,3])
# je definis un cercle de rayon 1. Tous les exemples dans le cercle sont positifs.
y = array([1 if (ex[0]**2+ex[1]**2) < 1 else -1 for ex in X])
affiche(X,y)
w = perceptron(40)
y_pred = array([-1 if dot(w,phi(ex)) <= 0 else 1 for ex in X])
affiche(X,y_pred)