Lab 2
Lab 2
Lab 2
CLO 3, CLO 4
Date: 5-02-2025
class Perceptron(nn.Module):
def __init__(self, input_size):
super(Perceptron, self).__init__()
self.weights = nn.Parameter(torch.randn(input_size + 1) * 0.01)
prediction = perceptron(x_sample).squeeze()
error = y_sample - prediction
with torch.no_grad():
perceptron.weights += learning_rate * error *
torch.cat((torch.tensor([1.0]), x_sample.squeeze()))
plot_decision_boundary(perceptron, X, y)
Task 2: Implement XOR through Perceptrons
🛠 Instructions
Code:
import torch
import numpy as np
import matplotlib.pyplot as plt
prediction = self.predict(x_sample)
error = y_sample - prediction
perceptron = Perceptron(input_size=2)
perceptron.train(X, y)
plot_decision_boundary(perceptron, X, y)
Output:
Results from different epochs:
Task 3: Apply Perceptron to a Dataset of Your Choice
Instructions
Code:
Ok so I am taking a random dataset but its arranged in a circle, again it will not be a linear
data and we will see what happens, obviously a simple line wont be able to do it
import torch
import numpy as np
import matplotlib.pyplot as plt
prediction = self.predict(x_sample)
error = y_sample - prediction
def generate_circle_data(n_samples=100):
X = torch.rand((n_samples, 2)) * 2 - 1
y = torch.tensor([(1 if x[0]**2 + x[1]**2 < 0.5**2 else 0) for x in X],
dtype=torch.float32)
return X, y
X, y = generate_circle_data(100)
perceptron = Perceptron(input_size=2)
perceptron.train(X, y)
plot_decision_boundary(perceptron, X, y)
Changing epochs size:
We tried to train a single-layer perceptron to classify points as inside or outside a circle. The
perceptron learned something, but it failed to correctly separate the data. The perceptron failed
because it can only learn linear decision boundaries, but our dataset requires a nonlinear one
(a circle).
1. Does the perceptron successfully classify the AND function? Why or why not?
Yes. The AND function is linearly separable, so a perceptron can find a straight-line
decision boundary to classify it correctly.
Because XOR is not linearly separable. A single-layer perceptron can only learn straight-
line boundaries, but XOR requires a more complex separation.
Linearly separable problems like AND, OR, and simple classification tasks where a
single straight line can split the classes
4. What modifications would allow a model to solve XOR?
Use a Multi-Layer Perceptron. Adding a hidden layer allows the model to learn complex,
nonlinear decision boundaries.
Following is output after adding multi layers and finally solving it for XOR too.
Submission Guidelines
● Your code should be written in PyTorch.
● Ensure that you print weight updates at each step.
● Include a decision boundary plot for both AND and XOR.
● Submit a brief explanation answering the conceptual questions.
Hints
Important Note:
● Copied labs will be marked zero.
○ All submissions must reflect your own understanding and effort.
Deadline:
If you have any questions or need assistance, please reach out to the lab engineer.