ML Assignment Jordan1
ML Assignment Jordan1
BIC703 6
A
report on
Bachelor of Engineering
in
INTERNET OF THINGS AND CSBT
Submitted by
2025-2026
1
Activity Based Learning - 1SP22IC02
BIC703 6
2
Activity Based Learning - 1SP22IC02
BIC703 6
Q1. Load a dataset of your choice (from [Link], Kaggle, or a local CSV file). Display the first few
rows of the dataset. Print the dataset shape and column data types. Identify the target (dependent)
variable and independent (input) features.
import pandas as pd
from [Link] import load_iris
print("Q1: Load a dataset and perform basic
exploration\n") iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) df['target'] =
[Link]
print("First 5 rows of the
dataset:") display([Link]())
print("\nDataset Shape:")
print([Link])
print("\nColumn Data
Types:") print([Link])
target = 'target'
features = [Link][:-1] print("\
nTarget (Dependent) Variable:")
print(target)
print("\nIndependent (Input)
Features:") print(list(features))
print("\n--- Completed by USN: 1SP22IC014 ---")
output:
Q1: Load a dataset and perform basic exploration
Dataset Shape:
(150, 5)
Q2. Perform basic data quality analysis. Check for missing values and duplicates. Handle missing values
using at least two different techniques (for example, mean/median imputation and forward fill). Explain
which technique is most appropriate for your dataset.
print("Q2: Basic Data Quality Analysis
\n") iris = load_iris()
df = [Link]([Link], columns=iris.feature_names)
df['target'] = [Link]
print("Missing values in the
dataset:") print([Link]().sum())
print("\nNumber of duplicate
rows:")
print([Link]().sum())
[Link][2, 1] = None
[Link][5, 3] = None
print("\nMissing values after inserting sample NaNs:")
print([Link]().sum())
3
Activity Based Learning - 1SP22IC02
BIC703
df_mean_imputed = [Link]()
6
4
Activity Based Learning - 1SP22IC02
BIC703 6
df_mean_imputed.fillna(df_mean_imputed.mean(),
inplace=True) print("\nMissing values after Mean
Imputation:") print(df_mean_imputed.isnull().sum())
df_ffill = [Link]()
df_ffill.fillna(method='ffill',
inplace=True) print("\nMissing values
after Forward Fill:")
print(df_ffill.isnull().sum())
print("\n--- Completed by USN: 1SP22IC014
---") output :
output:
Q2: Basic Data Quality Analysis
Q3. Conduct an initial exploratory data analysis (EDA). Display summary statistics using .describe(). Plot
histograms for numeric columns to understand data distribution. Identify and comment on any skewed
features.
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) df['target'] =
[Link]
print("Summary
Statistics:")
print([Link]())
[Link](figsize=(9, 6))
[Link]("Histograms of Numeric Features (Iris Dataset)")
[Link]()
print("\nSkewness of
features:") print([Link][:, :-
1].skew())
print("\nComments:")
for col in [Link][:-1]:
skew = df[col].skew()
if skew > 0.5:
print(f"{col} is positively skewed.")
elif skew < -0.5:
5
Activity Based Learning - 1SP22IC02
BIC703
print(f"{col} is negatively skewed.")
6
6
Activity Based Learning - 1SP22IC02
BIC703 6
else:
print(f"{col} is approximately
Output
:
Q3: Exploratory Data Analysis
Summary Statistics:
sepal length (cm) sepal width (cm) petal
length (cm) \ count 150.000000 150.000000
150.000000
mean 5.843333 3.05733 3.75800
3 0
std 0.828066 0.435866 1.765298
min 4.300000 2.000000 1.000000
25% 5.100000 2.800000 1.600000
50% 5.800000 3.000000 4.350000
75% 6.400000 3.300000 5.100000
max 7.900000 4.400000 6.900000
Skewness of features:
sepal length (cm)
0.314911 sepal width
(cm) 0.318966 petal
length (cm) -0.274884
petal width (cm) -
0.102967 dtype: float64
Comments:
sepal length (cm) is approximately
symmetric. sepal width (cm) is
approximately symmetric. petal length
(cm) is approximately symmetric. petal
width (cm) is approximately
symmetric.
Q4. Detect and handle outliers. Use visualizations such as box plots to identify outliers in numerical
features. Apply the Interquartile Range (IQR) method to remove or cap outliers. Explain the effect of
outlier treatment on data distribution.
7
Activity Based Learning - 1SP22IC02
BIC703
Q1 =
6
[Link](0.25) Q3
= [Link](0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 *
IQR
df_clean = df[~((df < lower_bound) | (df >
upper_bound)).any(axis=1)] print("Shape before removing
outliers:", [Link])
print("Shape after removing outliers :",
df_clean.shape) df_clean.iloc[:, :-
1].boxplot(figsize=(8, 6))
[Link]("Box Plot AFTER Outlier
Treatment") [Link]()
8
Activity Based Learning - 1SP22IC02
BIC703 6
print("\nSkewness Before
Treatment:") print([Link][:, :-
1].skew()) print("\nSkewness
After Treatment:")
print(df_clean.iloc[:, :-1].skew())
print("\n--- Completed by USN: 1SP22IC014 ---")
Output:
Q4: Outlier Detection and Treatment
Q5. Perform feature scaling. Apply both Standardization (Z-score scaling) and Normalization (Min-Max
scaling) on the dataset. Compare the results using summary statistics or visualizations. 1 Activity Based
Learning -BIC703 Explain why scaling is essential for algorithms such as KNN or SVM.
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) df['target'] =
[Link]
X = [Link][:, :-1]
scaler_standard = StandardScaler()
X_standard =
scaler_standard.fit_transform(X)
df_standard = [Link](X_standard,
columns=[Link]) print("Summary Statistics after
Standardization:") print(df_standard.describe())
scaler_minmax = MinMaxScaler()
X_minmax = scaler_minmax.fit_transform(X)
df_minmax = [Link](X_minmax,
columns=[Link]) print("\nSummary Statistics after
Min-Max Normalization:") print(df_minmax.describe())
[Link](figsize=(10, 6))
df_standard.boxplot()
[Link]("Box Plot After
9
Activity Based Learning - 1SP22IC02
BIC703
Standardization") [Link]()
6
[Link](figsize=(10, 6))
df_minmax.boxplot()
10
Activity Based Learning - 1SP22IC02
BIC703 6
1.003350e+00 min
-
1.447076e+00 25%
-
1.183812e+00
50% 1.325097e-01
75% 7.906707e-
01 max
1.712096e+00
petal width
(cm) count
150.000000
mean 0.458056
std 0.317599
min 0.000000
25% 0.083333
50% 0.500000
75% 0.708333
max 1.000000
--- Completed by USN: 1SP22IC014 ---
Q6. Handle categorical features. Identify categorical variables in your dataset. Apply Label Encoding
and One-Hot Encoding using appropriate methods from pandas or sklearn. Compare the results and
explain which encoding method is preferable for different types of algorithms (e.g., linear vs. tree-
based).
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) df['species'] =
11
Activity Based Learning - 1SP22IC02
BIC703
[Link]
6
df['species'] =
df['species'].astype('category')
print("Categorical Variables in
Dataset:")
print(df.select_dtypes(include=['categor
y'])) label_encoder = LabelEncoder()
df['species_label_encoded'] = label_encoder.fit_transform(df['species'])
print("\nAfter Label Encoding (first 5 rows):")
print(df[['species', 'species_label_encoded']].head())
df_onehot = pd.get_dummies(df, columns=['species'],
prefix='species') print("\nAfter One-Hot Encoding (first 5
rows):") print(df_onehot.head())
print("\nShape before encoding:", [Link])
print("Shape after One-Hot Encoding:",
df_onehot.shape) print("\n--- Completed by USN:
1SP22IC014 ---")
12
Activity Based Learning - 1SP22IC02
BIC703 6
Output :
Q6: Handling Categorical Features
Q7. Perform feature discretization (binning). Select one continuous variable and divide it into bins using
[Link]() or [Link](). Display the count of values in each bin. Explain the potential advantages of feature
binning in predictive modeling.
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) df['target'] =
[Link]
feature = 'petal length (cm)'
df['petal_length_bin'] =
[Link](df[feature],
bins=3,
labels=["Short", "Medium", "Long"])
print("First 10 entries with bins:")
print(df[[feature,
'petal_length_bin']].head(10)) print("\
nValue counts per bin:")
print(df['petal_length_bin'].value_counts()
) print("\n--- Completed by USN:
1SP22IC014 ---")
output:
13
Activity Based Learning - 1SP22IC02
BIC703
petal length (cm) petal_length_bin
6
14
Activity Based Learning - 1SP22IC02
BIC703 6
0 1.4 Short
1 1.4 Short
2 1.3 Short
3 1.5 Short
4 1.4 Short
5 1.7 Short
6 1.4 Short
7 1.5 Short
8 1.4 Short
9 1.5 Short
Q8. Create polynomial and interaction features. Use PolynomialFeatures from [Link]
to create higher-order and interaction features (e.g., degree = 2). Display the new feature matrix shape
and names. Discuss how polynomial features affect model complexity and performance.
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) poly =
PolynomialFeatures(degree=2,
include_bias=False) poly_features =
poly.fit_transform(df)
feature_names =
poly.get_feature_names_out([Link]) df_poly =
[Link](poly_features, columns=feature_names)
print("Original feature shape:", [Link])
print("After polynomial transformation:",
df_poly.shape) print("\nFirst 5 rows of transformed
feature space:") print(df_poly.head())
print("\n--- Completed by USN: 1SP22IC014 ---")
Output:
sepal length (cm) petal length (cm) sepal length (cm) petal width (cm) \
0 7.14 1.02
1 6.86 0.98
2 6.11 0.94
3 6.90 0.92
4 7.00 1.00
15
Activity Based Learning - 1SP22IC02
BIC703
2 10.24 4.16
6
16
Activity Based Learning - 1SP22IC02
BIC703 6
3 9.61 4.65
4 12.96 5.04
QG. Apply feature transformation to reduce skewness. Identify skewed features using skewness statistics.
Apply log, square root, or Box-Cox transformations to normalize the distribution. Compare the feature
distributions before and after transformation using histograms.
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) print("Skewness
before transformation:")
print([Link]())
df['log_petal_length'] = np.log1p(df['petal length
(cm)']) df['sqrt_petal_length'] = [Link](df['petal
length (cm)']) df['boxcox_petal_length'], _ =
boxcox(df['petal length (cm)'])
[Link](figsize=(12, 8))
[Link](figsize=(12, 8))
[Link](2, 2, 1)
[Link](df['petal length (cm)'],
color='red') [Link]("Original")
[Link](2, 2, 2)
[Link](df['log_petal_length'],
color='green') [Link]("Log Transform")
[Link](2, 2, 3)
[Link](df['sqrt_petal_length'],
color='blue') [Link]("Sqrt Transform")
[Link](2, 2, 4)
[Link](df['boxcox_petal_length'],
color='purple') [Link]("Box-Cox
Transform")
plt.tight_layout()
[Link]()
print("\nSkewness after transformations:")
print("Log Transform :",
df['log_petal_length'].skew()) print("Sqrt Transform
:", df['sqrt_petal_length'].skew()) print("Box-Cox
Transform :", df['boxcox_petal_length'].skew()) print("\
n--- Completed by USN: 1SP22IC014 ---")
Output:
Skewness before
transformation: sepal length
(cm) 0.314911 sepal width
(cm) 0.318966 petal length
(cm) -0.274884 petal width
(cm) -0.102967 dtype:
float64
<Figure size 1200x800 with 0 Axes>
17
Activity Based Learning - 1SP22IC02
BIC703
Transform : -
6
0.44901356468696196 Box-Cox
Transform : -0.301163625962206
--- Completed by USN: 1SP22IC014 ---
18
Activity Based Learning - 1SP22IC02
BIC703 6
Q10. Perform feature selection. Use one of the following methods to select the most relevant features: o
Variance Threshold o SelectKBest o Recursive Feature Elimination (RFE) Display the top selected features.
Explain how feature selection helps in improving model performance and interpretability.
iris = load_iris()
df = [Link]([Link],
columns=iris.feature_names) target = [Link]
selector = SelectKBest(score_func=f_classif, k=2)
[Link](df, target)
mask = selector.get_support()
selected_features =
[Link][mask] print("Top
Selected Features:")
print(selected_features)
scores = selector.scores_
print("\nFeature Scores:")
for col, score in zip([Link], scores):
print(f"{col}: {score:.2f}")
print("\n--- Completed by USN: 1SP22IC014 ---")
Output:
Feature Scores:
sepal length (cm):
119.26 sepal width
(cm): 49.16 petal
length (cm): 1180.16
petal width (cm):
960.01
Q11. Summarize your overall findings. Which feature engineering steps had the greatest impact on
data quality or model readiness? What challenges did you face during feature engineering? How
would you improve your feature engineering process for a large, complex dataset?
✅ Which feature engineering steps had the greatest impact on data quality or model readiness?
● Handling missing values improved data completeness and prevented model bias or errors.
● Encoding categorical variables (Label Encoding / One-Hot Encoding) made non-numerical
features usable for ML algorithms.
● Feature scaling (StandardScaler / MinMaxScaler) boosted the performance of distance-
based models such as K-Means, SVM, and KNN by standardizing feature ranges.
● Removing duplicate or irrelevant features reduced noise and improved model efficiency.
● Feature selection (Variance Threshold, SelectKBest, RFE) removed weak predictors,
improving training speed and sometimes accuracy.
● Dimensionality reduction techniques (PCA) helped simplify high-dimensional data and reduced
overfitting.
✅ How to Improve the Feature Engineering Process for Large, Complex Datasets
● Automate preprocessing pipelines with tools like [Link] to ensure consistency.
● Use advanced feature selection techniques such as mutual information, tree-based
importance, or embedded regularization.
19
Activity Based Learning - 1SP22IC02
BIC703 6
● Apply dimensionality reduction (PCA, t-SNE, Autoencoders) to handle thousands of features efficiently.
20
Activity Based Learning - 1SP22IC02
BIC703 6
● Use distributed processing tools like Spark or Dask to manage large volumes of data.
● Perform exploratory data analysis (EDA) early to identify patterns, correlations, and outliers.
● Leverage domain knowledge to engineer meaningful features beyond raw data.
● Monitor feature drift when data changes over time in real-world systems.
Q1. Dataset Loading and Overview Load a dataset of your choice (you may use [Link], Kaggle data,
or a local CSV file). Display the first 5 rows of the dataset. Show dataset shape, column names, and
data types. Identify the target (dependent) and input (independent) features.
df = pd.read_csv("[Link]")
print("\n--- First 5 Rows of the Dataset ---")
print([Link]())
print("\n--- Dataset Shape ---")
print([Link])
print("\n--- Column Names ---")
print([Link])
print("\n--- Data Types of Each Column ---")
print([Link])
X = [Link](['Final_Score'], axis=1)
y = df['Final_Score']
print("\n--- Independent (Input) Features ---")
print([Link])
print("\n--- Target (Dependent) Feature ---")
print([Link])
print("\nCompleted by USN - 1SP22IC014!")
Output:
Final_Score
0 57
1 60
2 54
3 65
4 70
22
Activity Based Learning - 1SP22IC02
BIC703 6
models. Convert any necessary data columns to their appropriate types (e.g., convert object → category or
datetime).
df =
pd.read_csv("[Link]")
print("\n--- Current Data Types
---") print([Link])
numerical_features = df.select_dtypes(include=['int64',
'float64']).[Link]() categorical_features =
df.select_dtypes(include=['object']).[Link]()
datetime_features =
df.select_dtypes(include=['datetime']).[Link]() print("\n---
Numerical Features ---")
print(numerical_features)
print("\n--- Categorical Features ---")
print(categorical_features)
print("\n--- Datetime Features ---")
print(datetime_features) print("\
nCompleted By USN - 1SP22IC014!")
Output:
Q3. Tabular Data Representation using Pandas Represent your dataset as a DataFrame. Display
column statistics using .describe() and .info(). Explain how tabular representation in Pandas helps in
efficient data processing and manipulation.
df = pd.read_csv("[Link]")
print("\nCompleted By USN -
1SP22IC014!") print("\n")
output:
23
Activity Based Learning - 1SP22IC02
BIC703 4 105 Karan Marketing 2022- 1
6
01-03 45000
24
Activity Based Learning - 1SP22IC02
BIC703 6
Q4. Numerical Data Representation Isolate the numerical features from your dataset. Calculate basic
statistics such as mean, median, mode, variance, and standard deviation for each numerical column.
Visualize the distributions using histograms or boxplots.
df = pd.read_csv("[Link]")
numeric_df = df.select_dtypes(include=['int64',
'float64']) print("\n--- Numerical Features ---")
print(numeric_df.columns)
25
Activity Based Learning - 1SP22IC02
BIC703
print("\n--- Mean ---")
6
print(numeric_df.mean())
print("\n--- Median ---")
print(numeric_df.median())
print("\n--- Mode ---")
print(numeric_df.mode().iloc
[0])
26
Activity Based Learning - 1SP22IC02
BIC703 6
output:
4.066667 dtype:
float64
2.227312 dtype:
float64
Q5. Categorical Data Representation Identify categorical features and list unique categories for each.
Represent categorical data numerically using Label Encoding or One-Hot Encoding. Explain how
categorical encoding changes data representation for machine learning algorithms.
df = pd.read_csv("[Link]")
categorical_cols =
df.select_dtypes(include=['object']).columns print("\n---
27
Activity Based Learning - 1SP22IC02
BIC703
Categorical Features------------\n")
6
print(categorical_cols)
print("\n--- Unique Categories for Each Categorical Feature \n")
for col in categorical_cols:
28
Activity Based Learning - 1SP22IC02
BIC703 6
print(f"{col}:
{df[col].unique()}") print("\n---
Label Encoding Result ---\n")
label_df = [Link]()
le = LabelEncoder()
for col in categorical_cols:
label_df[col] = le.fit_transform(label_df[col])
print(label_df.head())
print("\n--- One-Hot Encoding Result ---\n")
onehot_df = pd.get_dummies(df, columns=categorical_cols)
print(onehot_df.head())
print("\nCompleted By USN -
1SP22IC014!") print("\n")
output:
29
Activity Based Learning - 1SP22IC02
BIC703 6
Q6. Visual Data Representation Create at least three plots to represent different aspects of your data: o
Histogram or density plot for numerical data o Count plot or bar chart for categorical data o Correlation
heatmap for relationships between numerical features 3 Explain what insights you gain from each
visualization.
data = {
"Product_ID": range(101, 126),
"Price": [1200,1500,55000,8000,2000,3000,1800,900,1400,60000,
700,1600,3500,1800,500,2000,2600,3000,4500,2500,
7500,65000,1800,58000,1600],
"Category": ["Footwear","Clothing","Electronics","Accessories","Bags",
"Electronics","Clothing","Accessories","Footwear","Electronics",
"Accessories","Clothing","Electronics","Clothing","Accessories",
"Electronics","Footwear","Clothing","Electronics","Bags",
"Accessories","Electronics","Clothing","Electronics","Clothing"]
}
df = [Link](data)
[Link]()
[Link](df["Price"] ,
color='orange')
[Link]("Histogram of Product
Price") [Link]("Price")
[Link]("Frequency")
[Link]()
[Link]()
df["Category"].value_counts().plot(kind="bar",
color='g') [Link]("Category Count Bar Chart")
[Link]("Category")
[Link]("Count")
[Link]()
corr =
[Link](numeric_only=True)
[Link]()
[Link](corr)
[Link]()
[Link]("Correlation Heatmap (Numerical Features)")
[Link](range(len([Link])), [Link],
rotation=45) [Link](range(len([Link])),
[Link])
[Link]()
print("\n✅ Completed By USN - 1SP22IC014!")
Output:
30
Activity Based Learning - 1SP22IC02
BIC703 6
Q7. Sparse vs. Dense Data Representation Create an example of a sparse matrix and a dense matrix
using NumPy or SciPy. Convert a dense matrix into a sparse representation. Explain where sparse
data representation is beneficial (e.g., text mining, recommender systems).
dense_matrix =
[Link]([ [5, 1, 3],
[2, 0, 4],
[0, 6, 7]
])
print("Dense Matrix:")
print(dense_matrix)
sparse_matrix =
[Link]([
[0, 0, 3, 0],
[4, 0, 0, 0],
[0, 0, 0, 5],
[0, 2, 0, 0]
])
print("\nSparse Matrix (normal ndarray):")
print(sparse_matrix)
sparse_csr = csr_matrix(sparse_matrix)
print("\nSparse Matrix (CSR
Representation):") print(sparse_csr)
print("\nData stored in CSR:")
print(sparse_csr.data)
print("\nRow indices:", sparse_csr.indices)
print("\n✅ Sparse representation stores only non-zero values
efficiently!") print("\n ---Completed By USN - 1SP22IC014")
Output:
Q7. Sparse vs Dense Data Representation
Dense Matrix:
[[5 1 3]
[2 0 4]
[0 6 7]]
Sparse Matrix (normal
ndarray): [[0 0 3
0]
[4 0 0 0]
[0 0 0 5]
[0 2 0 0]]
Sparse Matrix (CSR
Representation): (0,
2) 3
(1, 0) 4
(2, 3) 5
(3, 1) 2
Data stored in CSR:
[3 4 5 2]
31
Activity Based Learning - 1SP22IC02
BIC703 6
Row indices: [2 0 3 1]
Q8. Vector and Matrix Representation for ML Models Convert your dataset into a NumPy array or
matrix format. Display the shape and data type of this matrix. Explain how representing data as
vectors and matrices enables efficient mathematical computation in ML algorithms.
data = {
"Category": ["Footwear","Clothing","Electronics","Accessories","Bags",
"Electronics","Clothing","Accessories","Footwear","Electronics"],
"Brand": ["Nike","Adidas","HP","Fossil","Puma",
"Sony","Nike","Puma","Adidas","Apple"],
"Size":
["Medium","Large","None","Small","Large",
"Medium","Medium","Small","Large","None"],
"Payment_Method":
["Online","Cash","UPI","Online","Card",
"UPI","Cash","Card","Online","Card"]
}
df =
[Link](data)
print("Original
DataFrame:") print(df)
df_encoded = [Link](lambda col:
[Link](col)[0]) matrix =
df_encoded.to_numpy()
print("\nConverted NumPy
Matrix:") print(matrix)
print("\nShape of Matrix:",
[Link]) print("Data Type:",
[Link])
print("\n -- Completed By USN - 1SP22IC014")
Output:
Q8. Vector and Matrix Representation for ML
Shape of Matrix:
(10, 4) Data Type:
int64
QG. Feature Scaling and Normalization for Representation Apply StandardScaler and MinMaxScaler on
numerical features. Compare how the values are represented before and after scaling. Explain how
scaling affects model convergence and distance-based algorithms.
32
Activity Based Learning - 1SP22IC02
BIC703
data = {
6
"Price": [1200, 55000, 8000, 2000, 3000, 1400, 60000, 3500, 500, 7500],
33
Activity Based Learning - 1SP22IC02
BIC703 6
output:
Q10. Reflection and Discussion Answer the following questions in Markdown: 1. Why is proper data
representation crucial in building effective ML models? 2. How does data representation differ between
numerical, categorical, and text data? 3. What steps would you take to ensure your dataset is well-
represented for model training and interpretation?
34
Activity Based Learning - 1SP22IC02
BIC703 6
Proper data representation is essential because machine learning models rely on patterns within the input data. If
data is poorly represented, the model may:
● Misinterpret relationships between features
● Produce biased or inaccurate predictions
● Perform poorly on unseen data
● Converge slower or not learn meaningful
patterns Good representation:
● Preserves useful information
● Reduces noise and redundancy
● Improves interpretability
● Enhances training efficiency and accuracy
In simple terms, better representation = better learning.
[Link] does data representation differ between numerical, categorical, and text data?
● Numerical Data
o Represents quantities and continuous values.
o Often requires scaling or normalization.
o Supports distance-based algorithms directly.
● Categorical Data
o Represents labels or groups (e.g., colors, types).
o Must be encoded (One-Hot, Label Encoding).
o Cannot be used directly in distance-based models.
● Text Data
o Represents unstructured language information.
o Requires tokenization, TF-IDF, embeddings, or vectorization.
o Has high dimensionality and sparsity.
Each type needs a different encoding strategy to be meaningful for model training.
[Link] steps would you take to ensure your dataset is well-represented for model training
and interpretation? To ensure high-quality representation:
● Handle missing values using strategies like mean, median, or modelling.
● Encode categorical variables using the appropriate technique.
● Scale numerical features for distance-based algorithms.
● Normalize distributions if skewed.
● Remove duplicates or irrelevant features to reduce noise.
● Perform feature selection to reduce dimensionality and improve generalization.
● Use text vectorization (TF-IDF, word embeddings) for documents.
● Detect and handle outliers to prevent bias.
● Conduct exploratory data analysis (EDA) to understand relationships.
● Apply dimensionality reduction (PCA) when dealing with high dimensions.
Q1. Dataset Loading and Overview Load a regression dataset (you may use [Link] such as California
Housing, Boston Housing, or any other dataset). Display the first 5 rows of the dataset. Print dataset
shape, column names, and data types. Identify the input (independent) features and target (dependent)
variable.
data = fetch_california_housing()
df = [Link]([Link], columns=data.feature_names)
df['Target'] = [Link]
print("\nFirst 5 rows of the dataset:")
print([Link]())
print("\nDataset Shape (rows, columns):")
print([Link])
print("\nColumn Names:")
print([Link]) print("\
nData Types:")
print([Link])
print("\nInput (Independent) Features:")
print(data.feature_names) print("\
nTarget (Dependent) Variable:")
print("Target (House Value)")
Output:
35
Activity Based Learning - 1SP22IC02
BIC703 6
Longitude Target
0 -122.23 4.526
1 -122.22 3.585
2 -122.24 3.521
3 -122.25 3.413
4 -122.25 3.422
Column Names:
Index(['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population',
'AveOccup', 'Latitude', 'Longitude', 'Target'],
dtype='object')
Data Types:
MedInc float64
HouseAge
float64
AveRooms
float64
AveBedrms
float64
Population
float64 AveOccup
float64 Latitude
float64
Longitude
float64 Target
float64
dtype: object
Input (Independent) Features:
['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']
Q2. Exploratory Data Analysis (EDA) Perform exploratory data analysis to understand the dataset. Check
for missing values and handle them if necessary. Show statistical summary using .describe(). 4 Plot
distributions of key features and the target variable. Create a correlation heatmap to identify relationships
between features.
data = fetch_california_housing()yy
df = [Link]([Link],
columns=data.feature_names) df['Target'] = [Link]
print("\nChecking missing
values:") print([Link]().sum())
if [Link]().sum().sum() > 0:
[Link]([Link](), inplace=True)
print("Missing values handled using mean
imputation.") else:
print("No missing values found.")
print("\nStatistical Summary:")
print([Link]())
print("\nPlotting distributions of key features...")
df[['MedInc', 'AveRooms', 'Population',
'Target']].hist(figsize=(10,8)) [Link]("Distribution of Key
Features", fontsize=14)
[Link]()
print("\nGenerating correlation heatmap...")
[Link](figsize=(10,6))
[Link]([Link](), annot=False,
cmap='coolwarm') [Link]("Correlation Heatmap")
36
Activity Based Learning - 1SP22IC02
BIC703
[Link]()
6
output:
37
Activity Based Learning - 1SP22IC02
BIC703 6
Statistical Summary:
MedInc HouseAge AveRooms AveBedrms Population \
count 20640.000000 20640.000000 20640.000000 20640.000000 20640.000000
mean 3.870671 28.639486 5.429000 1.096675 1425.476744
std 1.899822 12.585558 2.474173 0.473911 1132.462122
min 0.499900 1.000000 0.846154 0.333333 3.000000
25% 2.563400 18.000000 4.440716 1.006079 787.000000
50% 3.534800 29.000000 5.229129 1.048780 1166.000000
75% 4.743250 37.000000 6.052381 1.099526 1725.000000
max 15.000100 52.000000 141.909091 34.066667 35682.000000
Q3. Data Preparation for Regression Split the dataset into training and testing sets (e.g., 80% train, 20%
test). Apply feature scaling using StandardScaler or MinMaxScaler. Print the shapes of training and
testing data. Explain why data splitting and scaling are important before training a regression model.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df['Target'] = [Link]
X = [Link]('Target',
axis=1) y = df['Target']
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
38
Activity Based Learning - 1SP22IC02
BIC703 6
)
print("\nTraining data
shape:") print(X_train.shape,
y_train.shape) print("\
nTesting data shape:")
print(X_test.shape,
y_test.shape) scaler =
StandardScaler()
X_train_scaled =
scaler.fit_transform(X_train) X_test_scaled
= [Link](X_test) print("\nScaling
completed using StandardScaler.") print("\n✅
Q3 Completed by USN: 1SP22IC014")
output:
Q3. DATA PREPARATION FOR REGRESSION
Q4. Simple Linear Regression Implement a Simple Linear Regression model using one independent
variable (e.g., MedInc → MedHouseValue). Train the model and display the regression coefficient and
intercept. Plot the regression line along with actual data points. Evaluate the model using R² score and
RMSE (Root Mean Squared Error).
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df['Target'] = [Link]
X=
df[['MedInc']] y
= df['Target']
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
)
model =
LinearRegression()
[Link](X_train, y_train)
y_pred =
[Link](X_test)
print("\nRegression Coefficient (Slope):",
model.coef_[0]) print("Regression Intercept:",
model.intercept_)
r2 = r2_score(y_test, y_pred)
rmse = [Link](mean_squared_error(y_test, y_pred))
print("\nR² Score:", r2)
print("RMSE:", rmse)
[Link](X_test, y_test)
[Link](X_test, y_pred, linewidth=2 ,color='g')
[Link]("Median Income (MedInc)")
[Link]("Median House Value (Target)")
[Link]("Simple Linear Regression: MedInc vs
Target") [Link]()
print("\n✅ Q4 Completed by USN: 1SP22IC014")
output:
39
Activity Based Learning - 1SP22IC02
BIC703
✅ Q4 Completed by USN: 1SP22IC014
6
Q5. Multiple Linear Regression Implement Multiple Linear Regression using all numerical features.
Display model coefficients and intercept. Evaluate performance using R² and RMSE on both training and
test sets.
Compare results with your Simple Linear Regression model and explain the difference.
data = fetch_california_housing()
40
Activity Based Learning - 1SP22IC02
BIC703 6
df = [Link]([Link],
columns=data.feature_names) df['Target'] = [Link]
X = [Link]('Target',
axis=1) y = df['Target']
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
)
model = LinearRegression()
[Link](X_train, y_train)
y_train_pred =
[Link](X_train)
y_test_pred =
[Link](X_test) print("\
nModel Coefficients:")
for feature, coef in zip([Link], model.coef_):
print(f"{feature}: {coef}")
print("\nModel Intercept:",
model.intercept_) train_r2 =
r2_score(y_train, y_train_pred)
train_rmse = [Link](mean_squared_error(y_train,
y_train_pred)) test_r2 = r2_score(y_test, y_test_pred)
test_rmse = [Link](mean_squared_error(y_test,
y_test_pred)) print("\nTraining R² Score:", train_r2)
print("Training RMSE:",
train_rmse) print("\nTesting R²
Score:", test_r2) print("Testing
RMSE:", test_rmse)
print("\n✅ Q5 Completed by USN: 1SP22IC014")
output:
Q5. MULTIPLE LINEAR REGRESSION
Model Coefficients:
MedInc : 0.4486749096657176
HouseAge :
0.009724257517905023
AveRooms : -0.12332334282795863
AveBedrms : 0.7831449067929727
Population :-
2.0296205801885327e-
06
AveOccup : -0.00352631848713407
Latitude : -0.41979248658835966
Longitude : -0.43370806496398745
Training R² Score :
0.6125511913966953 Training RMSE
:
0.7196757085831573
Testing R² Score :
0.5757877060324507 Testing RMSE
:
0.7455813830127765
Q6. Polynomial Regression Use PolynomialFeatures (degree = 2 or 3) to create polynomial terms. Fit a
Polynomial Regression model using the transformed data. Compare the model’s R² and RMSE with Linear
Regression. Discuss the impact of polynomial degree on model performance (underfitting vs. overfitting).
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df['Target'] = [Link]
X=
df[['MedInc']] y
= df['Target']
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
41
Activity Based Learning - 1SP22IC02
BIC703
)
6
poly = PolynomialFeatures(degree=2)
X_train_poly =
poly.fit_transform(X_train) X_test_poly =
[Link](X_test) poly_model =
LinearRegression()
poly_model.fit(X_train_poly, y_train)
y_train_pred =
poly_model.predict(X_train_poly)
y_test_pred =
poly_model.predict(X_test_poly) train_r2
= r2_score(y_train, y_train_pred)
test_r2 = r2_score(y_test, y_test_pred)
42
Activity Based Learning - 1SP22IC02
BIC703 6
train_rmse = [Link](mean_squared_error(y_train,
y_train_pred)) test_rmse =
[Link](mean_squared_error(y_test, y_test_pred)) print("\
nPolynomial Regression Results:")
print("Training R²:", train_r2)
print("Testing R²:", test_r2)
print("Training RMSE:",
train_rmse) print("Testing
RMSE:", test_rmse)
simple_model =
LinearRegression()
simple_model.fit(X_train,
y_train)
y_test_simple =
simple_model.predict(X_test) simple_r2
= r2_score(y_test, y_test_simple)
simple_rmse = [Link](mean_squared_error(y_test,
y_test_simple)) print("\nSimple Linear Regression
Comparison:")
print("Simple Linear R²:", simple_r2)
print("Simple Linear RMSE:",
simple_rmse)
print("\n✅ Q6 Completed by USN: 1SP22IC014")
output:
Q6. POLYNOMIAL REGRESSION
Q7. Regularized Regression Models (Ridge and Lasso) Implement Ridge Regression and Lasso
Regression using scikit-learn. Train models using different regularization parameters (e.g., alpha = 0.1, 1,
10). Compare R² and RMSE for each model. Explain how regularization helps prevent overfitting.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df['Target'] = [Link]
X = [Link]('Target',
axis=1) y = df['Target']
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
)
scaler = StandardScaler()
X_train =
scaler.fit_transform(X_train) X_test
= [Link](X_test) alphas
= [0.1, 1, 10]
print("\n----- Ridge Regression Results")
for alpha in alphas:
ridge =
Ridge(alpha=alpha)
[Link](X_train, y_train)
y_pred =
[Link](X_test) r2 =
r2_score(y_test, y_pred)
rmse = [Link](mean_squared_error(y_test,
y_pred)) print(f"\nAlpha = {alpha}")
print("R² Score:", r2)
print("RMSE:", rmse)
43
Activity Based Learning - 1SP22IC02
BIC703
print("\n----- Lasso Regression Results ")
6
for alpha in alphas:
lasso =
Lasso(alpha=alpha)
[Link](X_train, y_train)
y_pred =
[Link](X_test) r2 =
r2_score(y_test, y_pred)
rmse = [Link](mean_squared_error(y_test,
y_pred)) print(f"\nAlpha = {alpha}")
print("R² Score:", r2)
print("RMSE:", rmse)
print("\n✅ Q7 Completed by USN: 1SP22IC014")
44
Activity Based Learning - 1SP22IC02
BIC703 6
Output:
Alpha = 0.1
R² Score: 0.5757905180002312
RMSE: 0.7455789118982767
Alpha = 1
R² Score: 0.5758157428913682
RMSE: 0.745556744281478
Alpha = 10
R² Score: 0.576059903284837
RMSE: 0.7453421422218557
Alpha = 0.1
R² Score: 0.48136113250290735
RMSE: 0.8243961598848472
Alpha = 1
R² Score: -0.00021908714592466794
RMSE: 1.1448563543099792
Alpha = 10
R² Score: -0.00021908714592466794
RMSE: 1.1448563543099792
Q8. Model Evaluation and Comparison Create a summary table comparing the following models: o Simple
Linear Regression o Multiple Linear Regression o Polynomial Regression 5 Activity Based Learning -BIC703
o Ridge Regression o Lasso Regression Include metrics such as RMSE and R² Score for each model.
Visualize comparison results using a bar chart.
data = load_diabetes()
df = [Link]([Link],
columns=data.feature_names) df["Target"] = [Link]
X = [Link]("Target",
axis=1) y = df["Target"]
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
)
scaler = StandardScaler()
X_train_scaled =
scaler.fit_transform(X_train)
X_test_scaled =
[Link](X_test) X_train_single
= X_train[["bmi"]] X_test_single =
X_test[["bmi"]]
simple_model = LinearRegression()
simple_model.fit(X_train_single, y_train)
y_pred_simple =
simple_model.predict(X_test_single)
multi_model = LinearRegression()
multi_model.fit(X_train_scaled, y_train)
y_pred_multi =
multi_model.predict(X_test_scaled) poly =
PolynomialFeatures(degree=2)
X_train_poly =
poly.fit_transform(X_train_single)
X_test_poly =
[Link](X_test_single) poly_model
= LinearRegression()
poly_model.fit(X_train_poly, y_train)
y_pred_poly =
poly_model.predict(X_test_poly) ridge =
Ridge(alpha=1)
45
Activity Based Learning - 1SP22IC02
BIC703
[Link](X_train_scaled, y_train)
6
y_pred_ridge =
[Link](X_test_scaled) lasso =
Lasso(alpha=1)
[Link](X_train_scaled, y_train)
46
Activity Based Learning - 1SP22IC02
BIC703 6
y_pred_lasso =
[Link](X_test_scaled) models = [
"Simple Linear
Regression", "Multiple
Linear Regression",
"Polynomial Regression",
"Ridge Regression",
"Lasso Regression"
]
r2_scores = [
r2_score(y_test,
y_pred_simple),
r2_score(y_test,
y_pred_multi),
r2_score(y_test,
y_pred_poly),
r2_score(y_test,
y_pred_ridge),
r2_score(y_test,
y_pred_lasso),
]
rmse_scores = [
[Link](mean_squared_error(y_test,
y_pred_simple)),
[Link](mean_squared_error(y_test,
y_pred_multi)),
[Link](mean_squared_error(y_test,
y_pred_poly)),
[Link](mean_squared_error(y_test,
y_pred_ridge)),
[Link](mean_squared_error(y_test,
y_pred_lasso)),
]
summary = [Link]({
"Model": models,
"R2 Score": r2_scores,
"RMSE": rmse_scores
})
print(summary)
[Link]()
[Link](models, r2_scores)
[Link](rotation=45)
[Link]("Model Comparison - R2
Score") [Link]("R2 Score")
[Link]()
[Link]()
[Link](models, rmse_scores)
[Link](rotation=45)
[Link]("Model Comparison -
RMSE") [Link]("RMSE")
[Link]()
Output:
47
Activity Based Learning - 1SP22IC02
BIC703 6
QG. Residual Analysis Plot residuals (y_actual - y_predicted) for at least two models. Check if residuals
are randomly distributed. Explain what residual analysis tells you about model bias and variance.
48
Activity Based Learning - 1SP22IC02
BIC703 6
data = load_diabetes()
df = [Link]([Link],
columns=data.feature_names) df["Target"] = [Link]
X = [Link]("Target",
axis=1) y = df["Target"]
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42
)
scaler = StandardScaler()
X_train_scaled =
scaler.fit_transform(X_train) X_test_scaled
= [Link](X_test) multi_model =
LinearRegression()
multi_model.fit(X_train_scaled, y_train)
y_pred_multi =
multi_model.predict(X_test_scaled) poly =
PolynomialFeatures(degree=2)
X_train_poly =
poly.fit_transform(X_train_scaled)
X_test_poly =
[Link](X_test_scaled)
poly_model = LinearRegression()
poly_model.fit(X_train_poly, y_train)
y_pred_poly =
poly_model.predict(X_test_poly)
residuals_multi = y_test - y_pred_multi
residuals_poly = y_test - y_pred_poly
[Link]()
[Link](y_pred_multi, residuals_multi , color='g')
[Link](0)
[Link]("Residuals - Multiple Linear
Regression") [Link]("Predicted
Values") [Link]("Residuals")
[Link]()
[Link]()
[Link](y_pred_poly, residuals_poly, color='g')
[Link](0)
[Link]("Residuals - Polynomial
Regression") [Link]("Predicted
Values") [Link]("Residuals")
[Link]()
print("\n✅ Q9 Completed by USN: 1SP22IC014")
Output:
================ Q9. Residual Analysis ================
Q10. Reflection and Discussion Answer the following in Markdown: 1. Which regression model performed
the best on your dataset and why? 2. How did regularization affect model complexity and performance? 3.
What are the trade-offs between model interpretability and accuracy in regression models? 4. What steps
would you take next to further improve your model’s performance?
[Link] regression model performed the best on your dataset and why?
Among the models tested, the Ridge Regression / Polynomial Regression / Multiple Linear Regression
(choose based on your results) performed the best. This is because:
49
Activity Based Learning - 1SP22IC02
BIC703 6
● It captured the underlying relationship between features and the target more effectively.
● It handled multicollinearity better (especially Ridge).
50
Activity Based Learning - 1SP22IC02
BIC703 6
[Link] are the trade-offs between model interpretability and accuracy in regression models?
● Simple models such as Linear Regression are highly interpretable. Each coefficient clearly explains a feature’s
contribution. However, these models may struggle with complex, non-linear relationships.
● More complex approaches like Polynomial Regression or regularized models can achieve higher accuracy but:
o Are harder to interpret
o Have coefficients that no longer map directly to simple feature
relationships So, more complexity often means less interpretability but potentially
higher predictive performance.
[Link] steps would you take next to further improve your model’s performance?
To improve performance further:
● Tune hyperparameters (degree of polynomial, regularization strength, etc.)
● Conduct more feature engineering such as interaction features or domain-specific transformations.
● Try advanced models like Gradient Boosting or Random Forest Regression.
● Perform cross-validation to ensure stable performance.
● Remove outliers, which can heavily influence regression results.
● Use feature selection to eliminate irrelevant predictors that
introduce noise. These steps would likely boost accuracy and make the
model more generalizable.
Program 1.4 : Programming Assignment: Implementation of Important Concepts of Nearest Neighbor Based Models
Q1. Dataset Loading and Overview Load a suitable dataset for a regression or classification task (you may
use [Link], Kaggle datasets, or a local CSV file). Display the first 5 rows of the dataset. Print
dataset shape, column names, and data types. Identify the target (dependent) variable and independent
features.
data = fetch_california_housing()
df = [Link]([Link], columns=data.feature_names)
df['PRICE'] = [Link]
print([Link]())
print([Link])
print([Link])
print([Link])
target = "PRICE"
features = [Link][:-1]
print(target)
print(list(features))
output:
MedInc HouseAge AveRooms AveBedrms Population AveOccup Latitude \
0 8.3252 41.0 6.984127 1.023810 322.0 2.555556 37.88
1 8.3014 21.0 6.238137 0.971880 2401.0 2.109842 37.86
2 7.2574 52.0 8.288136 1.073446 496.0 2.802260 37.85
3 5.6431 52.0 5.817352 1.073059 558.0 2.547945 37.85
4 3.8462 52.0 6.281853 1.081081 565.0 2.181467 37.85
Longitude PRICE
0 -122.23 4.526
1 -122.22 3.585
2 -122.24 3.521
3 -122.25 3.413
4 -122.25 3.422
(20640,
9)
Index(['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude',
'PRICE'], dtype='obj ect') MedInc float64
51
Activity Based Learning - 1SP22IC02
BIC703 HouseAge float64 6
AveRooms float64
52
Activity Based Learning - 1SP22IC02
BIC703 6
AveBedrms
float64
Population
float64 AveOccup
float64 Latitude
float64
Longitude
PRIC float64 PRICE
E float64
dtype: object
['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup', 'Latitude', 'Longitude']
Q2. Data Preprocessing Perform necessary preprocessing steps: Handle missing values if any. Encode
categorical variables using Label Encoding or One-Hot Encoding. Apply feature scaling (standardization or
normalization). Explain why feature scaling is critical for Nearest Neighbor algorithms.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
df =
[Link]([Link]())
scaler =
StandardScaler()
scaled = scaler.fit_transform([Link]("PRICE",
axis=1)) scaled_df = [Link](scaled,
columns=[Link][:-1]) scaled_df["PRICE"] =
df["PRICE"]
print(scaled_df.head())
X = scaled_df.drop("PRICE",
axis=1) y =
scaled_df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Output:
Longitude PRICE
0 -1.327835 4.526
1 -1.322844 3.585
2 -1.332827 3.521
3 -1.337818 3.413
4 -1.337818 3.422
Q3. Train-Test Split Split the dataset into training and testing sets (e.g., 80% train, 20% test). Display the
shapes of the resulting datasets. Explain the importance of splitting data for model evaluation.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
X = [Link]("PRICE",
axis=1) y = df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
Output:
(16512, 8)
(4128, 8)
(16512,)
(4128,)
53
Activity Based Learning - 1SP22IC02
BIC703 6
Q4. Implement K-Nearest Neighbors (KNN) Classifier or Regressor For classification tasks: use
KNeighborsClassifier. For regression tasks: use KNeighborsRegressor. Train the model with a specific
54
Activity Based Learning - 1SP22IC02
BIC703 6
value of k (number of neighbors). Display model parameters and basic performance metrics (e.g.,
accuracy for classification or R²/RMSE for regression).
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
X = [Link]("PRICE",
axis=1) y = df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model = KNeighborsRegressor(n_neighbors=5)
[Link](x_train, y_train)
y_pred =
[Link](x_test)
print(model)
print("R2 Score:", r2_score(y_test, y_pred))
print("RMSE:", [Link](mean_squared_error(y_test, y_pred)))
output :
KNeighborsRegressor()
R2 Score :
0.14631049965900345 RMSE
:
1.0576778270706204
Q5. Experiment with Different K Values Train the KNN model using different values of k (e.g., 1, 3, 5, 7, G, 11).
Evaluate and record the model’s performance for each k. Plot a graph showing model performance vs. k.
Identify the optimal k value and explain how it affects bias and variance.
data = load_iris()
X=
[Link] y
= [Link]
X_train, X_test, y_train, y_test =
train_test_split( X, y, test_size=0.2,
random_state=42)
k_values = [1, 3, 5, 7, 9, 11]
accuracies = []
for k in k_values:
knn = KNeighborsClassifier(n_neighbors=k)
[Link](X_train, y_train)
y_pred = [Link](X_test)
[Link](accuracy_score(y_test,
y_pred))
for k, acc in zip(k_values, accuracies):
print(f"k = {k}, Accuracy =
{acc:.3f}") [Link](figsize=(8, 5))
[Link](k_values, accuracies,
marker='o') [Link]("K value")
[Link]("Accuracy")
[Link]("KNN Accuracy vs K")
[Link](True)
[Link]()
output:
k = 1, Accuracy = 1.000
k = 3, Accuracy = 1.000
k = 5, Accuracy = 1.000
k = 7, Accuracy = 0.967
k = 9, Accuracy = 1.000
k = 11, Accuracy = 1.000
Q6. Distance Metrics Comparison Train KNN models using different distance metrics: o Euclidean o
Manhattan o Minkowski Compare performance results for each metric. Explain how the choice of
distance metric influences model performance.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
55
Activity Based Learning - 1SP22IC02
BIC703
X = [Link]("PRICE",
6
axis=1) y = df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
56
Activity Based Learning - 1SP22IC02
BIC703 6
output:
Q7. Effect of Feature Scaling (Practical Test) Train a KNN model without scaling and note its performance.
Then train the same model after scaling and compare results. Explain the observed difference in model
accuracy/performance.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
X = [Link]("PRICE",
axis=1) y = df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model1 = KNeighborsRegressor(n_neighbors=5)
[Link](x_train,
y_train) pred1 =
[Link](x_test)
print("Without Scaling R2:", r2_score(y_test,
pred1)) scaler = StandardScaler()
x_train_scaled =
scaler.fit_transform(x_train)
x_test_scaled = [Link](x_test)
model2 =
KNeighborsRegressor(n_neighbors=5)
[Link](x_train_scaled, y_train)
pred2 = [Link](x_test_scaled)
print("With Scaling R2:", r2_score(y_test,
pred2))
output:
Without Scaling R2 :
0.14631049965900345 With Scaling
R2 :
0.6700101862970989
Q8. Model Evaluation and Visualization For classification tasks: o Display the confusion matrix and
classification report. o Plot the decision boundary (if dataset is 2D). For regression tasks: o Plot actual
vs. predicted values. o Visualize residuals. Interpret what these visualizations reveal about model
performance.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
X = [Link]("PRICE",
axis=1) y = df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model = KNeighborsRegressor(n_neighbors=5)
[Link](x_train, y_train)
y_pred =
[Link](x_test)
[Link](y_test, y_pred,
color='r') [Link]("Actual
Values") [Link]("Predicted
Values") [Link]("Actual vs
Predicted") [Link]()
residuals = y_test - y_pred
[Link](y_pred, residuals ,
color='g') [Link]("Predicted
Values") [Link]("Residuals")
[Link]("Residual Plot")
[Link](0)
57
Activity Based Learning - 1SP22IC02
BIC703
[Link]()
6
output:
58
Activity Based Learning - 1SP22IC02
BIC703 6
QG. Hyperparameter Tuning using GridSearchCV Use GridSearchCV from scikit-learn to find the best
hyperparameters for the KNN model. Tune parameters such as: o n_neighbors o weights (uniform,
distance) o metric (euclidean, manhattan) 7 Activity Based Learning -BIC703 Display the best
parameters and their corresponding score. Discuss how hyperparameter tuning improved model
performance.
data = fetch_california_housing()
df = [Link]([Link],
columns=data.feature_names) df["PRICE"] = [Link]
X = [Link]("PRICE",
axis=1) y = df["PRICE"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) param_grid = {
'n_neighbors': [1, 3, 5, 7, 9, 11],
'weights': ['uniform', 'distance'],
'metric': ['euclidean',
'manhattan']
}
model = KNeighborsRegressor()
grid = GridSearchCV(model, param_grid, cv=5,
scoring='r2') [Link](x_train, y_train)
print(grid.best_params_)
print(grid.best_score_)
Output:
Q10. Reflection and Discussion Answer the following in Markdown: 1. What are the main strengths and
weaknesses of K-Nearest Neighbor models? 2. How does the choice of k influence model bias and variance?
3. Why is KNN considered a lazy learning algorithm? 4. In what types of real-world applications would KNN
perform well or poorly? 5. What strategies can be used to improve the efficiency of KNN on large datasets?
59
Activity Based Learning - 1SP22IC02
BIC703 6
● Small k (e.g., k = 1, 3)
o Low bias
o High variance
o Model becomes very sensitive to noise and overfits.
● Large k (e.g., k = 15, 20)
o High bias
o Low variance
o Model becomes too generalized and may
underfit. So, choosing k balances the bias-variance trade-off.
[Link] strategies can be used to improve the efficiency of KNN on large datasets?
● Feature Scaling (StandardScaler / MinMaxScaler)
● Dimensionality Reduction (PCA, t-SNE) to reduce computation
● Feature Selection to remove noisy or irrelevant attributes
● Use Efficient Data Structures like KD-Trees or Ball Trees
● Approximate Nearest Neighbor (ANN) algorithms for faster lookups
● Sampling or clustering to reduce training set size
These approaches significantly reduce computational cost and memory usage.
Assignment 1.5: Programming Assignment: Implementation of Important Concepts of Decision Tree Models
Q1. Dataset Loading and Overview Load a suitable dataset (you may use [Link], a Kaggle dataset,
or a CSV file). Display the first few rows of the dataset. Show dataset shape, column names, and data
types. Identify the target (dependent) variable and input (independent) features. Explain whether your
problem is a classification or regression task.
Output:
mean radius mean texture mean perimeter mean area mean smoothness \
60
Activity Based Learning - 1SP22IC02
BIC703 6
mean fractal dimension ... worst texture worst perimeter worst area \
0 0.07871 ... 17.33 184.60
2019.0
1 0.05667 ... 23.41 158.80
1956.0
2 0.05999 ... 25.53 152.50
1709.0
3 0.09744 ... 26.50 98.87 567.7
4 0.05883 ... 16.67 152.20
1575.0
[5 rows x 31 columns]
(569, 31)
Index(['mean radius', 'mean texture', 'mean perimeter', 'mean area', 'mean smoothness', 'mean
compactness', 'mean concavity','mean concave points', 'mean symmetry', 'mean fractal
dimension', 'radius error', 'texture error', 'perimeter error', 'area error', 'smoothness error',
'compactness error', 'concavity error','concave points error', 'symmetry error', 'fractal dimension
error','worst radius', 'worst texture', 'worst perimeter', 'worst area','worst smoothness', 'worst
compactness', 'worst concavity','worst concave points', 'worst symmetry', 'worst fractal
dimension','target'],dtype='object')
61
Activity Based Learning - 1SP22IC02
BIC703 6
mean fractal dimension
float64 radius error
float64
texture error float64
perimeter error
float64 area
error float64
smoothness error
float64
compactness error float64
concavity error
float64
concave points error
float64 symmetry error
float64
62
Activity Based Learning - 1SP22IC02
BIC703 6
float64
worst texture float64
worst perimeter
float64 worst
area float64
worst smoothness
float64 worst
compactness float64 worst
concavity
float64 worst
concave points float64 worst
symmetry
float64 worst
fractal dimension float64
target int32
dtype:
object target
['mean radius', 'mean texture', 'mean perimeter', 'mean area', 'mean smoothness', 'mean
compactness', 'mean concavity', 'mean concave points', 'mean symmetry', 'mean fractal
dimension', 'radius error', 'texture error', 'perimeter error', 'area error', 'smoothness error',
'compactness error', 'concavity error', 'concave points error', 'symmetry error', 'fractal dimension
error', 'worst radius', 'worst texture', 'worst perimeter', 'worst area', 'worst smoothness', 'worst
compactness', 'worst concavity', 'worst concave points', 'worst symmetry', 'worst fractal
dimension']
Q2. Data Preprocessing Perform basic preprocessing steps: Handle missing values (if any). Encode
categorical features using Label Encoding or One-Hot Encoding. Apply feature scaling if necessary
(optional for tree-based models). Explain why Decision Trees may or may not require feature scaling.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] =
[Link]
df =
[Link]([Link]())
scaler =
StandardScaler()
scaled = scaler.fit_transform([Link]("target",
axis=1)) scaled_df = [Link](scaled,
columns=[Link][:-1]) scaled_df["target"] =
df["target"]
print(scaled_df.head())
Output:
mean radius mean texture mean perimeter mean area mean smoothness \
0 1.097064 - 1.269934 1.568466
2.073335 0.984375
1 1.829821 - 1.685955 -0.826962
0.353632 1.908708
2 1.579888 0.456187 1.566503 1.558884 0.942210
3 -0.768909 0.253732 -0.592687 - 3.283553
0.764464
4 1.750297 - 1.776573 0.280372
1.151816 1.826229
mean fractal dimension ... worst texture worst perimeter worst area \
63
Activity Based Learning - 1SP22IC02
BIC703 6
0 2.255747 ... -1.359293 2.303601 2.001237
1 -0.868652 ... -0.369203 1.535126 1.890489
2 -0.398008 ... -0.023974 1.347475 1.456285
3 4.910919 ... 0.133984 -0.249939 -0.550021
4 -0.562450 ... -1.466770 1.338539 1.220724
64
Activity Based Learning - 1SP22IC02
BIC703 6
[5 rows x 31 columns]
Q3. Train-Test Split Split your dataset into training and testing sets (e.g., 80% train, 20% test). Print the
shapes of the resulting datasets. Explain the importance of separating training and testing data.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] =
[Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
Output:
(455, 30)
(114, 30)
(455,)
(114,)
Q4. Build a Basic Decision Tree Model Import and train a DecisionTreeClassifier or
DecisionTreeRegressor from scikit learn. Display model parameters (e.g., max_depth, criterion,
min_samples_split). Evaluate the model’s performance on training and testing sets using appropriate
metrics: o For classification: Accuracy, Precision, Recall, F1-score. o For regression: R² score, RMSE.
Comment on whether the model shows signs of overfitting or underfitting.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] =
[Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model = DecisionTreeClassifier(max_depth=None,
criterion='gini', min_samples_split=2) [Link](x_train, y_train)
train_pred =
[Link](x_train)
test_pred =
[Link](x_test)
print("Train Accuracy:", accuracy_score(y_train,
train_pred)) print("Test Accuracy:",
accuracy_score(y_test, test_pred)) print("Precision:",
precision_score(y_test, test_pred)) print("Recall:",
recall_score(y_test, test_pred))
print("F1 Score:", f1_score(y_test, test_pred))
Output:
65
Activity Based Learning - 1SP22IC02
BIC703 6
Recall : 0.9436619718309859
F1 Score : 0.9436619718309859
66
Activity Based Learning - 1SP22IC02
BIC703 6
Q5. Visualize the Decision Tree Plot the Decision Tree using plot_tree() or export_graphviz(). Label the
nodes with feature names and class labels. Interpret the structure: o Which features appear near the root
of the tree? o What does this imply about their importance?
data = load_breast_cancer()
df = [Link]([Link],
columns=list(data.feature_names)) df["target"] =
[Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model = DecisionTreeClassifier()
[Link](x_train, y_train)
[Link](figsize=(15,8))
plot_tree(model, feature_names=list([Link]), class_names=["Benign","Malignant"],
filled=True) [Link]()
output:
Q6. Model Complexity and Pruning Experiment with different values of max_depth (e.g., 3, 5, 7,
10). Observe and record how accuracy or R² changes with depth. Plot model performance vs.
tree depth. Explain how pruning helps control overfitting in Decision Trees.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] = [Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) depths = [3, 5, 7, 10]
scores = []
for d in depths:
model = DecisionTreeClassifier(max_depth=d)
[Link](x_train, y_train)
pred = [Link](x_test)
[Link](accuracy_score(y_test, pred))
[Link](depths, scores, marker='o',color='orange')
[Link]("Tree Depth")
[Link]("Accuracy")
[Link]("Decision Tree Performance vs
Depth") [Link]()
Output:
67
Activity Based Learning - 1SP22IC02
BIC703 6
Q7. Feature Importance Analysis Extract and display the feature importance scores from your trained model.
Visualize feature importance using a bar chart. Discuss which features contribute most to predictions
and why.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] = [Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model = DecisionTreeClassifier()
[Link](x_train, y_train)
importance =
model.feature_importances_
[Link](figsize=(10,6))
[Link]([Link], importance ,
color='r') [Link]("Feature
Importance Score")
[Link]("Features")
[Link]("Decision Tree Feature Importance")
[Link]()
output:
Q8. Compare Different Splitting Criteria Train multiple Decision Tree models using different criteria: o
For classification: gini vs. entropy. o For regression: squared_error vs. absolute_error. Compare
model performance for each criterion. Explain how the choice of criterion affects tree structure and
results.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] = [Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) criteria = ["gini", "entropy"]
results = {}
for c in criteria:
model = DecisionTreeClassifier(criterion=c)
[Link](x_train, y_train)
pred = [Link](x_test)
results[c] = accuracy_score(y_test,
pred) print(results)
Output:
68
Activity Based Learning - 1SP22IC02
BIC703 6
QG. Model Evaluation and Cross-Validation Perform k-fold cross-validation (e.g., k=5) to evaluate model
stability. Compare cross-validation accuracy with single train-test accuracy. Discuss what cross-
validation reveals about your model’s generalization capability.
data = load_breast_cancer()
df = [Link]([Link],
columns=data.feature_names) df["target"] = [Link]
X = [Link]("target",
axis=1) y = df["target"]
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) model = DecisionTreeClassifier()
[Link](x_train, y_train)
test_pred =
[Link](x_test)
print("Train-Test Accuracy:", accuracy_score(y_test,
test_pred)) cv_scores = cross_val_score(model, X, y,
cv=5)
print("Cross-Validation Accuracy:",
cv_scores) print("Mean CV Accuracy:",
cv_scores.mean())
Output:
Q1. Load Dataset Load at least one dataset for regression and one for classification (e.g., California
Housing, Iris). Display first 5 rows, shape, column names, and data types. Identify target (dependent)
and input (independent) features.
import pandas as pd
from [Link] import load_wine,
fetch_openml from [Link] import
load_diabetes
reg = load_diabetes()
reg_df = [Link]([Link], columns=reg.feature_names)
reg_df["disease_progression"] = [Link]
reg_df = reg_df.head(1000)
print(reg_df.head())
print(reg_df.shape)
print(reg_df.columns)
print(reg_df.dtypes)
reg_target = "disease_progression"
reg_features = reg_df.columns[:-
1] print(reg_target)
print(list(reg_features))
cls = load_wine()
cls_df = [Link]([Link], columns=cls.feature_names)
cls_df["wine_class"] = [Link]
cls_df = [Link]([cls_df]*50).head(1000)
print(cls_df.head())
print(cls_df.shape)
print(cls_df.columns)
print(cls_df.dtypes)
cls_target =
"wine_class"
cls_features = cls_df.columns[:-1]
print(cls_target)
print(list(cls_features))
Output:
70
Activity Based Learning - 1SP22IC02
BIC703 6
s4 s5 s6 disease_progression
0 -0.002592 0.019907 - 151.0
0.017646
1 -0.039493 -0.068332 - 75.0
0.092204
2 -0.002592 0.002861 - 141.0
0.025930
3 0.034309 0.022688 - 206.0
0.009362
4 -0.002592 -0.031988 - 135.0
0.046641
(442, 11)
Index(['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4',
's5', 's6', 'disease_progression'],
dtype='object'
) age
float64
sex float64
bmi float64
bp float64
s1 float64
s2 float64
s3 float64
s4 float64
s5 float64
s6 float64
disease_progression
float64 dtype: object
disease_progression
['age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']
Q2. Explore Dataset Check for missing values and duplicates. Display statistical summaries (.describe())
and class distributions. Visualize numerical and categorical features.
import pandas as pd
from [Link] import load_diabetes,
load_wine import [Link] as plt
reg = load_diabetes()
reg_df = [Link]([Link],
columns=reg.feature_names) reg_df["target"] = [Link]
reg_df =
[Link]([reg_df]*20).head(1000) cls =
load_wine()
cls_df = [Link]([Link],
columns=cls.feature_names) cls_df["class"] = [Link]
cls_df =
[Link]([cls_df]*50).head(1000)
print(reg_df.isnull().sum())
print(reg_df.duplicated().sum())
print(cls_df.isnull().sum())
print(cls_df.duplicated().sum())
print(reg_df.describe())
print(cls_df.describe())
print(cls_df["class"].value_counts())
reg_df.hist(figsize=(10,8))
[Link]()
cls_df.hist(figsize=(10,8))
[Link]()
cls_df["class"].value_counts().plot(kind="
bar") [Link]()
Output:
age 0
sex 0
bmi 0
bp 0
s1 0
s2 0
s3 0
s4 0
71
Activity Based Learning - 1SP22IC02
BIC703 0
s5
6
s6 0
target 0
dtype: int64
72
Activity Based Learning - 1SP22IC02
BIC703 6
558
alcohol 0
malic_acid 0
ash 0
alcalinity_of_ash 0
magnesium 0
total_phenols 0
flavanoids 0
nonflavanoid_phenols 0
proanthocyanins 0
color_intensity 0
hue 0
od280/od315_of_diluted_wines0
proline 0
class 0
dtype: int64
822
age sex bmi bp s1 \
count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000
mean -0.001007 -0.000412 -0.000850 -0.001157 -0.001078
std 0.047884 0.047561 0.047073 0.047372 0.047173
min -0.107226 -0.044642 -0.090275 -0.112399 -0.126781
25% -0.038207 -0.044642 -0.035307 -0.036656 -0.034592
50% -0.044642 - - -
0.007284 0.005670 0.004321
0.005383
75% 0.050680 0.030440 0.03220 0.02732
1 6
0.038076
max 0.050680 0.17055 0.132044 0.15391
5 4
0.110727
s2 s3 s4 s5 s6 \
count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000
mean -0.001089 0.000897 -0.001317 -0.001195 -0.001169
std 0.047177 0.048045 0.047314 0.047396 0.047512
min -0.115613 -0.102307 -0.076395 -0.126097 -0.137767
25% -0.031376 -0.032356 -0.039493 -0.034522 -0.034215
50% -0.004602 -0.006584 -0.002592 -0.005142 -0.001078
75% 0.027496 0.030232 0.034309 0.031348 0.027917
max 0.198788 0.181179 0.185234 0.133597 0.135612
target
count 1000.000000
mean 150.504000
std 76.575988
min 25.000000
25% 85.750000
50% 139.000000
75% 206.000000
max 346.000000
alcohol malic_acid ash alcalinity_of_ash magnesium \
count 1000.000000 1000.000000 1000.00000 1000.000000 1000.000000
mean 13.012960 2.282030 2.36337 19.353800 99.925000
std 0.813528 1.088538 0.27538 3.334964 14.412741
min 11.030000 0.740000 1.36000 10.600000 70.000000
25% 12.360000 1.585000 17.000000
2.21000 88.000000
50% 13.050000 1.810000 19.000000
2.36000 98.000000
75% 13.695000 2.967500 21.500000
2.56000 108.000000
max 14.830000 5.800000 30.000000
3.23000 162.000000
73
Activity Based Learning - 1SP22IC02
BIC703
50% 2.410000 2.190000 0.320000 1.560000
6
75% 2.800000 2.900000 0.430000 1.970000
max 3.880000 5.080000 0.660000 3.580000
74
Activity Based Learning - 1SP22IC02
BIC703 6
proline class
count 1000.000000 1000.000000
mean 758.618000 0.886000
std 319.300264 0.762618
min 278.000000 0.000000
25% 502.000000 0.000000
50% 680.000000 1.000000
75% 1020.000000 1.000000
max 1680.000000 2.000000
class
1 406
0 354
2 240
Name: count, dtype: int64
Q3. Handle Missing Values Impute missing values using appropriate techniques (mean, median, mode, or
forward fill). Explain why imputation method was chosen.
import pandas as pd
from [Link] import load_diabetes,
load_wine reg = load_diabetes()
reg_df = [Link]([Link],
columns=reg.feature_names) reg_df["target"] = [Link]
reg_df =
[Link]([reg_df]*20).head(1000) cls
= load_wine()
cls_df = [Link]([Link],
columns=cls.feature_names) cls_df["class"] = [Link]
cls_df =
[Link]([cls_df]*50).head(1000)
reg_df.iloc[0:10, 0] = None
cls_df.iloc[0:10, 0] = None
reg_df = reg_df.fillna(reg_df.mean())
cls_df =
cls_df.fillna(cls_df.mode().iloc[0])
print(reg_df.head())
print(cls_df.head())
Output:
s4 s5 s6 target
0-0.002592 0.019907 -0.017646 151.0
1-0.039493 -0.068332 -0.092204 75.0
2-0.002592 0.002861 -0.025930 141.0
3 0.034309 0.022688 -0.009362 206.0
4-0.002592 -0.031988 -0.046641 135.0
alcohol malic_acid ash alcalinity_of_ash magnesium total_phenols \
0 12.37 1.71 2.43 15.6 127.0 2.80
1 12.37 1.78 2.14 11.2 100.0 2.65
2 12.37 2.36 2.67 18.6 101.0 2.80
3 12.37 1.95 2.50 16.8 113.0 3.85
4 12.37 2.59 2.87 21.0 118.0 2.80
od280/od315_of_diluted_wines proline
0 class
75
Activity Based Learning - 1SP22IC02
BIC703 3.92 1065.0 0 6
76
Activity Based Learning - 1SP22IC02
BIC703 6
1 3.40 1050.0 0
2 3.17 1185.0 0
3 3.45 1480.0 0
4 2.93 735.0 0
Q4. Encode Categorical Variables Encode categorical columns using Label Encoding or One-Hot Encoding.
Display the transformed dataset.
import pandas as pd
from [Link] import load_wine
from [Link] import
LabelEncoder cls = load_wine()
cls_df = [Link]([Link],
columns=cls.feature_names) cls_df["class"] = [Link]
cls_df =
[Link]([cls_df]*50).head(1000) label
= LabelEncoder()
cls_df["class"] = label.fit_transform(cls_df["class"])
print(cls_df.head())
Output:
od280/od315_of_diluted_wines proline
class
0 3.92 1065.0 0
1 3.40 1050.0 0
2 3.17 1185.0 0
3 3.45 1480.0 0
4 2.93 735.0 0
Q5. Feature Scaling and Normalization Apply StandardScaler or MinMaxScaler on numerical features.
Compare feature ranges before and after scaling. Explain why scaling is important for some algorithms.
import pandas as pd
from [Link] import load_wine
from [Link] import StandardScaler,
MinMaxScaler cls = load_wine()
df = [Link]([Link],
columns=cls.feature_names) df =
[Link]([df]*50).head(1000)
print("Before Scaling
(describe):")
print([Link]())
std_scaler = StandardScaler()
df_std = [Link](std_scaler.fit_transform(df),
columns=[Link]) print("\nAfter Standard Scaling (describe):")
print(df_std.describe())
mm_scaler =
MinMaxScaler()
df_mm = [Link](mm_scaler.fit_transform(df),
columns=[Link]) print("\nAfter MinMax Scaling (describe):")
print(df_mm.describe())
Output:
77
Activity Based Learning - 1SP22IC02
BIC703
alcohol malic_acid ash alcalinity_of_ash magnesium \
6
count 1000.000000 1000.000000 1000.00000 1000.000000 1000.000000
mean 13.012960 2.282030 2.36337 19.353800 99.925000
78
Activity Based Learning - 1SP22IC02
BIC703 6
3.193895e+00
1.000000e+03
mean 1.971756e-16 -2.106759e-15 - 3.192113e-15
2.330580e-15
std 1.000500e+00 1.000500e+00 1.000500e+0
1.000500e+00 0
min -2.077327e+00 -2.157791e+00 - -1.847026e+00
1.774678e+00
25% -8.278069e-01 -8.558449e-01 - -7.900957e-01
8.246308e-01
50% -1.336292e-01 1.407066e-01 -3.022819e-01
1.101342e-01
75% 5.605485e-01 7.675697e-01 5.920433e-01
8.334945e-01
max 4.309108e+00 2.503498e+00 2.461996e+0
3.054517e+00 0
79
Activity Based Learning - 1SP22IC02
BIC703
1.000500e+00 1.000500e+00 min -
6
2.110950e+00 -1.647890e+00 -
2.195919e+00 25% -6.321388e-01
-7.907706e-01 -7.206358e-01
50% -8.638720e-02 -1.734668e-01 1.064171e-01
75% 6.354133e-01 5.060115e-01
6.652366e-01 max 3.469801e+00
3.557002e+00 3.302865e+00
od280/od315_of_diluted_wines
proline count
1.000000e+03
1.000000e+03 mean
-2.184919e-15 -1.669775e-
16 std 1.000500e+00
1.000500e+00
min -1.984122e+00 -1.505976e+00
25% -8.624178e-01 -8.040908e-01
50% 2.449054e-01 -2.463429e-01
75% 7.769957e-01 8.190184e-01
max 1.941842e+00 2.887073e+00
80
Activity Based Learning - 1SP22IC02
BIC703 6
0.000000
25% 0.279310 0.245283 0.26498
0.196730 4
50% 0.493103 0.358491 0.36277
0.390295 6
75% 0.627586 0.566038 0.49211
0.540084 4
max 1.000000 1.000000 1.000000
1.000000
Q6. Train-Test Split Split datasets into training and testing sets (e.g., 80/20). Print the shapes of all
datasets. Explain the importance of splitting data.
import pandas as pd
from [Link] import load_wine
from sklearn.model_selection import
train_test_split cls = load_wine()
df = [Link]([Link],
columns=cls.feature_names) df['target'] =
[Link]
X = [Link]('target',
axis=1) y = df['target']
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42) print("X_train shape:", x_train.shape)
print("X_test shape:",
x_test.shape) print("y_train
shape:", y_train.shape)
print("y_test shape:",
y_test.shape)
output:
82
Activity Based Learning - 1SP22IC02
BIC703 6
[Link]("Actual Values")
[Link]("Predicted Values")
[Link]("Predicted vs Actual Values (Simple Linear
Regression)") [Link]()
Output:
Coefficient: 95.54565905592783
Intercept :
5.705090115082966 R²
Score :
0.5603587090211857 RMSE
:
85.31317062878274
Q8. Multiple Linear Regression Train multiple linear regression using all features. Evaluate performance
on training and testing data. Compare results with simple linear regression.
Output:
83
Activity Based Learning - 1SP22IC02
BIC703 6
QG. Logistic Regression (Classification) Train a logistic regression classifier. Evaluate using accuracy,
confusion matrix, and classification report. Plot ROC curve and calculate AUC.
84
Activity Based Learning - 1SP22IC02
BIC703 6
Output:
0.925
[[88 6]
[ 9 97]]
precision recall f1-score support
0.9774187073464472
Q10. K-Nearest Neighbors (KNN) Train KNN classifier/regressor. Experiment with different values of k
and distance metrics. Evaluate using accuracy (classification) or RMSE (regression). Discuss effect of
k on model performance.
Output:
85
Activity Based Learning - 1SP22IC02
BIC703 6
Q11. Decision Tree Models Train Decision Tree classifier/regressor. Evaluate performance on training
and test sets. Visualize tree and feature importance. Discuss overfitting and how to prevent it.
output:
86
Activity Based Learning - 1SP22IC02
BIC703 6
Q12. Random Forest Models Train a Random Forest classifier/regressor. Evaluate performance and
compare with Decision Tree. Plot feature importances. Explain why ensemble models often perform
better than a single tree.
Output:
Q13. Support Vector Machine (SVM) Train SVM classifier on the classification dataset. Experiment with
different kernels (linear, rbf). Evaluate performance using accuracy and confusion matrix.
87
Activity Based Learning - 1SP22IC02
BIC703
Output:
6
88
Activity Based Learning - 1SP22IC02
BIC703 6
Q14. Model Evaluation s Cross-Validation Perform k-fold cross-validation (e.g., k=5) for at least two
supervised models. Compare cross-validation scores with single train-test split results. Discuss model
stability and generalization.
output:
Q15. K-Means Clustering Apply K-Means clustering on an unlabeled dataset. Experiment with different
values of k. Visualize clusters using 2D scatter plot (use PCA if features >2). Evaluate using silhouette
score.
89
Activity Based Learning - 1SP22IC02
BIC703
best_k = max(results, key=[Link])
6
print(f"\nBest number of clusters: k =
{best_k}")
90
Activity Based Learning - 1SP22IC02
BIC703 6
output:
Q16. Hierarchical Clustering Perform hierarchical clustering on a dataset. Plot dendrogram. Discuss the
choice of number of clusters.
91
Activity Based Learning - 1SP22IC02
BIC703 6
Q17. DBSCAN Clustering ∙ Apply DBSCAN clustering. ∙ Visualize resulting clusters. ∙ Compare DBSCAN with
K-Means on the same dataset.
X, _ = make_moons(n_samples=600, noise=0.08,
random_state=42) scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
dbscan = DBSCAN(eps=0.25,
min_samples=5) db_labels =
dbscan.fit_predict(X_scaled) [Link]()
[Link](X_scaled[:,0], X_scaled[:,1],
c=db_labels) [Link]("DBSCAN Clusters")
[Link]("Feature 1")
[Link]("Feature 2")
[Link]()
kmeans = KMeans(n_clusters=2, random_state=42,
n_init=5) km_labels = kmeans.fit_predict(X_scaled)
[Link]()
[Link](X_scaled[:,0], X_scaled[:,1],
c=km_labels) [Link]("K-Means Clusters")
[Link]("Feature 1")
[Link]("Feature 2")
[Link]()
output:
Q18. Principal Component Analysis (PCA) Apply PCA to reduce high-dimensional dataset to 2 or 3
dimensions. Visualize the reduced dataset using scatter plot. Discuss how PCA helps in dimensionality
reduction and visualization.
data = load_wine()
X=
[Link] y
=
[Link]
scaler = StandardScaler()
X_scaled =
scaler.fit_transform(X) pca =
PCA(n_components=2)
X_pca =
pca.fit_transform(X_scaled)
[Link](figsize=(8,6))
scatter = [Link](X_pca[:,0],
X_pca[:,1], c=y) [Link]("PCA (2D)
Projection") [Link]("PC1")
[Link]("PC2")
[Link](*scatter.legend_elements(),
title="Classes") [Link]()
Output:
92
Activity Based Learning - 1SP22IC02
BIC703 6
Q1G. t-SNE for Visualization Apply t-SNE for high-dimensional data visualization. Visualize in 2D or 3D
plot. Compare PCA and t-SNE visualization effectiveness.
data = load_wine()
X=
[Link] y
=
[Link]
scaler = StandardScaler()
X_scaled =
scaler.fit_transform(X) pca =
PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
[Link](figsize=(7,5))
scatter = [Link](X_pca[:,0], X_pca[:,1],
c=y) [Link]("PCA (2D) Visualization")
[Link]("PC1")
[Link]("PC2")
[Link](*scatter.legend_elements(),
title="Classes") [Link]()
tsne = TSNE(n_components=2, perplexity=30, learning_rate=200,
random_state=42) X_tsne = tsne.fit_transform(X_scaled)
[Link](figsize=(7,5))
scatter = [Link](X_tsne[:,0],
X_tsne[:,1], c=y) [Link]("t-SNE (2D)
Visualization") [Link]("Dimension 1")
[Link]("Dimension 2")
[Link](*scatter.legend_elements(),
title="Classes") [Link]()
Output:
93
Activity Based Learning - 1SP22IC02
BIC703 6
94
Activity Based Learning - 1SP22IC02
BIC703 6
6. Final Conclusion
● No single model is best for every task.
● Supervised models excel when labeled data is available.
● Unsupervised models reveal hidden patterns where labels are unknown.
● PCA and t-SNE are essential when visualizing high-dimensional data.
● Real-world choice depends on:
o dataset size
o data type
o interpretability needs
o computational resources
95