0% found this document useful (0 votes)
2 views19 pages

ML Lab Programs Final

The document outlines a series of machine learning lab programs, detailing the installation and setup of Python, scikit-learn, and essential libraries, followed by practical coding exercises. Each program includes steps for data manipulation, visualization, handling missing data, and implementing machine learning models like k-NN and linear regression. The document serves as a comprehensive guide for beginners to learn and apply machine learning techniques using Python.

Uploaded by

danish.sec.dev
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

ML Lab Programs Final

The document outlines a series of machine learning lab programs, detailing the installation and setup of Python, scikit-learn, and essential libraries, followed by practical coding exercises. Each program includes steps for data manipulation, visualization, handling missing data, and implementing machine learning models like k-NN and linear regression. The document serves as a comprehensive guide for beginners to learn and apply machine learning techniques using Python.

Uploaded by

danish.sec.dev
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ML Lab Programs

Complete Lab Examination — Programs 1 to 10

All programs verified and corrected


Program 1
Install and set up Python and essential libraries like NumPy and pandas

Step 1 — Install Python


Download: Go to [Link], navigate to "Downloads" and download the latest version for Windows.
Choose the executable installer.
Install: Execute the downloaded file. Check "Add Python 3.x to PATH" at the start. Select "Customize
installation" and ensure all options including "pip" are selected. In "Advanced Options", choose "Install
for all users" and set path to C:\Python. Click "Install".

Step 2 — Install PIP


PIP comes with Python 3.4+. Confirm with: pip --version
To install or upgrade: python -m ensurepip --upgrade
To verify: python -m pip --version

Step 3 — Workspace Creation


Create a dedicated directory for ML projects:
CMD

C:\> mkdir C:\ML_Projects


C:\> cd C:\ML_Projects

Step 4 — Creating a Virtual Environment


Work in an isolated environment to manage dependencies and avoid conflicts:
CMD

C:\> pip install virtualenv # Install virtualenv


C:\> virtualenv ml_env # Create virtual environment
C:\> ml_env\Scripts\activate # Activate the environment
# To exit: deactivate

Step 5 — Installing Necessary Tools


Install Jupyter, NumPy, pandas, Matplotlib, and Scikit-Learn:
CMD

(ml_env) C:\> python -m pip install --upgrade pip


(ml_env) C:\> pip install matplotlib numpy pandas scikit-learn
Program 2
Introduce scikit-learn as a machine learning library

Overview
Scikit-learn is a popular open-source machine learning library in Python that offers a comprehensive set
of tools and algorithms for data analysis, modeling, and machine learning tasks. It is built on foundational
libraries like NumPy, SciPy, and Matplotlib.

Key Features
1. Comprehensive ML Library: Offers algorithms for classification, regression, clustering,
dimensionality reduction, and more.
2. User-Friendly and Easy to Use: Simple syntax and user-friendly interface accessible for
beginners and experienced practitioners.
3. Integration with Scientific Libraries: Integrates with NumPy, SciPy, and Matplotlib for a
powerful ML environment.
4. Extensive Documentation & Community Support: Comprehensive tutorials, examples, and a
vibrant community for support.
5. Efficient Algorithm Implementation: Built on NumPy, SciPy, and Cython for efficient
implementation and scalability to large datasets.
6. Model Evaluation & Validation: Tools for cross-validation, hyperparameter tuning, and
performance metrics.
7. Flexibility & Customization: Allows parameter tuning and adaptation of algorithms to specific
datasets.
8. Wide Adoption & Industry Usage: Widely used in academia, research, and industry due to its
ease of use and versatility.
Program 3
Install and set up scikit-learn and other necessary tools

Same as Program 1. Follow all 5 steps from Program 1 — the same setup installs scikit-learn along with
other necessary tools (NumPy, pandas, Matplotlib) via pip.
Program 4
Write a program to Load and explore the dataset of CSV and Excel files using pandas

Step 1 — Create Sample Data Files


CSV File — save as sample_data.csv
CSV

Name,Age,Score
Srikanth,28,85
Snigdha,22,78
Mary,31,92

