Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Perceptron in Python v.1
"""
MIT License
Copyright (c) 2018 Thomas Countz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as np
class Perceptron(object):
def __init__(self, no_of_inputs, threshold=100, learning_rate=0.01):
self.threshold = threshold
self.learning_rate = learning_rate
self.weights = np.zeros(no_of_inputs + 1)
def predict(self, inputs):
summation = np.dot(inputs, self.weights[1:]) + self.weights[0]
if summation > 0:
activation = 1
else:
activation = 0
return activation
def train(self, training_inputs, labels):
for _ in range(self.threshold):
for inputs, label in zip(training_inputs, labels):
prediction = self.predict(inputs)
self.weights[1:] += self.learning_rate * (label - prediction) * inputs
self.weights[0] += self.learning_rate * (label - prediction)
@hoanW

This comment has been minimized.

Copy link

@hoanW hoanW commented May 1, 2020

line 46: "inputs" is a tuple which can not be multiplied by a number. My suggestion is to convert it into an array.
for example : self.weights[1:] += self.learning_rate * (label - prediction) * np.array(inputs)

@Thomascountz

This comment has been minimized.

Copy link
Owner Author

@Thomascountz Thomascountz commented May 1, 2020

@hoanW, As written,training_inputs should be a list (or other iterable) of numpy arrays when passed into the train() function.

Here's an example usage and writeup:

https://gist.github.com/Thomascountz/baeecd8de6eb73f179d1342fd4519748
https://www.thomascountz.com/2018/04/05/19-line-line-by-line-python-perceptron

Sorry for the confusion and thank you for your feedback! Please let me know if this doesn't solve the problem.

@hoanW

This comment has been minimized.

Copy link

@hoanW hoanW commented May 1, 2020

thank you for clearing that up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.