0% found this document useful (0 votes)
30 views2 pages

Code 111

Uploaded by

ryanedward947
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views2 pages

Code 111

Uploaded by

ryanedward947
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

'%pylab inline'

#IBIKUNLE Lateef Kayode


#139047037

import matplotlib.pyplot as plt


import random as rnd
import numpy as np

def generateLine():
points = np.random.uniform(-1, 1, (2, 2))
(x1,y1),(x2,y2) = points
k = (y2 - y1) / (x2 - x1)
m = y1 - k * x1
return k,m

def generateData(line, N=10):


k,m = line
x = np.ones((N, 3))
x[:,1:] = np.random.uniform(-1, 1, (N, 2))
y = x[:,2] - (x[:,1] * k + m)
return x,np.sign(y)

def showData(x,y, line, label):


pos = y > 0
neg = y < 0
plt.plot(x[:,1][pos], x[:,2][pos], 'gD')
plt.plot(x[:,1][neg], x[:,2][neg], 'rs')
k,m = line
v = np.array([-1.0, 1.0])
plt.plot(v, v * k + m, label=label)

def perceptron(x, y):


w = np.zeros(x.shape[1], dtype=float)
t = 0
while True:
missed = []
for i, r in enumerate(x):
result = np.sign(np.dot(r, w))
u = r * (y[i] - result)
if result != y[i]: missed.append(u)
if len(missed) == 0: return w,t
w = w + rnd.choice(missed)
t += 1

def disagreement(x,y,w):
result = np.dot(x, w)
d = np.ones(y.size)[y != np.sign(result)]
return np.sum(d) / y.size

def runProblem(N, n=20):


c = 0.0
d = 0.0
for i in xrange(n):
line = generateLine()
x,y = generateData(line, N)
w,t = perceptron(x,y)
testX, testY = generateData(line, n)
d += disagreement(testX, testY, w)
c += t
return {'iterations': c / n, 'disagreement': d / n}

line = generateLine()
x,y = generateData(line, 20)
w,_ = perceptron(x,y)

plt.title("Perceptron Learning Algorithm Output ")


#showData(x,y, line, "Testing")
showData(x, y, (- w[1] / w[2], - w[0] / w[2]), "P-L-A")
plt.legend(loc='best')
plt.show()

You might also like