ML Code Output
ML Code Output
To create NumPy arrays using list, tuple, and dictionary, create a 2D array of order
3×4, and apply indexing on 1D and 2D arrays.
1
(c) Apply Indexing in NumPy 1D and 2D Array
Indexing in 1D Array
arr_1d = [Link]([100, 200, 300, 400, 500])
Indexing in 2D Array
print("2D Array:")
print(arr_2d)
Output (Sample)
NumPy array from list: [10 20 30 40 50]
NumPy array from tuple: [1 2 3 4 5]
NumPy array from dictionary keys: [1 2 3]
2
Experiment 2: WAP to implement Numpy Commands
Exp 2 a. Apply slicing in numpy 1D and 2D array
b. Apply type conversion of numpy arrays
c. c. Create copy and view of numpy array
To apply slicing in NumPy 1D and 2D arrays, perform type conversion of NumPy arrays, and
create copy and view of NumPy arrays.
Slicing in 2D Array
arr_2d = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print("Original 2D Array:")
print(arr_2d)
3
(c) Create Copy and View of NumPy Array
original = [Link]([100, 200, 300, 400])
# View
view_arr = [Link]()
view_arr[0] = 999
# Copy
copy_arr = [Link]()
copy_arr[1] = 888
Output (Sample)
Original 1D Array: [10 20 30 40 50 60]
Slicing from index 1 to 4: [20 30 40 50]
Original 2D Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
4
Experiment 3: WAP to implement Numpy Commands
To apply reshaping and flattening, perform iteration on NumPy arrays, and implement joining
and splitting of NumPy arrays.
reshaped_arr = [Link](2, 3)
print("Original Array:", arr)
print("Reshaped Array (2x3):")
print(reshaped_arr)
print("Iterating 1D Array:")
for element in arr_1d:
print(element)
print("Iterating 2D Array:")
for row in arr_2d:
for item in row:
print(item)
5
(c) Apply Joining and Splitting NumPy Arrays
Joining NumPy Arrays
Using concatenate()
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
split_arr = np.array_split(arr, 3)
print("Split 1D Array:", split_arr)
SpliṄng 2D Array
arr_2d = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8]])
split_2d = [Link](arr_2d, 2)
print("Split 2D Array:")
print(split_2d)
Output (Sample)
Original Array: [1 2 3 4 5 6]
Reshaped Array:
[[1 2 3]
[4 5 6]]
Flattened Array: [1 2 3 4 5 6]
Iterating 1D Array:
10
20
30
40
Joined Array: [1 2 3 4 5 6]
Split 1D Array:
[array([10, 20]), array([30, 40]), array([50, 60])]
6
Experiment 4: WAP to implement Pandas
1. Creating a Series
2. Creating a DataFrame
• Python 3.x
• Pandas Library
• Jupyter Notebook
# Creating a Series
data = [10, 20, 30, 40, 50]
series = [Link](data)
Output
Pandas Series:
0 10
1 20
2 30
3 30
4 50
dtype: int64
print(series2)
7
b) Creating DataFrame in Pandas
A DataFrame is a two-dimensional data structure consisting of rows and columns, similar
to a table in a database or an Excel spreadsheet.
df = [Link](data)
Output
Pandas DataFrame:
Name Age Marks
0 Rahul 22 85
1 Amit 24 90
2 Neha 21 88
8
Experiment 5: WAP to implement Pandas
Step-wise Program
print("CSV Data:")
print(csv_data)
print("\nJSON Data:")
print(json_data)
9
Step 5: Display Last 5 Rows (Tail)
print("\nLast 5 rows of CSV dataset:")
print(csv_data.tail())
[Link]
[
{"ID":1,"Name":"Amit","Marks":78},
{"ID":2,"Name":"Rahul","Marks":85},
{"ID":3,"Name":"Pooja","Marks":90}
]
Output
CSV Data Output
ID Name Marks
0 1 Amit 78
1 2 Rahul 85
2 3 Pooja 90
3 4 Neha 88
4 5 Ravi 76
5 6 Suman 82
Head Output
ID Name Marks
0 1 Amit 78
1 2 Rahul 85
2 3 Pooja 90
3 4 Neha 88
4 5 Ravi 76
10
Tail Output
ID Name Marks
1 2 Rahul 85
2 3 Pooja 90
3 4 Neha 88
4 5 Ravi 76
5 6 Suman 82
11
Experiment 6: WAP to create following graphs using matplotlib
Exp 6 a. Draw a line in a diagram from position (0,0) to position (6,250):
h. Create Histogram.
• Line graph
• Multiple line graph
• Graph with title & labels
• Graph with grid
• Multiple plots
• Bar graph
• Pie chart
• Histogram
[Link](x, y)
[Link]()
12
b) Create a Multiple Lines Graph
x = [1, 2, 3, 4]
y1 = [10, 20, 30, 40]
y2 = [15, 25, 35, 45]
[Link](x, y1)
[Link](x, y2)
[Link]()
[Link](x, y)
[Link]("Simple Line Graph")
[Link]("X Axis")
[Link]("Y Axis")
[Link]()
[Link](x, y)
[Link](True)
[Link]()
[Link](1, 2, 1)
[Link](x, [10, 20, 30, 40])
[Link]("Plot 1")
[Link](1, 2, 2)
[Link](x, [40, 30, 20, 10])
[Link]("Plot 2")
[Link]()
[Link](names, values)
[Link]("Bar Graph")
[Link]()
13
g) Create Pie Chart
labels = ["Python", "Java", "C++", "Others"]
sizes = [40, 30, 20, 10]
h) Create Histogram
data = [10, 20, 20, 30, 30, 30, 40, 50]
[Link](data)
[Link]("Histogram")
[Link]()
14
Experiment 7: WAP Encoding Categorical Data.
1. Label Encoding
2. One-Hot Encoding
Theory
• Categorical data contains text values (e.g., Male/Female, Red/Blue).
• Machine learning algorithms require numerical input, so encoding is necessary.
Step-wise Program
df = [Link](data)
print("Original Data:")
print(df)
15
df['Gender_Encoded'] = le.fit_transform(df['Gender'])
df['City_Encoded'] = le.fit_transform(df['City'])
Output
Original Data
Name Gender City
0 Amit Male Delhi
1 Rahul Male Mumbai
2 Neha Female Delhi
3 Pooja Female Kolkata
16
Experiment 8: WAP for Splitting the dataset into Training and Test set.
To split a given dataset into training data and testing data using Python.
Theory
• Training set is used to train the machine learning model.
• Test set is used to evaluate the performance of the model.
• Common split ratio is 70:30 or 80:20.
Step-wise Program
Step 1: Import Required Libraries
import numpy as np
from sklearn.model_selection import train_test_split
# Dependent variable
Y = [Link]([100, 200, 300, 400, 500])
17
print("\nTraining Output (Y_train):")
print(Y_train)
Output
Training Data (X_train):
[[1 10]
[3 30]
[4 40]]
18
Experiment 9: WAP for Feature Scaling.
To apply Feature Scaling techniques on a dataset so that all features are on the same scale.
Theory
Feature scaling is used to normalize the range of independent variables.
Common techniques:
Step-wise Program
df = [Link](data)
print("Original Dataset:")
print(df)
Method 1: Standardization
Step 3: Apply Standard Scaler
scaler = StandardScaler()
standardized_data = scaler.fit_transform(df)
19
print("\nAfter Standardization:")
print(df_standardized)
Method 2: Normalization
Step 4: Apply Min–Max Scaler
minmax = MinMaxScaler()
normalized_data = minmax.fit_transform(df)
Output
Original Dataset
Age Salary
0 18 15000
1 22 22000
2 25 27000
3 30 35000
4 35 40000
After Standardization
Age Salary
0 -1.414214 -1.336306
1 -0.707107 -0.534522
2 0.000000 0.000000
3 0.707107 0.801784
4 1.414214 1.069045
After Normalization
Age Salary
0 0.00 0.00
1 0.24 0.21
2 0.41 0.36
3 0.71 0.71
4 1.00 1.00
20
Experiment 10: WAP to implement Simple linear regression.
# [Link]
# Salary data
import numpy as nm
import [Link] as mtp
import pandas as pd
data_set= pd.read_csv('Salary_Data.csv')
print(data_set)
x= data_set.iloc[:, :-1].values
y= data_set.iloc[:, 1].values
print("x_train")
print(x_train)
print("x_test")
print(x_test)
print("y_train")
print(y_train)
print("y_test")
print(y_test)
21
regressor= LinearRegression()
[Link](x_train, y_train)
# y_pred= [Link](x_test)
# x_pred= [Link](x_train)
print("y_train")
print(y_train)
print("y_pred_train")
print(y_pred_train)
print("y_test")
print(y_test)
print("y_pred_test")
print(y_pred_test)
print([Link](x_test, y_test))
Output:
22
0.9749154407708353
23
Experiment 11: WAP to implement Multiple linear regression.
# [Link]
# dataset(50_CompList),
# importing libraries
import numpy as nm
import pandas as pd
#importing datasets
data_set= pd.read_csv('50_Startups.csv')
print(data_set)
x= data_set.iloc[:, :-1].values
y= data_set.iloc[:, 3].values
print(x)
print(y)
print("x_train")
print(x_train)
print("x_test")
24
print(x_test)
print("y_train")
print(y_train)
print("y_test")
print(y_test)
regressor= LinearRegression()
[Link](x_train, y_train)
y_pred= [Link](x_test)
print("y_pred")
print(y_pred)
Output
25
Experiment 12: To implement Logistic Regression for a binary
classification problem. Train the model, predict class labels, and evaluate
the model accuracy.
Tools Required:
• Python 3.x
• Libraries: pandas, numpy, scikit-learn, matplotlib, seaborn
# Machine Learning
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, confusion_matrix, classification_report,
roc_curve, roc_auc_score
# Visualization
import [Link] as plt
import seaborn as sns
iris = load_iris()
X = [Link]
y = [Link]
# For binary classification, select only Setosa (0) and Versicolor (1)
binary_indices = y != 2 # Remove class 2 (Virginica)
X = X[binary_indices]
y = y[binary_indices]
26
# Display first 5 rows
print([Link]())
# Basic statistics
print([Link]())
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:\n", cm)
# Classification Report
27
print("Classification Report:\n", classification_report(y_test, y_pred))
Sample output
(Bar chart will show equal distribution of class 0 and 1, each with 50 samples.)
28
Step 4 Output: Train-Test Split
Training samples: 70, Testing samples: 30
Confusion Matrix:
[[15 0]
[ 0 15]]
Classification Report:
precision recall f1-score support
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
(Heatmap of confusion matrix will show perfect classification with diagonal cells
highlighted.)
29
Experiment 13: WAP to implement cross validation.
# [Link]
import pandas as pd
df = [Link]({'y': [6, 8, 12, 14, 14, 15, 17, 22, 24, 23],
print(df)
X = df[['x1', 'x2']]
y = df['y']
cv = KFold(n_splits=10)
30
model = LinearRegression()
mae= mean(absolute(scores))
Output:
MSE = 3.1461548083469744
31
Experiment 14: To Implement Over-Fitting and Bias–Variance Analysis.
• Python 3.x
• NumPy
• Matplotlib
• Scikit-learn
Theory
• Over-fitting: Model performs very well on training data but poorly on test data.
• Under-fitting: Model is too simple and performs poorly on both training and test
data.
• Bias: Error due to overly simple model.
• Variance: Error due to overly complex model.
Step-wise Program
import numpy as np
import [Link] as plt
from [Link] import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error
from sklearn.model_selection import train_test_split
[Link](0)
poly = PolynomialFeatures(degree=8)
X_train_poly = poly.fit_transform(X_train)
X_test_poly = [Link](X_test)
32
Step 5: Train the Regression Model
model = LinearRegression()
[Link](X_train_poly, y_train)
y_train_pred = [Link](X_train_poly)
y_test_pred = [Link](X_test_poly)
Output
Error Output
33
Experiment 15: WAP to implement decision tree.
# [Link]
# importing libraries
import numpy as nm
import pandas as pd
#importing datasets
data_set= pd.read_csv('user_data.csv')
# [Link]
x= data_set.iloc[:, [2,3]].values
y= data_set.iloc[:, 4].values
#feature Scaling
st_x= StandardScaler()
x_train= st_x.fit_transform(x_train)
34
x_test= st_x.transform(x_test)
[Link](x_train, y_train)
y_pred= [Link](x_test)
print(cm)
print(score)
Output:
Confusion Matrix is :
[[62 6]
[ 3 29]]
0.91
35
Experiment 16: WAP to implement Naïve Bayes classifier.
# Steps to implement:
import numpy as nm
import pandas as pd
#importing datasets
# [Link]
dataset = pd.read_csv('user_data.csv')
y = [Link][:, 4].values
# Splitting the dataset into the Training set and Test set
# Feature Scaling
sc = StandardScaler()
36
x_train = sc.fit_transform(x_train)
x_test = [Link](x_test)
classifier = GaussianNB()
[Link](x_train, y_train)
y_pred = [Link](x_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
# Accuracy
print(score)
Output:
Confusion Matrix is :
[[65 3]
[ 7 25]]
0.9
37
Experiment 17: To implement a k-Nearest Neighbors classifier. Train the
model, predict class labels for test data, experiment with different values of
k, and evaluate model performance.
Tools Required:
• Python 3.x
• Libraries: pandas, numpy, scikit-learn, matplotlib, seaborn
# Machine Learning
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import accuracy_score, confusion_matrix, classification_report
# Visualization
import [Link] as plt
import seaborn as sns
38
# Class distribution
[Link](x='target', data=df)
[Link]("Target Class Distribution")
[Link]()
# Summary statistics
print([Link]())
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:\n", cm)
# Classification Report
print("Classification Report:\n", classification_report(y_test, y_pred))
39
[Link]("Actual")
[Link]("Confusion Matrix")
[Link]()
for k in k_values:
knn = KNeighborsClassifier(n_neighbors=k)
[Link](X_train, y_train)
y_pred_k = [Link](X_test)
accuracy_list.append(accuracy_score(y_test, y_pred_k))
# Plot accuracy vs k
[Link](k_values, accuracy_list, marker='o')
[Link]("Number of Neighbors (k)")
[Link]("Accuracy")
[Link]("k-NN Accuracy vs k Value")
[Link]()
Sample output
Step 2 Output: Dataset Preview
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0
3 4.6 3.1 1.5 0.2 0
4 5.0 3.6 1.4 0.2 0
40
Step 6 Output: Predictions
Predicted labels: [1 0 2 1 2 0 1 1 0 0]
Actual labels: [1 0 2 1 2 0 1 1 0 0]
Confusion Matrix:
[[14 0 0]
[ 0 16 2]
[ 0 1 12]]
Classification Report:
precision recall f1-score support
accuracy 0.98 45
macro avg 0.93 0.94 0.93 45
weighted avg 0.97 0.98 0.97 45
(Confusion matrix heatmap will show almost perfect classification, slight misclassifications
occur between class 1 and 2.)
(Plot will show a peak around k=3 to k=7, then slightly decreasing.)
41
Train multiple decision trees, combine their predictions, and evaluate
accuracy and feature importance.
Tools Required:
• Python 3.x
• Libraries: pandas, numpy, scikit-learn, matplotlib, seaborn
# Machine Learning
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score, confusion_matrix, classification_report
# Visualization
import [Link] as plt
import seaborn as sns
iris = load_iris()
X = [Link] # Features
y = [Link] # Target variable
42
# Check for missing values
print([Link]().sum())
# Basic statistics
print([Link]())
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:\n", cm)
# Classification Report
print("Classification Report:\n", classification_report(y_test, y_pred))
43
[Link](cm, annot=True, fmt='d', cmap='Blues', xticklabels=iris.target_names,
yticklabels=iris.target_names)
[Link]("Predicted")
[Link]("Actual")
[Link]("Confusion Matrix")
[Link]()
# Create a DataFrame
feat_df = [Link]({'Feature': features, 'Importance': importances})
feat_df = feat_df.sort_values(by='Importance', ascending=False)
Sample Output:
44
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
Basic statistics:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
count 150.000000 150.000000 150.000000 150.000000 150.000000
mean 5.843333 3.057333 3.758000 1.199333 1.000000
std 0.828066 0.435866 1.765298 0.762238 0.819232
min 4.300000 2.000000 1.000000 0.100000 0.000000
25% 5.100000 2.800000 1.600000 0.300000 0.000000
50% 5.800000 3.000000 4.350000 1.300000 1.000000
75% 6.400000 3.300000 5.100000 1.800000 2.000000
max 7.900000 4.400000 6.900000 2.500000 2.000000
(The target class distribution plot would show roughly 50 samples per class.)
Confusion Matrix:
[[14 0 0]
[ 0 17 1]
[ 0 0 13]]
Classification Report:
precision recall f1-score support
45
accuracy 0.98 45
macro avg 0.98 0.98 0.98 45
weighted avg 0.98 0.98 0.98 45
(Bar chart will clearly show petal length and petal width are the most important
features.)
46
Experiment 19: WAP to implement support vector machine.
# SVM
# [Link]
# importing libraries
import numpy as nm
import pandas as pd
#importing datasets
data_set= pd.read_csv('user_data.csv')
print(data_set.head())
x= data_set.iloc[:, [2,3]].values
y= data_set.iloc[:, 4].values
print(x)
print(y)
#feature Scaling
st_x= StandardScaler()
x_train= st_x.fit_transform(x_train)
47
x_test= st_x.transform(x_test)
print(x_train)
print(x_test)
[Link](x_train, y_train)
y_pred= [Link](x_test)
print(cm)
print(score)
Output:
Confusion Matrix is :
[[66 2]
[ 8 24]]
0.9
48
Experiment 20: To implement PCA for dimensionality reduction on a
dataset. Reduce features to principal components, visualize the
transformed data, and analyze variance explained by each component.
Tools Required:
• Python 3.x
• Libraries: pandas, numpy, matplotlib, seaborn, scikit-learn
df = [Link](X, columns=iris.feature_names)
df['target'] = y
print([Link]())
print(X_scaled[:5])
explained_variance = pca.explained_variance_ratio_
49
print(explained_variance)
Sample output:
50
[0.7277, 0.2303]
(This means the first 2 principal components retain ~95.8% of the original dataset’s
variance.)
(This shows which features contribute most to each principal component. PC1 is mostly
influenced by petal length and width, PC2 by sepal width.)
51