Code 111

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy