You are on page 1of 4

import numpy as np

# Define the input data and target labels

# Each input is a binary vector of length 4

# Each label is a binary vector of length 2

# The first element of the label is 1 if the number is odd, 0 otherwise

# The second element of the label is 1 if the number is even, 0 otherwise

input_data = [

[0, 0, 0, 0], # 0

[0, 0, 0, 1], # 1

[0, 0, 1, 0], # 2

[0, 0, 1, 1], # 3

[0, 1, 0, 0], # 4

[0, 1, 0, 1], # 5

[0, 1, 1, 0], # 6

[0, 1, 1, 1], # 7

[1, 0, 0, 0], # 8

[1, 0, 0, 1] # 9

output_labels = [

[0, 1], # even

[1, 0], # odd

[0, 1], # even

[1, 0], # odd

[0, 1], # even

[1, 0], # odd

[0, 1], # even


[1, 0], # odd

[0, 1], # even

[1, 0] # odd

# Initialize the weights and bias randomly

# The weights are a matrix of size 4 x 2

# The bias is a vector of size 2

weights = np.random.uniform(size=(4, 2))

bias = np.random.uniform(size=(2,))

# Define the activation function (sigmoid)

def sigmoid(x):

return 1 / (1 + np.exp(-x))

# Define the learning rate and the number of epochs

learning_rate = 0.1

epochs = 1000

# Train the Perceptron using the delta rule

for epoch in range(epochs):

for i in range(len(input_data)):

# Forward pass

z = np.dot(input_data[i], weights) + bias

output = sigmoid(z)

# Compute the error


error = output - output_labels[i]

# Update the weights and bias

weights -= learning_rate * np.outer(input_data[i], error)

bias -= learning_rate * error

# Ask the user for a number between 0 and 9

user_input = input("Enter a number between 0 and 9: ")

# Convert the user input to an integer

user_input = int(user_input)

# Check if the user input is valid

if user_input < 0 or user_input > 9:

print("Invalid input. Please enter a number between 0 and 9.")

else:

# Convert the user input to a binary vector of length 4

test_input = [int(x) for x in bin(user_input)[2:].zfill(4)]

# Test the Perceptron on the user input

test_output = sigmoid(np.dot(test_input, weights) + bias)

# Print the prediction

if test_output[0] > test_output[1]:

print("Predicted: Odd")

else:

print("Predicted: Even")

You might also like