The Perceptron Algorithm: pseudo code

Finally! There we go:

def error(weights, bias, features, label):
pred = prediction(weights, bias, features)
if pred == label:
return 0
else:
return np.abs(score(weights, bias, features))
 def total_error(weights, bias, X, y):
total_error = 0
for i in range(len(X)):
total_error += error(weights, bias, X.loc[i], y[i])
return total_error
def perceptron_trick(weights, bias, features, label, learning_rate = 0.01):
pred = prediction(weights, bias, features)
if pred==label:
return weights, bias
else:
if label==1 and pred==0:
for i in range(len(weights)):
weights[i] += features[i]*learning_rate
bias += learning_rate
elif label==0 and pred==1:
for i in range( len(weights)):
weights[i] -= features[i]*learning_rate
bias -= learning_rate
return weights, bias
def perceptron_trick_clever(weights, bias, features, label, learning_rate = 0.01):     
pred = prediction(weights, bias, features)
for i in range(len(weights)):
weights[i] += (label-pred)*features[i]*learning_rate
bias += (label-pred)*learning_rate
return weights, bias
def perceptron_algorithm(X, y, learning_rate = 0.01, epochs = 200):     
weights = [1.0 for i in range(len(X.loc[0]))]
bias = 0.0
errors = []
for i in range(epochs):
errors.append(total_error(weights, bias, X, y))
j = random.randint(0, len(features)-1)
weights, bias = perceptron_trick(weights, bias, X.loc[j], y[j]) return weights, bias, errors
BEAUTY

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store