Untitled
unknown
python
2 years ago
1.5 kB
10
Indexable
import numpy as np
class Perceptron:
def __init__(self, input_size, learning_rate=0.1):
self.weights = np.zeros(input_size + 1) # Add one for the bias
self.learning_rate = learning_rate
def predict(self, inputs):
summation = np.dot(inputs, self.weights[1:]) + self.weights[0]
return 1 if summation > 0 else 0
def train(self, training_inputs, labels):
weight_changed = True
while weight_changed:
weight_changed = False
for inputs, label in zip(training_inputs, labels):
prediction = self.predict(inputs)
error = label - prediction
if error != 0:
weight_changed = True
self.weights[1:] += self.learning_rate * error * inputs
self.weights[0] += self.learning_rate * error
# Training data for logical AND function
training_inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
labels = np.array([0, 0, 0, 1])
# Create and train perceptron
perceptron = Perceptron(input_size=2)
perceptron.train(training_inputs, labels)
print("Testing the trained perceptron")
for inputs in training_inputs:
prediction = perceptron.predict(inputs)
print(f"inputs: {inputs}, Predicted output: {prediction}")
#Testing the trained perceptron
#inputs: [0 0], Predicted output: 0
#inputs: [0 1], Predicted output: 0
#inputs: [1 0], Predicted output: 0
#inputs: [1 1], Predicted output: 1Editor is loading...
Leave a Comment