import numpy as np
def step_function(x):
return 1 if x >= 0 else 0
class Perceptron:
def __init__(self, input_size, learning_rate=0.1, epochs=100):
self.weights = np.zeros(input_size + 1)
self.learning_rate = learning_rate
self.epochs = epochs
def predict(self, x):
x_with_bias = np.insert(x, 0, 1)
linear_output = np.dot(self.weights, x_with_bias)
return step_function(linear_output)
def train(self, X, y):
for _ in range(self.epochs):
for i in range(len(X)):
x_with_bias = np.insert(X[i], 0, 1)
y_pred = step_function(np.dot(self.weights, x_with_bias))
error = y[i] - y_pred
self.weights += self.learning_rate * error * x_with_bias
def train_gate(gate_name, X, y):
print(f"Training {gate_name} gate...")
perceptron = Perceptron(input_size=2)
perceptron.train(X, y)
print(f"Weights for {gate_name} gate: {perceptron.weights}")
for x, target in zip(X, y):
pred = perceptron.predict(x)
print(f"Input: {x}, Predicted: {pred}, Target: {target}")
print()
return perceptron
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_and = np.array([0, 0, 0, 1])
y_or = np.array([0, 1, 1, 1])
y_xor = np.array([0, 1, 1, 0])