ML Lab
ML Lab
LAB MANUAL
DAEC HoD-CSE
INSTITUTION VISION & MISSION
VISION
MISSION
The Institution aims at providing a vibrant, intellectually and emotionally rich teaching learning
environment with state of art infrastructure and recognizing and nurturing the potential of each
individual to evolve into one’s own self and contribute to the welfare of all.
VISION
MISSION
M1: To provide state-of-the-art ICT infrastructure and innovative, research oriented teaching learning
environment and motivation for self-learning & problem-solving abilities by recruiting
committed faculty.
M3: To Imbibe awareness on societal responsibility and leadership qualities with professional
competency and ethics.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
PEO1: Graduates of Computer Science and Engineering will be able to utilize
mathematics, science, engineering fundamentals, theoretical as well as laboratory
based experiences to identify, formulate & solve engineering problems and
succeed in entry-level engineering positions in ITES or in advanced engineering.
PEO2: Graduates of Computer Science and Engineering will be prepared to communicate
and work effectively on individual & team based engineering projects while
practicing the ethics of their profession consistent with a sense of social
responsibility.
PEO3: Graduates of Computer Science and Engineering will be equipped to recognize the
importance of, and have the skills for, continuous learning to become experts in
their domain and enhance their professional attributes.
Book 1: Chapter 2
2 Develop a program to Compute the correlation matrix to understand the relationships between
pairs of features. Visualize the correlation matrix using a heatmap to know which variables have
strong positive/negative correlations. Create a pair plot to visualize pairwise relationships
between features. Use California Housing dataset.
Book 1: Chapter 2
3 Develop a program to implement Principal Component Analysis (PCA) for reducing the
dimensionality of the Iris dataset from 4 features to 2.
Book 1: Chapter 2
4 For a given set of training data examples stored in a .CSV file, implement and demonstrate the Find-
S algorithm to output a description of the set of all hypotheses consistent with the training
examples.
Book 1: Chapter 3
5 Develop a program to implement k-Nearest Neighbour algorithm to classify the randomly
generated 100 values of x in the range of [0,1]. Perform the following based on dataset generated.
Label the first 50 points {x1,……,x50} as follows: if (xi ≤ 0.5), then xi Class1, else xi
Class1 Classify the remaining points, x51,……,x100 using KNN. Perform this for
k=1,2,3,4,5,20,30
Book 2: Chapter – 2
6 Implement the non-parametric Locally Weighted Regression algorithm in order to fit data points.
Select appropriate data set for your experiment and draw graphs
Book 1: Chapter – 4
7 Develop a program to demonstrate the working of Linear Regression and Polynomial Regression.
Use Boston Housing Dataset for Linear Regression and Auto MPG Dataset (for vehicle fuel
efficiency prediction) for Polynomial Regression.
Book 1: Chapter – 5
8 Develop a program to demonstrate the working of the decision tree algorithm. Use Breast Cancer
Data set for building the decision tree and apply this knowledge to classify a new sample.
Book 2: Chapter – 3
9 Develop a program to implement the Naive Bayesian classifier considering Olivetti Face Data
set for training. Compute the accuracy of the classifier, considering a few test data sets.
Book 2: Chapter – 4
10 Develop a program to implement k-means clustering using Wisconsin Breast Cancer data set and
visualize the clustering result.
Book 2: Chapter – 4
Course outcomes (Course Skill Set):
At the end of the course the student will be able to:
● Illustrate the principles of multivariate data and apply dimensionality reduction techniques.
● Demonstrate similarity-based learning methods and perform regression analysis.
● Develop decision trees for classification and regression problems, and Bayesian models for
probabilistic learning.
• Implement the clustering algorithms to share computing resources.
EXPERIMENT 1
1. Develop a program to create histograms for all numerical features and analyze the
distribution of each feature. Generate box plots for all numerical features and
identify any outliers. Use California Housing dataset.
import pandas as pd
import [Link] as plt
OUTPUT
Outliers Detection:
MedHouseVal: 1071 outliers
Total_rooms: 1287 outliers
Total_bedrooms: 1271 outliers
Population: 1196 outliers
Households: 1220 outliers
Median_income: 681 outliers
ADDITIONAL PROGRAM-1
# -------------------------------
# Step 1: Load dataset (offline)
# -------------------------------
iris = load_iris(as_frame=True)
df = [Link]
# -------------------------------
# Step 2: KDE Plot
# -------------------------------
[Link](figsize=(6, 4))
[Link](df['sepal length (cm)'], shade=True)
[Link]("KDE Plot of Sepal Length")
[Link]("Sepal Length (cm)")
[Link]("Density")
[Link](True)
[Link]()
# -------------------------------
# Step 3: Log Transformed Histogram
# -------------------------------
[Link](figsize=(6, 4))
[Link](np.log1p(df['sepal length (cm)']), bins=30)
[Link]("Log Transformed Histogram of Sepal Length")
[Link]("Log(Sepal Length)")
[Link]("Frequency")
[Link](True)
OUTPUT
EXPERIMENT 2
import pandas as pd
import [Link] as plt
from [Link] import scatter_matrix
# Correlation matrix
corr = df_num.corr()
print(corr)
# Heatmap
[Link](corr, cmap='coolwarm', interpolation='nearest')
[Link](range(len(corr)), [Link], rotation=45, ha='right')
[Link](range(len(corr)), [Link])
[Link]()
[Link]()
# Pair plot
scatter_matrix(df_num, figsize=(12, 12), diagonal='hist')
[Link]()
OUTPUT
median_house_value
longitude -0.045967
latitude -0.144160
housing_median_age 0.105623
total_rooms 0.134153
total_bedrooms 0.049686
population -0.024650
households 0.065843
median_income 0.688075
median_house_value 1.000000
ADDITIONAL PROGRAM 2
Write a Python program to compute the correlation matrix of a dataset and identify highly
correlated feature pairs.
import pandas as pd
from [Link] import load_breast_cancer
# -------------------------------
# Step 1: Load dataset (offline)
# -------------------------------
data = load_breast_cancer(as_frame=True)
df = [Link]
# -------------------------------
# Step 2: Compute correlation matrix
# -------------------------------
corr = [Link]()
# -------------------------------
# Step 3: Find highly correlated pairs
# -------------------------------
print("\nHighly correlated pairs (|correlation| > 0.8):")
for i in range(len([Link])):
for j in range(i):
if abs([Link][i, j]) > 0.8:
print([Link][i], " & ", [Link][j], " : ", [Link][i, j])
OUTPUT
EXPERIMENT 3
import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
from [Link] import PCA
from [Link] import StandardScaler
# Standardize features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Apply PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
# Plot
[Link](figsize=(8, 6))
[Link](x='PC1', y='PC2', hue='Species', palette='Set1', data=df_pca)
[Link]('PCA on Iris Dataset (4D → 2D)')
[Link]('Principal Component 1')
[Link]('Principal Component 2')
[Link](title='Species')
[Link](True)
[Link]()
# Explained variance
print("Explained Variance Ratio:", pca.explained_variance_ratio_)
print("Total Variance Explained:", pca.explained_variance_ratio_.sum())
OUTPUT
ADDITIONAL PROGRAM 3
Write a Python program to apply PCA on the Iris dataset after standardizing the features.
iris = load_iris()
X = [Link]
X_scaled = StandardScaler().fit_transform(X)
pca = PCA(0.95)
X_pca = pca.fit_transform(X_scaled)
[Link](pca.explained_variance_ratio_.cumsum())
[Link]("Components")
[Link]("Cumulative Variance")
[Link]()
OUTPUT
EXPERIMENT 4
4. For a given set of training data examples stored in a .CSV file, implement and
demonstrate the Find-S algorithm to output a description of the set of all
hypotheses consistent with the training examples.
import numpy as np
import pandas as pd
data = pd.read_csv('[Link]')
# Update hypothesis
for i, h in enumerate(concepts):
if target[i] == "Yes":
for x in range(len(specific_h)):
if h[x] != specific_h[x]:
specific_h[x] = "?"
return specific_h
OUTPUT
['Sunny' 'Warm' 'High' 'Strong' '?' '?']
ADDITIONAL PROGRAM 4
Implement the Find-S algorithm in Python to find the most specific hypothesis consistent with
the given training data.
import pandas as pd
import numpy as np
# -------------------------------
# Step 1: Create dataset (offline)
# -------------------------------
data = {
"Sky": ["Sunny", "Sunny", "Rainy", "Sunny"],
"AirTemp": ["Warm", "Warm", "Cold", "Warm"],
"Humidity": ["Normal", "High", "High", "High"],
"Wind": ["Strong", "Strong", "Strong", "Weak"],
"Water": ["Warm", "Warm", "Warm", "Warm"],
"Forecast": ["Same", "Same", "Change", "Same"],
"EnjoySport": ["Yes", "Yes", "No", "Yes"]
}
df = [Link](data)
print("Training Data:\n", df)
# -------------------------------
# Step 2: Separate concepts & target
# -------------------------------
concepts = [Link][:, :-1].values
target = [Link][:, -1].values
# -------------------------------
# Step 3: Initialize hypothesis
# -------------------------------
hypothesis = concepts[0].copy()
# -------------------------------
# Step 4: Find-S Algorithm
Dept. of CSE, JIT-Bangalore Page 17
Machine Learning Laboratory- BCSL606
# -------------------------------
for i, val in enumerate(target):
if val == "Yes":
for j in range(len(hypothesis)):
if hypothesis[j] != concepts[i][j]:
hypothesis[j] = "?"
# -------------------------------
# Step 5: Output
# -------------------------------
print("\nFinal hypothesis:")
print(hypothesis)
OUTPUT
EXPERIMENT 5
# Data
[Link](0)
x=[Link](100)
train,test=x[:50],x[50:]
lab=["Class1" if i<=0.5 else "Class2" for i in train]
# KNN
def knn(p,k):
i=[Link](abs(train-p))[:k]
return Counter([lab[j] for j in i]).most_common(1)[0][0]
# Run
for k in [1,2,3,4,5,20,30]:
print(f"\nk={k}")
pred=[knn(p,k) for p in test]
# Classification output
for i,(v,c) in enumerate(zip(test,pred),51):
print(f"x{i}={v:.2f} -> {c}")
# Visualization
[Link]()
[Link](train,[0]*50,c=['blue' if l=="Class1" else 'red' for l in lab])
[Link](test,[0.05]*50,marker='x',
c=['blue' if l=="Class1" else 'red' for l in pred])
[Link](f"k={k}")
[Link]([]); [Link](0,1)
[Link]()
OUTPUT
k=1
x51=0.57 -> Class2
x52=0.44 -> Class1
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
x57=0.65 -> Class2
x58=0.25 -> Class1
x59=0.47 -> Class1
x60=0.24 -> Class1
x61=0.16 -> Class1
x62=0.11 -> Class1
x63=0.66 -> Class2
x64=0.14 -> Class1
x65=0.20 -> Class1
x66=0.37 -> Class1
x67=0.82 -> Class2
x68=0.10 -> Class1
x69=0.84 -> Class2
x70=0.10 -> Class1
x71=0.98 -> Class2
x72=0.47 -> Class1
x73=0.98 -> Class2
x74=0.60 -> Class2
x75=0.74 -> Class2
x76=0.04 -> Class1
x77=0.28 -> Class1
x78=0.12 -> Class1
x79=0.30 -> Class1
x80=0.12 -> Class1
k=2
x51=0.57 -> Class2
x52=0.44 -> Class1
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
x57=0.65 -> Class2
x58=0.25 -> Class1
x59=0.47 -> Class1
x60=0.24 -> Class1
x61=0.16 -> Class1
x62=0.11 -> Class1
x63=0.66 -> Class2
x64=0.14 -> Class1
x65=0.20 -> Class1
x66=0.37 -> Class1
x67=0.82 -> Class2
x68=0.10 -> Class1
x69=0.84 -> Class2
x70=0.10 -> Class1
x71=0.98 -> Class2
x72=0.47 -> Class1
x73=0.98 -> Class2
x74=0.60 -> Class2
k=3
x51=0.57 -> Class2
x52=0.44 -> Class1
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
x57=0.65 -> Class2
x58=0.25 -> Class1
x59=0.47 -> Class1
x60=0.24 -> Class1
x61=0.16 -> Class1
x62=0.11 -> Class1
x63=0.66 -> Class2
x64=0.14 -> Class1
x65=0.20 -> Class1
x66=0.37 -> Class1
x67=0.82 -> Class2
x68=0.10 -> Class1
k=4
x51=0.57 -> Class2
x52=0.44 -> Class1
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
x57=0.65 -> Class2
x58=0.25 -> Class1
x59=0.47 -> Class1
x60=0.24 -> Class1
x61=0.16 -> Class1
x62=0.11 -> Class1
k=5
x51=0.57 -> Class2
x52=0.44 -> Class1
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
k=20
x51=0.57 -> Class2
x52=0.44 -> Class1
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
x57=0.65 -> Class2
x58=0.25 -> Class1
x59=0.47 -> Class1
x60=0.24 -> Class1
x61=0.16 -> Class1
x62=0.11 -> Class1
x63=0.66 -> Class2
x64=0.14 -> Class1
x65=0.20 -> Class1
x66=0.37 -> Class1
x67=0.82 -> Class2
x68=0.10 -> Class1
x69=0.84 -> Class2
x70=0.10 -> Class1
x71=0.98 -> Class2
x72=0.47 -> Class1
x73=0.98 -> Class2
x74=0.60 -> Class2
x75=0.74 -> Class2
x76=0.04 -> Class1
x77=0.28 -> Class1
x78=0.12 -> Class1
x79=0.30 -> Class1
x80=0.12 -> Class1
x81=0.32 -> Class1
x82=0.41 -> Class1
x83=0.06 -> Class1
x84=0.69 -> Class2
x85=0.57 -> Class2
x86=0.27 -> Class1
x87=0.52 -> Class2
x88=0.09 -> Class1
x89=0.58 -> Class2
x90=0.93 -> Class2
x91=0.32 -> Class1
x92=0.67 -> Class2
x93=0.13 -> Class1
x94=0.72 -> Class2
x95=0.29 -> Class1
k=30
x51=0.57 -> Class2
x52=0.44 -> Class2
x53=0.99 -> Class2
x54=0.10 -> Class1
x55=0.21 -> Class1
x56=0.16 -> Class1
x57=0.65 -> Class2
x58=0.25 -> Class1
x59=0.47 -> Class2
x60=0.24 -> Class1
x61=0.16 -> Class1
x62=0.11 -> Class1
x63=0.66 -> Class2
x64=0.14 -> Class1
x65=0.20 -> Class1
x66=0.37 -> Class1
x67=0.82 -> Class2
x68=0.10 -> Class1
x69=0.84 -> Class2
x70=0.10 -> Class1
x71=0.98 -> Class2
x72=0.47 -> Class2
x73=0.98 -> Class2
x74=0.60 -> Class2
x75=0.74 -> Class2
x76=0.04 -> Class1
x77=0.28 -> Class1
x78=0.12 -> Class1
x79=0.30 -> Class1
x80=0.12 -> Class1
x81=0.32 -> Class1
x82=0.41 -> Class2
x83=0.06 -> Class1
x84=0.69 -> Class2
x85=0.57 -> Class2
x86=0.27 -> Class1
x87=0.52 -> Class2
x88=0.09 -> Class1
x89=0.58 -> Class2
ADDITIONAL PROGRAM 5
Write a Python program to demonstrate the working of the KNN algorithm using the Iris
dataset loaded from an online source.
import pandas as pd
from [Link] import KNeighborsClassifier
from [Link] import load_iris
try:
# Try loading Iris dataset from internet
url = "[Link]
df = pd.read_csv(url)
print("Online Iris dataset loaded")
OUTPUT
EXPERIMENT 6
[Link](0)
X = [Link](0, 2*[Link], 50)
y = [Link](X) + 0.1*[Link](50)
Xb, Xt = np.c_[[Link]([Link]), X], np.c_[[Link](100), [Link](0, 2*[Link], 100)]
tau = 0.4
yp = [Link]([lwr(x, Xb, y, tau) for x in Xt])
[Link](X, y, color='red')
[Link](Xt[:,1], yp, color='blue')
[Link]("Locally Weighted Regression")
[Link]()
OUTPUT
ADDITIONAL PROGRAM 6
Implement Robust Linear Regression using RANSAC algorithm and compare it with
ordinary Linear Regression using graphical analysis
import numpy as np
[Link](0)
X = [Link](1, 21).reshape(-1, 1)
y = 3 * [Link]() + 5 + [Link](20)
# Add outliers
y[3] += 25
y[14] -= 30
lr = LinearRegression()
[Link](X, y)
y_pred_lr = [Link](X)
ransac = RANSACRegressor(LinearRegression())
[Link](X, y)
y_pred_ransac = [Link](X)
[Link]("X")
[Link]("y")
[Link]()
[Link]()
OUTPUT
EXPERIMENT 7
#
# 1) Linear Regression - Boston Housing
#
boston = pd.read_csv("[Link]")
Xb, yb = boston[['rm']], boston['medv']
Xb_train, Xb_test, yb_train, yb_test = train_test_split(Xb, yb, test_size=0.2,
random_state=42)
lr = LinearRegression()
[Link](Xb_train, yb_train)
yb_pred = [Link](Xb_test)
#
# 2) Polynomial Regression - Auto MPG
#
auto = pd.read_csv("[Link]").replace('?', [Link])
auto['horsepower'] = auto['horsepower'].astype(float)
auto = [Link]()
Xa, ya = auto[['horsepower']].values, auto['mpg'].values
Xa_train, Xa_test, ya_train, ya_test = train_test_split(Xa, ya, test_size=0.2,
random_state=42)
poly = PolynomialFeatures(degree=2)
Xa_train_poly, Xa_test_poly = poly.fit_transform(Xa_train), [Link](Xa_test)
poly_model = LinearRegression()
poly_model.fit(Xa_train_poly, ya_train)
ya_pred = poly_model.predict(Xa_test_poly)
#
# RMSE
#
print("LR RMSE:", [Link](mean_squared_error(yb_test, yb_pred)))
print("Poly RMSE:", [Link](mean_squared_error(ya_test, ya_pred)))
OUTPUT
LR RMSE: 6.792994578778734
Poly RMSE: 4.858761912005639
ADDITIONAL PROGRAM 7
import numpy as np
[Link](42)
y = 3 * X**2 + 2 * X + 5 + [Link](50, 1) * 10
y = [Link]()
degrees = [1, 2, 3, 4, 5]
mse_list = []
for d in degrees:
poly = PolynomialFeatures(degree=d)
X_poly = poly.fit_transform(X)
model = LinearRegression()
scores = -cross_val_score(
model, X_poly, y,
scoring='neg_mean_squared_error',
cv=5
mse_list.append([Link]())
[Link]("Polynomial Degree")
[Link]()
OUTPUT
EXPERIMENT 8
8. Develop a program to demonstrate the working of the decision tree algorithm. Use
Breast Cancer Data set for building the decision tree and apply this knowledge to
classify a new sample.
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
OUTPUT
ADDITIONAL PROGRAM 8
Develop a program to demonstrate Decision Tree pruning by controlling tree depth and
compare model accuracy
for d in depths:
model = DecisionTreeClassifier(max_depth=d, criterion='entropy')
[Link](X_train, y_train)
y_pred = [Link](X_test)
acc = accuracy_score(y_test, y_pred)
[Link](acc)
OUTPUT
EXPERIMENT 9
# Download dataset
data = fetch_olivetti_faces(shuffle=True, random_state=42)
X = [Link]
y = [Link]
import numpy as np
import [Link] as plt
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from [Link] import accuracy_score, classification_report
data = [Link]('olivetti_faces.npz')
X, y = data['X'], data['y']
OUTPUT
Accuracy: 80.83%
Classification Report:
precision recall f1-score support
ADDITIONAL PROGRAM 9
Develop a small program to predict whether to play outside or not using the Naive Bayes
classifier
# Training data
X = [Link]([
[1, 0], # Sunny, Cold
[1, 1], # Sunny, Hot
[0, 1], # Rainy, Hot
[0, 0] # Rainy, Cold
])
# Train model
model = GaussianNB()
[Link](X, y)
if result[0] == 1:
print("Play Outside")
else:
print("Do Not Play")
OUTPUT
Do Not Play
EXPERIMENT 10
10. Develop a program to implement k-means clustering using Wisconsin Breast Cancer
data set and visualize the clustering result.
import pandas as pd
import [Link] as plt
import seaborn as sns
from [Link] import load_breast_cancer
from [Link] import StandardScaler
from [Link] import KMeans
from [Link] import PCA
from [Link] import confusion_matrix, classification_report
# K-Means clustering
y_kmeans = KMeans(n_clusters=2, random_state=42).fit_predict(X_scaled)
# Evaluation
print("Confusion Matrix:\n", confusion_matrix(y, y_kmeans))
print("\nClassification Report:\n", classification_report(y, y_kmeans))
# Plots
plot_scatter('Cluster', 'K-Means Clustering of Breast Cancer', 'Set1')
plot_scatter('True Label', 'True Labels of Breast Cancer', 'coolwarm')
plot_scatter('Cluster', 'K-Means Clustering with Centroids', 'Set1')
OUTPUT
Confusion Matrix:
[[175 37]
[ 13 344]]
Classification Report:
precision recall f1-score support
ADDITIONAL PROGRAM 10
# Apply K-Means
kmeans = KMeans(n_clusters=2, random_state=42)
[Link](X)
OUTPUT
Cluster Labels: [0 0 0 1 1 1]
SAMPLE PROGRAMS
# Transpose
for i in range(len(X)): # iterate over rows of X
for j in range(len(X[0])): # iterate over columns of X
result[j][i] = X[i][j]
# Print result
for r in result:
print(r)
OUTPUT
[12, 4, 3]
[7, 5, 8]
# Set union
print("Union of E and N is", E | N)
# Set intersection
print("Intersection of E and N is", E & N)
# Set difference
print("Difference of E and N is", E - N)
OUTPUT:
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {0, 8, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
print(count)
OUTPUT
{'a': 2, 'e': 5, 'i': 3, 'o': 5, 'u': 3}
# Sample dataset
reviews = ["I love this product", "This is terrible", "Absolutely fantastic",
"Worst purchase ever", "Very happy with it", "I hate it"]
labels = [1, 0, 1, 0, 1, 0] # 1=positive, 0=negative
# Vectorize text
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(reviews)
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.33,
random_state=42)
OUTPUT
Accuracy: 0.5
X = df[['Change']]
y = df['Up']
print("Predictions:", y_pred)
print("Accuracy:", accuracy_score(y_test, y_pred))
OUTPUT
Predictions: [1 1]
Accuracy: 0.0
VIVA QUESTIONS
5. What is PCA?
Answer:
Principal Component Analysis reduces the dimensionality of data while preserving most
variance.
• Converts correlated features into principal components.
• Useful for visualization and reducing computation.