Q1. Design a simple class
DataPoint with attributes x and y. Create an instance with x=3, y=5. Add a method to compute Euclidean distance from origin.class DataPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return (self.x**2 + self.y**2) ** 0.5
point = DataPoint(3,5)
print(point.distance_from_origin()) # 5.83This models a data point as an object.Q2. Create a
Model class with attributes weights (list) and bias. Include a method predict that computes linear combination of input features. Initialize with random weights.class Model:
def __init__(self, n_features):
import random
self.weights = [random.random() for _ in range(n_features)]
self.bias = 0
def predict(self, x):
return sum(w * xi for w, xi in zip(self.weights, x)) + self.biasThis is a linear model.Q3. Add a method to the
Model class to update weights using gradient descent (simple update: subtract learning_rate * gradient). Assume you have a gradient list.def update(self, gradients, lr=0.01):
for i in range(len(self.weights)):
self.weights[i] -= lr * gradients[i]
self.bias -= lr * gradients[-1] # assuming bias gradient is lastThis encapsulates parameter update logic, core to training neural networks.Q4. Create a class
Dataset that takes a list of samples (each a tuple of features and label) and provides a method to get batch of size batch_size. Use yield to make it iterable.class Dataset:
def __init__(self, data):
self.data = data
def batch(self, batch_size):
for i in range(0, len(self.data), batch_size):
yield self.data[i : i+batch_size]This allows efficient data loading during training.Q5. Define a class
Polynomial that takes coefficients as list (e.g., [a,b,c] for ax²+bx+c). Implement __call__ method to evaluate polynomial at a given x. Test with coeffs [1, -2, 1] at x=2.class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __call__(self, x):
return sum(c * (x ** i) for i, c in enumerate(self.coeffs))
p = Polynomial([1, -2, 1])
print(p(2)) # 1 + (-2*2) + (1*4) = 1__call__ makes instance callable like a function.