Excel File — save as sample_data.xlsx

Name Course Sem

Rajesh BCA 1

Ramesh BCA 2

Swati BCOM 1

Florina BCOM 3

Pooja BBA 2

Raghu BBA 4

Step 2 — Python Code


PYTHON
import pandas as pd

# Define the file paths


csv_file_path = 'C:\\Users\\danis\\OneDrive\\Desktop\\sample_data.csv'
excel_file_path = 'C:\\Users\\danis\\OneDrive\\Desktop\\sample_data.xlsx'

# Load the CSV file


data_csv = pd.read_csv(csv_file_path)
print("CSV File Data:")
print(data_csv)

# Load the Excel file


data_excel = pd.read_excel(excel_file_path)
print("\nExcel File Data:")
print(data_excel)

# Basic Data Exploration


print("\nData Descriptions:")
print("CSV Data Description:")
print(data_csv.describe())

print("\nExcel Data Description:")


print(data_excel.describe())

# Displaying data types


print("\nData Types in CSV File:")
print(data_csv.dtypes)

print("\nData Types in Excel File:")


print(data_excel.dtypes)

OUTPUT
CSV File Data:
Name Age Score
0 Srikanth 28 85
1 Snigdha 22 78
2 Mary 31 92

Excel File Data:


Name Course Sem
0 Rajesh BCA 1
1 Ramesh BCA 2
2 Swati BCOM 1
3 Florina BCOM 3
4 Pooja BBA 2
5 Raghu BBA 4

CSV Data Description:


Age Score
count 3.000000 3.000000
mean 27.000000 85.000000
std 4.582576 7.000000
min 22.000000 78.000000
25% 25.000000 81.500000
50% 28.000000 85.000000
75% 29.500000 88.500000
max 31.000000 92.000000

Data Types in CSV File:


Name object
Age int64
Score int64

Data Types in Excel File:


Name object
Course object
Sem int64

Explanation
1. Importing pandas: The script begins by importing the pandas library, essential for data
manipulation and analysis.
2. Loading Data: pd.read_csv() loads CSV data; pd.read_excel() loads Excel data.
3. Printing Data: Both datasets are printed to verify they are read correctly.
4. Data Exploration: .describe() provides statistical summary: count, mean, std, min, max, and
percentiles.
5. Data Types: .dtypes prints each column's data type to identify potential type mismatches.
Program 5
Write a program to Visualize the dataset using Matplotlib by plotting scatter plots, bar charts

Step 1 — Create study_data.csv


CSV

Student ID,Study Hours,Exam Score


1,5,82
2,2,48
3,8,90
4,1,35
5,3,50
6,4,66
7,9,95
8,6,75
9,7,88
10,0.5,30
11,10,96
12,0,20
13,12,98

Step 2 — Python Code


PYTHON

import pandas as pd
import [Link] as plt

# Load the data


data = pd.read_csv('C:\\Users\\danis\\OneDrive\\Desktop\\study_data.csv')

# Scatter plot of Study Hours vs. Exam Scores


[Link](figsize=(14, 7))
[Link](1, 2, 1) # 1 row, 2 columns, 1st subplot
[Link](data['Study Hours'], data['Exam Score'],
color='dodgerblue', edgecolor='k', alpha=0.7)
[Link]('Study Hours vs. Exam Scores')
[Link]('Study Hours')
[Link]('Exam Scores')
[Link](True)

# Bar chart of Average Exam Score by Study Hour Range


bins = [0, 2, 4, 6, 8, 10, 13] # 13 not 12 to include 12 hours
labels = ['0-2', '2-4', '4-6', '6-8', '8-10', '10-12']
data['Study Hour Range'] = [Link](data['Study Hours'],
bins=bins, labels=labels, right=False)
grouped_data = [Link]('Study Hour Range')['Exam Score'].mean()

[Link](1, 2, 2) # 1 row, 2 columns, 2nd subplot


grouped_data.plot(kind='bar', color='salmon')
[Link]('Average Exam Score by Study Hour Range')
[Link]('Study Hour Range')
[Link]('Average Exam Score')
[Link](rotation=0)

