98 lines
3.4 KiB
Python
98 lines
3.4 KiB
Python
import numpy as np
|
||
|
||
class Perceptron():
|
||
|
||
def __init__(self):
|
||
# Initialize weights randomly between -1 and 1 for 3 inputs
|
||
np.random.seed(1) # For reproducible results
|
||
self.synaptic_weights = 2 * np.random.random((3, 1)) - 1
|
||
|
||
def sigmoid(self, x):
|
||
"""Sigmoid activation function"""
|
||
return 1 / (1 + np.exp(-x))
|
||
|
||
def sigmoid_derivative(self, x):
|
||
"""Derivative of sigmoid function"""
|
||
return x * (1 - x)
|
||
|
||
def think(self, inputs):
|
||
"""One thought step of the perceptron for given inputs"""
|
||
# Calculate weighted sum and apply sigmoid function
|
||
return self.sigmoid(np.dot(inputs, self.synaptic_weights))
|
||
|
||
def train(self, inputs, targets, iterations):
|
||
"""Training loop with backpropagation and weight adjustments"""
|
||
for iteration in range(iterations):
|
||
# Forward propagation
|
||
output = self.think(inputs)
|
||
|
||
# Calculate error
|
||
error = targets - output
|
||
|
||
# Backpropagation: calculate weight adjustments
|
||
# ΔW = (Error * sigmoid_derivative(output)) × inputs^T
|
||
adjustments = np.dot(inputs.T, error * self.sigmoid_derivative(output))
|
||
|
||
# Update weights
|
||
self.synaptic_weights += adjustments
|
||
|
||
if __name__ == "__main__":
|
||
# Create perceptron instance
|
||
p = Perceptron()
|
||
|
||
# Training data from the task
|
||
training_inputs = np.array([[0, 0, 1],
|
||
[1, 1, 1],
|
||
[1, 0, 0],
|
||
[0, 1, 1]])
|
||
|
||
training_targets = np.array([[0, 1, 1, 0]]).T
|
||
|
||
print("Random synaptic weights before training:")
|
||
print(p.synaptic_weights.T)
|
||
|
||
# Train the perceptron
|
||
print("\nTraining the perceptron...")
|
||
p.train(training_inputs, training_targets, 10000)
|
||
|
||
print("\nSynaptic weights after training:")
|
||
print(p.synaptic_weights.T)
|
||
|
||
# Test the perceptron with training data
|
||
print("\nTesting with training data:")
|
||
for i, inp in enumerate(training_inputs):
|
||
output = p.think(inp.reshape(1, -1))
|
||
print(f"Input: {inp} → Output: {output[0][0]:.4f} (Target: {training_targets[i][0]})")
|
||
|
||
# Test with new data [1, 1, 0]
|
||
print("\nTesting with new input [1, 1, 0]:")
|
||
new_input = np.array([1, 1, 0])
|
||
prediction = p.think(new_input.reshape(1, -1))
|
||
print(f"Input: {new_input} → Prediction: {prediction[0][0]:.4f}")
|
||
|
||
# Interactive part - ask user for input
|
||
print("\n" + "="*50)
|
||
print("Interactive mode:")
|
||
while True:
|
||
try:
|
||
print("\nEnter values for I1, I2, I3 (or 'quit' to exit):")
|
||
user_input = input("I1, I2, I3: ")
|
||
|
||
if user_input.lower() == 'quit':
|
||
break
|
||
|
||
# Parse user input
|
||
values = [float(x.strip()) for x in user_input.split(',')]
|
||
if len(values) != 3:
|
||
print("Please enter exactly 3 values separated by commas.")
|
||
continue
|
||
|
||
user_array = np.array(values)
|
||
result = p.think(user_array.reshape(1, -1))
|
||
print(f"Perceptron's belief for {user_array}: {result[0][0]:.4f}")
|
||
|
||
except (ValueError, IndexError):
|
||
print("Invalid input. Please enter 3 numbers separated by commas.")
|
||
except KeyboardInterrupt:
|
||
print("\nExiting...")
|
||
break |