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) |
This comment has been minimized.
This comment has been minimized.
@hoanW, As written, Here's an example usage and writeup: https://gist.github.com/Thomascountz/baeecd8de6eb73f179d1342fd4519748 Sorry for the confusion and thank you for your feedback! Please let me know if this doesn't solve the problem. |
This comment has been minimized.
This comment has been minimized.
thank you for clearing that up. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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)