1.
a) Implement the non-parametric Locally Weighted Regression algorithm in order to fit
data points. Select an appropriate data set for your experiment and draw graphs
import numpy as np
import matplotlib.pyplot as plt
def kernel(x, x_point, tau):
return np.exp(-np.sum((x - x_point)*2, axis=1) / (2 * tau*2))
def predict(x, y, x_query, tau):
m = len(x)
X_ = np.c_[np.ones(m), x]
x_query_ = np.r_[1, x_query]
W = np.diag(kernel(x, x_query, tau))
theta = np.linalg.pinv(X_.T @ W @ X_) @ X_.T @ W @ y
return x_query_ @ theta
# Sample data
x = np.linspace(1, 10, 100)
y = np.sin(x) + np.random.normal(0, 0.1, 100)
# Predictions
x_query = np.linspace(1, 10, 100)
y_pred = np.array([predict(x[:, None], y, np.array([pt]), tau=0.5) for pt in x_query])
plt.scatter(x, y, label='Original')
plt.plot(x_query, y_pred, color='red', label='LWR')
plt.legend()
plt.show()
b) Write a Python Program to Generate a Random Number.
import random
print("Random number:", random.randint(1, 100))
2. a) To generate a python code for SVM algorithm.
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
iris = datasets.load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = SVC()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
2)b) Design a Python code to Check Leap Year.
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
3.a) Implement KNN algorithm to classify the data set using python.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
print("Accuracy:", knn.score(X_test, y_test))
3.b) Write a Python Program to Find the Factorial of a Number.
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial:", fact)
4. a) Generate a python code for K-means algorithm.
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], color='red')
plt.title("K-Means Clustering")
plt.show()
4.b) Write a Python Program to Print the Fibonacci sequence.
n = int(input("Enter number of terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
5. a) To implement Maximum margin classifier algorithm using python.
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = datasets.make_classification(n_samples=100, n_features=2, n_classes=2, n_redundant=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
print("Score:", clf.score(X_test, y_test))
5.b) Develop a Python code to Check Armstrong Number.
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** len(str(num))
temp //= 10
print("Armstrong Number" if num == sum else "Not an Armstrong Number")
6. a) To generate a python code for Random Forests algorithm.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3)
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
print("Accuracy:", clf.score(X_test, y_test))
6.b) Write a Python Program to Make a Simple Calculator.
def calculator(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operation (+ - * /): ")
print("Result:", calculator(a, b, op))
7. a) Develop a program for Perceptron algorithm using python.
from sklearn.linear_model import Perceptron
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data[:100], iris.target[:100] # Binary classification
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
clf = Perceptron()
clf.fit(X_train, y_train)
print("Accuracy:", clf.score(X_test, y_test))
7.b) To design a Python Program to Display Calendar.
import calendar
year = int(input("Enter year: "))
month = int(input("Enter month (1-12): "))
print(calendar.month(year, month))
8. a) Generate a python code gradient descent algorithm.
import numpy as np
X = np.array([1, 2, 3, 4, 5])
y = np.array([1, 2, 1.3, 3.75, 2.25])
m, c = 0, 0
L = 0.01
epochs = 1000
n = len(X)
for _ in range(epochs):
y_pred = m * X + c
D_m = (-2/n) * sum(X * (y - y_pred))
D_c = (-2/n) * sum(y - y_pred)
m -= L * D_m
c -= L * D_c
print(f"Slope: {m}, Intercept: {c}")
8.b) To write a Python Program to Find Sum of Natural Numbers Using Recursion.
def recursive_sum(n):
if n == 1:
return 1
else:
return n + recursive_sum(n - 1)
n = int(input("Enter a number: "))
print("Sum:", recursive_sum(n))
9. a) Develop a program Simple linear regression algorithm using python.
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])
model = LinearRegression()
model.fit(X, y)
predictions = model.predict(X)
plt.scatter(X, y, color='blue', label='Original')
plt.plot(X, predictions, color='red', label='Fitted Line')
plt.xlabel("X")
plt.ylabel("y")
plt.title("Simple Linear Regression")
plt.legend()
plt.show()
print("Slope:", model.coef_[0])
print("Intercept:", model.intercept_)
9.b) Generate a Python Program to Add Two Matrices.
X = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]
print("Resultant Matrix:")
for row in result:
print(row)
10. a) Write a python code for Multiple linear regression algorithm.
from sklearn.linear_model import LinearRegression
import numpy as np
# Multiple features
X = np.array([[1, 2], [2, 3], [4, 5], [3, 6]])
y = np.array([3, 6, 9, 10])
model = LinearRegression()
model.fit(X, y)
print("Coefficients:", model.coef_)
print("Intercept:", model.intercept_)
10.b) Design a Python Program to Sort Words in Alphabetic Order.
words = input("Enter a sentence: ")
words_list = words.split()
words_list.sort()
print("Sorted Words:")
for word in words_list:
print(word)
Viva Questions
1. Locally Weighted Regression + Random Number Generator
Q1: What is Locally Weighted Regression?
A1: It's a non-parametric regression method that fits a model to a subset of the data around the
point of interest, giving higher weights to nearer points using a kernel function.
Q2: Why is it called 'non-parametric'?
A2: Because it doesn't assume a fixed form for the model; the regression function is determined by
the local data.
Q3: How does the bandwidth parameter affect Locally Weighted Regression?
A3: A smaller bandwidth gives more weight to nearby points, resulting in a model that closely
follows the training data, while a larger one smooths the model.
Q4: What Python function can you use to generate random numbers?
A4: You can use random.randint(a, b) or random.random() from the random module.
2. Support Vector Machine (SVM) + Leap Year
Q1: What is the core idea behind the SVM algorithm?
A1: SVM aims to find the hyperplane that best separates data into two classes with the maximum
margin.
Q2: What are support vectors?
A2: They are the data points closest to the hyperplane, which influence the position and orientation
of the hyperplane.
Q3: How do you check for a leap year in Python?
A3: A year is a leap year if it's divisible by 4 and not divisible by 100, or divisible by 400.
3. KNN Algorithm + Factorial
Q1: How does the KNN algorithm work?
A1: It classifies data points based on the majority label of the 'k' nearest neighbors using a distance
metric.
Q2: What distance metrics are commonly used in KNN?
A2: Euclidean, Manhattan, and Minkowski distances.
Q3: What is a factorial?
A3: The product of all positive integers up to a given number n. It’s used in combinatorics and
probability.
4. K-means Clustering + Fibonacci
Q1: What is the objective of the K-means algorithm?
A1: To partition the dataset into K clusters such that the intra-cluster variance is minimized.
Q2: What are the steps in K-means clustering?
A2: Initialize centroids, assign points to the nearest centroid, update centroids, and repeat until
convergence.
Q3: What is the Fibonacci sequence?
A3: A sequence where each number is the sum of the two preceding ones, starting from 0 and 1.
5. Maximum Margin Classifier + Armstrong Number
Q1: What is a Maximum Margin Classifier?
A1: It's essentially the core idea of a linear SVM that finds the line or hyperplane with the maximum
margin.
Q2: Define an Armstrong number.
A2: A number is Armstrong if the sum of its own digits each raised to the power of the number of
digits equals the number itself.
6. Random Forests + Calculator
Q1: How does a Random Forest work?
A1: It's an ensemble method that builds multiple decision trees and merges their outputs for more
accurate and stable predictions.
Q2: What is the advantage of using a Random Forest over a single decision tree?
A2: It reduces overfitting and improves generalization by averaging multiple trees.
Q3: What are basic operations in a Python calculator?
A3: Addition, subtraction, multiplication, and division using +, -, *, /.
7. Perceptron Algorithm + Calendar
Q1: What is a perceptron?
A1: A binary classifier that updates its weights based on prediction error using a linear combination
of input features.
Q2: What is the learning rule in a perceptron?
A2: w = w + α(y - ŷ)x, where α is the learning rate, y is actual, and ŷ is predicted output.
Q3: How do you display a calendar in Python?
A3: Use the calendar module, like calendar.month(2025, 5).
8. Gradient Descent + Recursion
Q1: What is gradient descent used for?
A1: To minimize a cost function by iteratively moving in the direction of the steepest descent as
defined by the negative gradient.
Q2: What are types of gradient descent?
A2: Batch, Stochastic, and Mini-batch Gradient Descent.
Q3: What is recursion?
A3: A function calling itself with a base condition to avoid infinite loops.
9. Simple Linear Regression + Matrix Addition
Q1: What is Simple Linear Regression?
A1: A technique to model the relationship between one independent variable and one dependent
variable using a straight line.
Q2: How is the line equation expressed in simple linear regression?
A2: y = mx + c, where m is the slope and c is the intercept.
Q3: How do you add two matrices in Python?
A3: Use nested loops or NumPy arrays: result = A + B.
10. Multiple Linear Regression + Word Sorting
Q1: What is Multiple Linear Regression?
A1: It models the relationship between two or more independent variables and a dependent
variable.
Q2: What is multicollinearity in regression?
A2: When independent variables are highly correlated, making coefficient estimation unstable.
Q3: How do you sort words alphabetically in Python?
A3: Use the split() and sort() methods: words.sort().