plt.tight_layout()
[Link]()

Explanation
1. Data Loading: pandas loads the CSV file containing students' study hours and exam scores.
2. Scatter Plot: Matplotlib plots 'Study Hours' against 'Exam Scores' to visually explore the
relationship.
3. Bar Chart Setup: Data is binned using [Link](). Last bin boundary is 13 (not 12) so that value
12 is included when using right=False.
4. Visualization Config: Both plots sit in one figure using [Link]() with clear titles, labels,
and side-by-side layout.
5. Display: [Link]() renders both plots showing how study time correlates with academic
performance.
Program 6
Write a program to Handle missing data, encode categorical variables, and perform feature
scaling
PYTHON

import pandas as pd
from [Link] import SimpleImputer
from [Link] import OneHotEncoder, StandardScaler

# Create dummy data


data = {
'Age': [25, 30, None, 28, 35],
'Gender': ['Female', 'Male', 'Male', 'Female', 'Male'],
'Income': [50000, 60000, 45000, None, 70000]
}
df = [Link](data)

# Handling missing data (fill with mean)


imputer = SimpleImputer(strategy='mean')
df[['Age', 'Income']] = imputer.fit_transform(df[['Age', 'Income']])

print("Data after handling missing values:")


print(df)

# Encoding categorical variables


encoder = OneHotEncoder()
encoded_data = encoder.fit_transform(df[['Gender']]).toarray()
encoded_df = [Link](encoded_data,
columns=encoder.get_feature_names_out(['Gender']))
print("\nData after categorical encoding:")
print(encoded_df)

# Feature scaling
scaler = StandardScaler()
scaled_data = scaler.fit_transform(df[['Age', 'Income']])
scaled_df = [Link](scaled_data, columns=['Scaled Age', 'Scaled Income'])
print("\nData after feature scaling:")
print(scaled_df)

OUTPUT
Data after handling missing values:
Age Gender Income
0 25.0 Female 50000.0
1 30.0 Male 60000.0
2 29.5 Male 45000.0
3 28.0 Female 56250.0
4 35.0 Male 70000.0

Data after categorical encoding:


Gender_Female Gender_Male
0 1.0 0.0
1 0.0 1.0
2 0.0 1.0
3 1.0 0.0
4 0.0 1.0

Data after feature scaling:


Scaled Age Scaled Income
0 -1.289648 -0.679366
1 0.143294 0.407620
2 0.000000 -1.222859
3 -0.429883 0.000000
4 1.576237 1.494605

Explanation
1. Data Preparation: A dummy dataset with 'Age', 'Gender', and 'Income' columns is created using
pandas.
2. Handling Missing Data: SimpleImputer(strategy='mean') fills missing values in 'Age' and
'Income' with the column mean.
3. Categorical Encoding: OneHotEncoder converts 'Gender' into one-hot encoded numerical
format suitable for ML algorithms.
4. Feature Names: get_feature_names_out() retrieves the encoded column names for clear
DataFrame creation.
5. Feature Scaling: StandardScaler standardizes 'Age' and 'Income' to mean=0 and std=1,
improving performance of many ML algorithms.
Program 7
Write a program to implement a k-Nearest Neighbours (k-NN) classifier using scikit-learn
and Train the classifier on the dataset and evaluate its performance
PYTHON

import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import accuracy_score

# Dummy student data: exam score 1, exam score 2, pass/fail


X = [Link]([[80, 75], [95, 90], [60, 50], [45, 30],
[30, 40], [85, 95], [70, 60], [50, 55],
[40, 45], [60, 70]])
y = [Link]([1, 1, 0, 0, 0, 1, 1, 0, 0, 1]) # Binary pass/fail labels

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)

# Initialize k-NN classifier with k=3


knn = KNeighborsClassifier(n_neighbors=3)

# Train the classifier


[Link](X_train, y_train)

# Evaluate classifier performance


