Perceptron
Verfasst: Samstag 16. Juni 2012, 11:57
Hi. Ich habe nen Code geschrieben, der Perceptronen trainiert und Vorhersagen machen soll, Nur leider kommt da immer totaler Schwachsinn raus und ich kann mir nicht erklären, wo der Fehler liegt. Hier der Code:
Das Problem sollte auf jeden Fall lernbar sein, da das Beispiel des Und-Operators linear separabel ist...
Hat jemand eine Idee?
Grüße,
Thomy800
Code: Alles auswählen
import sys
import random
import math
import scipy.io as sc
from numpy import *
import matplotlib.pyplot as plt
#x: beispiel
#w: gewichtsvektor
#r: vorhersage {1,-1}
def predict(x, w):
tw = w.transpose()
r = dot(tw,x)
return r
def predictSign(x, w):
r=predict(x,w)
if r<0: r=-1
else: r=1
return r
#x: array mit den einzelnen zu lernenden Beispielen (Vektoren)
#y: array mit den einzelnen Kategorien {1,-1}
#its: anzahl der Iterationen
#rate: Lernrate
#w: gewichtsvektor
def trainperceptron(x, y, its, rate):
#D: Dimension der Vektoren
#N: Anzahl der Beispiele
#w: Gewichtsvektor
(N,D) = x.shape
w=zeros((1,D))[0]
for it in range(0,its):
d=random.random()
i=int(math.ceil(d*(N)))-1
r = predictSign(x[i],w)
if r!=y[i]:
w = w + rate/(it+1) * dot(x[i],y[i])
print w
return w
x = array([[0.5,0.5],[0.5,-0.5],[-0.5,0.5],[-0.5,-0.5]])
y = array([1,-1,-1,-1])
w = trainperceptron(x, y, 5000, 1.0)
(N,D)=x.shape
for i in range(0,N):
r = predictSign(x[i],w)
print str(x[i]) + '=> '+str(r)+' (' +str(y[i])+')'
print w
Hat jemand eine Idee?
Grüße,
Thomy800