y_pred = [Link](X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy on the test set: {:.2f}".format(accuracy))

# Take user input for exam scores


exam_score1 = float(input("Enter Exam Score 1: "))
exam_score2 = float(input("Enter Exam Score 2: "))

# Prepare user input for prediction


user_input = [Link]([[exam_score1, exam_score2]])

# Predict outcome using trained k-NN classifier


predicted_outcome = [Link](user_input)

if predicted_outcome[0] == 1:
print("Based on the exam scores provided, the student is predicted to pass.")
else:
print("Based on the exam scores provided, the student is predicted to fail.")

Sample Outputs
OUTPUT

Output 1:
Accuracy on the test set: 1.00
Enter Exam Score 1: 45
Enter Exam Score 2: 50
Based on the exam scores provided, the student is predicted to fail.

Output 2:
Accuracy on the test set: 1.00
Enter Exam Score 1: 75
Enter Exam Score 2: 89
Based on the exam scores provided, the student is predicted to pass.
Explanation
1. Data Preparation: NumPy array X holds exam scores as features; y holds binary pass/fail labels.
2. Model Training: Data is split 80/20 using train_test_split. A KNN classifier with
n_neighbors=3 is trained on (X_train, y_train).
3. Evaluation: Accuracy is computed by predicting on X_test and comparing against y_test using
accuracy_score.
4. User Interaction: User inputs two exam scores; these are formatted as a NumPy array for
prediction.
5. Prediction & Output: The trained KNN predicts pass or fail and prints the result.
Program 8
Write a program to implement a linear regression model for regression tasks and Train the
model on a dataset with continuous target variables
PYTHON

import numpy as np
from sklearn.linear_model import LinearRegression

# Dummy house price data


# Features: [house size (sqft), number of bedrooms]
# Target: house price
X = [Link]([[1000, 2], [1500, 3], [1200, 2],
[1800, 4], [900, 2], [2000, 3]])
y = [Link]([300000, 400000, 350000, 500000, 280000, 450000])

# Initialize the Linear Regression model


model = LinearRegression()

# Train the model on the dataset


[Link](X, y)

# Take input from user for new house data


size = float(input("Enter the size of the house in sqft: "))
bedrooms = int(input("Enter the number of bedrooms: "))
new_data = [Link]([[size, bedrooms]])

# Predict the price for the new house


predicted_price = [Link](new_data)

# Print the predicted price


print("Predicted price for a house with size {} sqft"
" and {} bedrooms: Rs.{:.2f}".format(size, bedrooms, predicted_price[0]))

OUTPUT

Enter the size of the house in sqft: 1600


Enter the number of bedrooms: 3
Predicted price for a house with size 1600.0 sqft and 3 bedrooms: Rs.418163.93

Explanation
1. Model Training: A Linear Regression model is initialized and trained on dummy house price data
with features (house size, bedrooms) and target (price).
2. User Input: The program prompts the user for house size (sqft) and number of bedrooms,
converting them to a NumPy array matching the model's expected format.
3. Prediction: The trained model's predict() method returns the estimated price for the input
house.
4. Output: The predicted price is printed in a formatted string showing size, bedrooms, and price.
Program 9
Write a program to implement a decision tree classifier using scikit-learn and visualize the
decision tree and understand its splits
PYTHON

import numpy as np
from [Link] import DecisionTreeClassifier, plot_tree, export_text
import [Link] as plt

# Custom dummy data for fruit classification


# Features: [Weight, Texture] -> Target: [Fruit Type]
X = [Link]([[150, 0], [170, 1], [120, 0],
[140, 1], [200, 1], [130, 0]])
y = [Link](['Apple', 'Orange', 'Apple',
'Orange', 'Melon', 'Apple'])

# Initialize and train Decision Tree Classifier


clf = DecisionTreeClassifier(random_state=42)
[Link](X, y)

# Visualize text-based decision rules


tree_rules = export_text(clf, feature_names=['Weight', 'Texture'])
print("Decision Tree Classifier Rules:\n", tree_rules)

# Plot the Decision Tree


[Link](figsize=(10, 6))
plot_tree(clf,
filled=True,
feature_names=['Weight', 'Texture'],
class_names=[Link](y))
[Link]()

Output — Decision Tree Rules


OUTPUT

Decision Tree Classifier Rules:


|--- Texture <= 0.50
| |--- class: Apple
|--- Texture > 0.50
| |--- Weight <= 185.00
| | |--- class: Orange
| |--- Weight > 185.00
| | |--- class: Melon

Explanation
1. Data Preparation: A dummy fruit classification dataset is defined with 'Weight' and 'Texture' as
features and Fruit Type as the target.
2. Classifier Initialization: DecisionTreeClassifier(random_state=42) ensures reproducibility;
the classifier is trained via fit().
3. Text Visualization: export_text() generates human-readable decision rules showing how the
tree splits on features.
4. Graphical Plot: plot_tree() renders the full tree visually with filled color nodes, feature names,
and class labels.
5. Display: [Link]() renders the tree structure allowing visual understanding of each decision
split.
Program 10
Write a program to Implement K-Means clustering and Visualize clusters
PYTHON

import numpy as np
import [Link] as plt
from [Link] import KMeans

# Generate dummy customer data (Age, Income)


X = [Link]([
[30, 50000], [35, 60000], [40, 80000],
[25, 30000], [45, 100000], [20, 20000],
[50, 120000], [55, 150000], [60, 140000],
[28, 40000]
])

# Initialize K-Means with 3 clusters


kmeans = KMeans(n_clusters=3, random_state=0, n_init=10)
[Link](X)

# Get cluster labels and cluster centers


labels = kmeans.labels_
centers = kmeans.cluster_centers_

# Visualize the clusters


[Link](figsize=(8, 6))
[Link](X[:, 0], X[:, 1],
c=labels, cmap='viridis', s=50, alpha=0.8)
[Link](centers[:, 0], centers[:, 1],
c='red', s=200, marker='X', label='Centroids')
[Link]('Age')
[Link]('Income')
[Link]('K-Means Clustering of Customers')
[Link]()
[Link]()

Explanation
1. Dummy Data Generation: Customer data with 'Age' and 'Income' features is created as a
NumPy array representing 10 customers.
2. K-Means Clustering: KMeans(n_clusters=3, n_init=10) creates 3 clusters. The n_init=10
parameter explicitly sets the number of initializations to avoid deprecation warnings.
3. Labels & Centers: kmeans.labels_ gives each point's cluster assignment;
kmeans.cluster_centers_ gives the centroid coordinates.
4. Visualization: A scatter plot shows all customers colored by cluster, with centroids marked as
large red "X" markers for easy identification.
5. Plot Interpretation: The chart shows how customers group by Age and Income. Centroids
represent the average Age and Income of each customer segment.
How to Run These Programs (CMD + Notepad)
1. Save the code
Open Notepad, paste the code, and save as [Link] on your Desktop (e.g., [Link], [Link], etc.)

2. Open CMD
Press Win+R, type cmd, press Enter.

3. Run the program


CMD

python C:\Users\danis\OneDrive\Desktop\[Link]

4. Install missing libraries (if needed)


CMD

pip install pandas numpy matplotlib scikit-learn openpyxl

5. For programs needing CSV files (4, 5)


Create the CSV in Notepad and save it to your Desktop. Make sure the file path in the code matches
where you saved it.
Summary of Corrections from Original
1. All Programs — File paths: Updated to use C:\\Users\\danis\\OneDrive\\Desktop\\ paths
that work on your system via CMD.

2. Program 5 — [Link]() bin boundary bug (FIXED): Changed last bin from 12 to 13. With
right=False, the bin [10, 12) excludes the student with 12 study hours. Using [10, 13) includes it.

3. Program 6 — Output values (CORRECTED): The StandardScaler output now shows actual
computed values instead of the slightly-off rounded ones in the original.

4. Program 10 — n_init parameter (ADDED): Added n_init=10 to KMeans to suppress


FutureWarning in scikit-learn 1.4+.

5. Programs 1–4, 7–9 — No logic changes: Code was already correct. Only file paths updated for
your system.

You might also like