Python Practical Complete Final
Python Practical Complete Final
2026
Program
# Palindrome Number Check
num = int(input('Enter a number: '))
original = num
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
if original == reverse:
print(f'{original} is a Palindrome.')
else:
print(f'{original} is NOT a Palindrome.')
Output
Page 1 of 72
ML&DA using Python 2024-
2026
Program
# Prime Number Check
import math
num = int(input('Enter a number: '))
if num < 2:
print(f'{num} is NOT a Prime number.')
else:
is_prime = True
for i in range(2, int([Link](num)) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f'{num} is a Prime number.')
else:
print(f'{num} is NOT a Prime number.')
Output
Page 2 of 72
ML&DA using Python 2024-
2026
Aim: Write a program to enter a number and calculate the sum of its
digits.
Program
# Sum of Digits
num = int(input('Enter a number: '))
original = num
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
print(f'Sum of digits of {original} = {digit_sum}')
Output
Page 3 of 72
ML&DA using Python 2024-
2026
Program
# Sum of first n positive integers
n = int(input('Enter value of n: '))
# Method 1: Formula
total_formula = n * (n + 1) // 2
# Method 2: Loop
total_loop = sum(range(1, n + 1))
print(f'Sum of first {n} positive integers:')
print(f' Formula : n*(n+1)/2 = {total_formula}')
print(f' Loop : {total_loop}')
Output
Page 4 of 72
ML&DA using Python 2024-
2026
Program
# Fibonacci Series
n = int(input('Enter number of terms: '))
a, b = 0, 1
print('Fibonacci Series:', end=' ')
for i in range(n):
print(a, end=' ')
a, b = b, a + b
print()
Output
Page 5 of 72
ML&DA using Python 2024-
2026
Program
# Factorial of a Number
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
Output
Page 6 of 72
ML&DA using Python 2024-
2026
Output
Page 7 of 72
ML&DA using Python 2024-
2026
Program
# HCF using Euclidean Algorithm
def hcf(a, b):
while b:
a, b = b, a % b
return a
Output
Page 8 of 72
ML&DA using Python 2024-
2026
Aim: Write a program to read the age of 100 persons and count
persons in age group 50 to 60.
Program
# Count persons in age group 50 to 60
import random
[Link](42) # reproducible results
ages = [[Link](1, 90) for _ in range(100)]
Output
Page 9 of 72
ML&DA using Python 2024-
2026
Aim: Write a program to read a positive integer and print its binary
equivalent.
Program
# Decimal to Binary Conversion
def decimal_to_binary(n):
if n == 0:
return '0'
binary = ''
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary
Output
Page 10 of 72
ML&DA using Python 2024-
2026
Page 11 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
# 3. Range of values
arr_range = [Link](1, 11) # 1 to 10
arr_lin = [Link](0,1,5) # 5 equally spaced
arr_step = [Link](0,50,5) # step of 5
# 4. Array attributes
a = [Link]([[1,2,3],[4,5,6]])
print('Shape :', [Link]) # (2,3)
print('Size :', [Link]) # 6
print('Ndim :', [Link]) # 2
print('Dtype :', [Link]) # int64
print('Itemsize :', [Link]) # 8 bytes
print('Nbytes :', [Link]) # 48 bytes
Page 12 of 72
ML&DA using Python 2024-
2026
Output
Page 13 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
a = [Link]([10, 20, 30, 40, 50])
b = [Link]([ 1, 2, 3, 4, 5])
# Arithmetic (element-wise)
print('Add :', a + b) # [11 22 33 44 55]
print('Mul :', a * b) # [10 40 90 160 250]
print('Pow :', b ** 3) # [1 8 27 64 125]
# Aggregation
print('Sum:', [Link](a)) # 150
print('Mean:', [Link](a)) # 30.0
print('Std:', [Link](a)) # 14.142
print('Cumsum:', [Link](b)) # [1 3 6 10 15]
# Linear Algebra
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print('Dot:\n', [Link](A, B))
print('Det:', [Link](A))
vals, _ = [Link](A)
print('Eigenvalues:', vals)
Page 14 of 72
ML&DA using Python 2024-
2026
Output
Page 15 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import time
# Key features
print('Reduce(add) :', [Link](arr)) # 15.0
print('Accumulate(add):', [Link](arr)) # [1 3 6
10 15]
print('Outer product:\n', [Link]([1,2,3],
[1,2,3]))
# Speed comparison
large = [Link](1_000_000)
t0 = [Link]()
_ = [x**2 for x in large] # Python loop
loop_t = [Link]() - t0
t0 = [Link]()
_ = [Link](large) # ufunc
ufunc_t = [Link]() - t0
print(f'Python loop : {loop_t:.4f}s')
print(f'NumPy ufunc : {ufunc_t:.4f}s')
print(f'Speedup : {loop_t/ufunc_t:.1f}x faster')
Page 16 of 72
ML&DA using Python 2024-
2026
Output
Page 17 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
arr = [Link]([[1,2,3],[4,5,6],[7,8,9]])
Page 18 of 72
ML&DA using Python 2024-
2026
Output
Page 19 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
Page 20 of 72
ML&DA using Python 2024-
2026
Output
Page 21 of 72
ML&DA using Python 2024-
2026
# Boolean mask
mask_gt40 = a > 40
print('Mask >40 :', mask_gt40)
print('Values>40:', a[mask_gt40]) # [72 45 88 55 60]
# Conditional filtering
print('Even :', a[a % 2 == 0]) # even numbers
print('20-60 :', a[(a>=20)&(a<=60)]) # between 20 and 60
print('<20|>70 :', a[(a<20)|(a>70)]) # <20 OR >70
Output
Page 22 of 72
ML&DA using Python 2024-
2026
Page 23 of 72
ML&DA using Python 2024-
2026
Aim: Use integer arrays for indexing and demonstrate advanced fancy
indexing techniques.
Program
import numpy as np
# 1D fancy indexing
a = [Link]([10, 20, 30, 40, 50, 60, 70, 80])
idx = [0, 2, 5, 7]
print('Selected:', a[idx]) # [10 30 60 80]
# 2D fancy indexing
m = [Link](1, 26).reshape(5, 5)
print('Rows 0,2,4:\n', m[[0, 2, 4]])
Output
Page 24 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
# Adding dimensions
a = [Link]([1, 2, 3])
print('newaxis row:', a[[Link],:].shape) # (1,3)
print('newaxis col:', a[:,[Link]].shape) # (3,1)
# Remove dimensions
b = [Link]([[[1],[2],[3]]]) # shape (1,3,1)
print('squeeze:', [Link](b).shape) # (3,)
# Flatten vs Ravel
m = [Link]([[1,2,3],[4,5,6]])
print('flatten:', [Link]()) # always returns copy
print('ravel :', [Link]()) # returns view if possible
# Stacking
x = [Link]([[1,2],[3,4]])
y = [Link]([[5,6],[7,8]])
print('vstack:\n', [Link]([x, y]))
print('hstack:\n', [Link]([x, y]))
Page 25 of 72
ML&DA using Python 2024-
2026
Output
Page 26 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
# Exercise 2: Arithmetic
A = [Link]([[1,2,3],[4,5,6],[7,8,9]])
B = [Link]([[9,8,7],[6,5,4],[3,2,1]])
print('A@B:\n', A @ B)
print('Mean:', [Link](A), '| Std:', round([Link](A),4))
# Exercise 3: Broadcasting
M = [Link](float)
norm = (M - [Link]()) / ([Link]() - [Link]())
print('Normalized:\n', [Link](norm, 3))
topper = [Link](total)
print(f'Topper: S{topper+1} with {total[topper]} marks')
Output
Page 28 of 72
ML&DA using Python 2024-
2026
Program
import pandas as pd
import numpy as np
# Arithmetic operations
print('s1 * 5:\n', s1 * 5)
print('s1 + s1:\n', s1 + s1)
# Accessing elements
print('First 3 :', s1[:3].tolist())
print('Last 2 :', s1[-2:].tolist())
print('Values>50:', s1[s1 > 50].tolist())
# Statistics
print('Mean:', [Link](), '| Max:', [Link]())
print('Sum :', [Link](), '| Std:', round([Link](),2))
Page 29 of 72
ML&DA using Python 2024-
2026
Output
Page 30 of 72
ML&DA using Python 2024-
2026
data = {
'Name' :
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'
],
'Roll' : [101,102,103,104,105,106,107,108],
'Marks' : [88, 55, 92, 41, 76, 68, 95, 33],
'City' :
['Delhi','Mumbai','Delhi','Pune','Chennai','Mumbai','Delhi',
'Pune']
}
df = [Link](data)
print('First 5 rows:\n', [Link]())
df['Grade'] = df['Marks'].apply(grade)
print('With Grades:\n', df)
Page 31 of 72
ML&DA using Python 2024-
2026
Output
Page 32 of 72
ML&DA using Python 2024-
2026
Aim: Create DataFrame with NaN values, detect, count, fill and drop
missing values using Pandas functions.
Program
import pandas as pd
import numpy as np
data = {
'Name' : ['Alice','Bob','Carol','David','Eve'],
'Age' : [23, [Link], 25, 28, [Link]],
'Salary': [50000, 60000, [Link], 45000, 55000],
'City' : ['Delhi','Mumbai', [Link],'Pune','Delhi']
}
df = [Link](data)
Page 33 of 72
ML&DA using Python 2024-
2026
Output
Page 34 of 72
ML&DA using Python 2024-
2026
Program
import pandas as pd
data = {
'Employee' :
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'
,'Iris','Jack'],
'Department':
['IT','HR','IT','Finance','HR','IT','Finance','HR','IT','Fin
ance'],
'Salary' :
[75000,45000,80000,62000,48000,72000,55000,42000,68000,70000
]
}
df = [Link](data)
grp = [Link]('Department')
print('Avg Salary:\n', grp['Salary'].mean())
print('Max Salary:\n', grp['Salary'].max())
print('Emp Count :\n', grp['Employee'].count())
# Multiple aggregation
print(grp['Salary'].agg(['mean','max','min','sum','count']))
Page 35 of 72
ML&DA using Python 2024-
2026
Output
Page 36 of 72
ML&DA using Python 2024-
2026
students = [Link]({
'Roll': [101,102,103,104,105],
'Name': ['Alice','Bob','Carol','David','Eve'],
'City': ['Delhi','Mumbai','Delhi','Pune','Chennai']
})
marks = [Link]({
'Roll' : [101,102,103,106,107],
'Math' : [85, 70, 92, 55, 60],
'Science': [78, 65, 88, 72, 45]
})
# Row concatenation
more = [Link]({'Roll':[108,109],'Name':
['Frank','Grace'],'City':['Jaipur','Kolkata']})
print('Concat:\n', [Link]([students,more],
ignore_index=True))
Page 37 of 72
ML&DA using Python 2024-
2026
Output
Page 38 of 72
ML&DA using Python 2024-
2026
Aim: Read data from CSV, display info, save to CSV/Excel, export
selected columns and change delimiter.
Program
import pandas as pd, io
csv_data = '''Order,Customer,Product,Amount,City
1,Alice,Laptop,75000,Delhi
2,Bob,Phone,25000,Mumbai
3,Carol,Tablet,35000,Delhi
4,David,Laptop,70000,Pune
5,Eve,Headphones,5000,Chennai
6,Frank,Phone,28000,Mumbai
7,Grace,Laptop,82000,Delhi
8,Henry,Tablet,30000,Kolkata'''
# Read CSV
df = pd.read_csv([Link](csv_data))
print('Data:\n', df)
print('Describe:\n', [Link]())
print('Dtypes:\n', [Link])
# Pipe delimiter
df.to_csv('[Link]', sep='|', index=False)
df2 = pd.read_csv('[Link]', sep='|')
print('Pipe re-read:\n', [Link]())
Page 39 of 72
ML&DA using Python 2024-
2026
Output
Page 40 of 72
ML&DA using Python 2024-
2026
Aim: Apply all Pandas concepts: load dataset, handle missing values,
group by category, city-wise sales, merge datasets, export summary.
Program
import pandas as pd, numpy as np, io
orders_csv = '''OrderID,CustomerID,Category,Amount,City
1001,C01,Electronics,75000,Delhi
1002,C02,Clothing,3500,Mumbai
1003,C01,Electronics,25000,Delhi
1004,C03,Furniture,18000,Pune
1005,C04,Clothing,2200,Chennai
1006,,Electronics,32000,Delhi
1007,C05,Furniture,45000,Mumbai
1008,C02,Clothing,,Bangalore
1009,C06,Electronics,15000,Pune
1010,C04,Furniture,22000,Chennai'''
orders = pd.read_csv([Link](orders_csv))
print('Missing:\n', [Link]().sum())
# Handle NaN
orders['CustomerID'].fillna('Unknown', inplace=True)
orders['Amount'].fillna(orders['Amount'].median(),
inplace=True)
# Category-wise sales
cat = [Link]('Category')
['Amount'].sum().sort_values(ascending=False)
print('Category Sales:\n', cat)
# City-wise sales
city = [Link]('City')
['Amount'].sum().sort_values(ascending=False)
print('City Sales:\n', city)
Page 41 of 72
ML&DA using Python 2024-
2026
# Export summary
summary = [Link]('Category').agg(
Orders=('OrderID','count'), Total=('Amount','sum'),
Avg=('Amount','mean')
).round(2)
summary.to_csv('sales_summary.csv')
print(summary)
Output
Page 42 of 72
ML&DA using Python 2024-
2026
Aim: Plot a line graph showing Student vs Marks and Study Hours
trend.
Program
import [Link] as plt
import numpy as np
students =
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'
,'Iris','Jack']
marks = [88, 55, 92, 41, 76, 68, 95, 33, 71, 80]
study_hrs = [7, 4, 8, 3, 6, 5, 9, 2, 6, 7]
Page 43 of 72
ML&DA using Python 2024-
2026
axes[1].set_xticklabels(students, rotation=45)
plt.tight_layout()
[Link]('line_graph.png', dpi=150)
[Link]()
Output
Graph / Plot
Page 44 of 72
ML&DA using Python 2024-
2026
Aim: Plot bar charts comparing student marks and Alice's subject-
wise performance.
Program
import [Link] as plt
import numpy as np
students =
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'
]
math = [88, 55, 92, 41, 76, 68, 95, 33]
subjects = ['Math','Physics','Chemistry','English','CS']
alice_marks = [88, 74, 85, 91, 79]
fontweight='bold')
axes[1].set_xticks(x) ; axes[1].set_xticklabels(subjects)
axes[1].set_ylim(0, 110)
plt.tight_layout()
[Link]('bar_chart.png', dpi=150)
[Link]()
Output
Graph / Plot
Page 46 of 72
ML&DA using Python 2024-
2026
Aim: Draw pie chart for marks distribution, histogram for score
distribution, and scatter plot for study hours vs marks.
Program
import [Link] as plt
import numpy as np
# ── Pie Chart
─────────────────────────────────────────────────
subjects = ['Math','Physics','Chemistry','English','CS']
marks = [88, 74, 85, 91, 79]
explode = [0, 0, 0, 0.08, 0] # highlight English
[Link](figsize=(7, 7))
[Link](marks, labels=subjects, explode=explode,
autopct='%1.1f%%', startangle=140, shadow=True)
[Link]("Alice's Marks Distribution", fontweight='bold')
[Link]('pie_chart.png', dpi=150) ; [Link]()
# ── Histogram
─────────────────────────────────────────────────
[Link](42)
scores = [Link]([[Link](70,10,60),
[Link](45,8,20),
[Link](90,5,20)]).astype(int)
scores = [Link](scores, 0, 100)
[Link](figsize=(9, 5))
[Link](scores, bins=15, edgecolor='black',
color='#3B82F6', alpha=0.8)
[Link]([Link](scores), color='red', linestyle='--',
label='Mean')
[Link]([Link](scores), color='green',
linestyle='-.', label='Median')
[Link]() ; [Link]('[Link]', dpi=150) ;
[Link]()
Page 47 of 72
ML&DA using Python 2024-
2026
# ── Scatter Plot
───────────────────────────────────────────────
[Link](5)
study = [Link](2, 10, 30)
marks2 = study * 8 + [Link](-10, 10, 30)
[Link](figsize=(7, 5))
[Link](study, marks2, c='blue', s=70, alpha=0.7)
m, b = [Link](study, marks2, 1)
[Link]([Link](2,9,100), m*[Link](2,9,100)+b,
'r--',
label=f'Trend y={m:.1f}x+{b:.1f}')
[Link]('Study Hours vs Marks') ; [Link]()
[Link]('scatter_plots.png', dpi=150) ; [Link]()
Output
Graph / Plot
Page 48 of 72
ML&DA using Python 2024-
2026
Page 49 of 72
ML&DA using Python 2024-
2026
Aim: Draw box plot for marks spread, multiple line graph for subject
comparison, and heatmap for correlation.
Program
import [Link] as plt
import numpy as np, pandas as pd
# ── Box Plot
──────────────────────────────────────────────────
[Link](1)
subjects = ['Math','Physics','Chemistry','English','CS']
data = [[Link](m,s,40).clip(0,100)
for m,s in [(68,15),(62,12),(75,10),(80,8),(72,14)]]
fig, ax = [Link](figsize=(10, 6))
bp = [Link](data, labels=subjects, patch_artist=True)
colors = ['#3B82F6','#10B981','#8B5CF6','#F59E0B','#EF4444']
for patch,c in zip(bp['boxes'],colors):
patch.set_facecolor(c) ; patch.set_alpha(0.7)
ax.set_title('Subject-wise Marks Distribution',
fontweight='bold')
[Link]('box_plot.png',dpi=150) ; [Link]()
# ── Multi-Line Graph
──────────────────────────────────────────
students =
['S1','S2','S3','S4','S5','S6','S7','S8','S9','S10']
subj_marks = {'Math':[88,55,92,41,76,68,95,33,71,80],
'Physics':[74,62,80,55,70,72,85,44,66,75],
'Chemistry':[85,70,88,60,78,65,90,50,72,82],
'English':[91,65,87,72,83,75,92,58,80,85],
'CS':[79,60,84,48,72,70,88,40,68,77]}
[Link](figsize=(12, 6))
for subj,scores in subj_marks.items():
[Link](students, scores, linewidth=2, label=subj)
[Link]('Students vs Marks – All
Subjects',fontweight='bold')
Page 50 of 72
ML&DA using Python 2024-
2026
[Link]() ; [Link](alpha=0.3)
[Link]('multi_line.png',dpi=150) ; [Link]()
# ── Heatmap
───────────────────────────────────────────────────
df = [Link](subj_marks)
corr = [Link]()
fig,ax = [Link](figsize=(8,6))
im = [Link](corr, cmap='RdYlGn', vmin=-1, vmax=1)
[Link](im) ; ax.set_title('Correlation
Heatmap',fontweight='bold')
for i in range(len(corr)):
for j in range(len(corr)):
[Link](j,i,f'{[Link][i,j]:.2f}',ha='center',va='center',
fontweight='bold')
[Link]('[Link]',dpi=150) ; [Link]()
Output
Graph / Plot
Page 51 of 72
ML&DA using Python 2024-
2026
Page 52 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score
# Train model
model = LinearRegression()
[Link](X_train, y_train)
Page 53 of 72
ML&DA using Python 2024-
2026
Output
Graph / Plot
Page 54 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score,
confusion_matrix, classification_report
# Evaluate
print('Accuracy :', accuracy_score(y_test, y_pred))
print('Confusion Matrix:')
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
Page 55 of 72
ML&DA using Python 2024-
2026
Z =
[Link](np.c_[[Link](),[Link]()]).reshape([Link]
)
[Link](xx, yy, Z, alpha=0.3, cmap='coolwarm')
[Link](X[:,0], X[:,1], c=y, cmap='coolwarm',
edgecolors='k')
[Link]('Logistic Regression Decision Boundary',
fontweight='bold')
[Link]('ml_p2_logistic_reg.png', dpi=150)
[Link]()
Output
Graph / Plot
Page 56 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import accuracy_score
X, y = make_classification(n_samples=200, n_features=2,
n_redundant=0, random_state=42)
X_train,X_test,y_train,y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
best_k = list(k_range)[[Link](accuracies)]
print(f'Best K={best_k}, Accuracy={max(accuracies):.3f}')
# Plot Accuracy vs K
[Link](figsize=(10, 4))
Page 57 of 72
ML&DA using Python 2024-
2026
Output
Graph / Plot
Page 58 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_blobs
from [Link] import KMeans
Page 59 of 72
ML&DA using Python 2024-
2026
# Visualize clusters
for c in range(4):
[Link](X[labels==c,0], X[labels==c,1],
label=f'Cluster {c+1}')
[Link](km.cluster_centers_[:,0],
km.cluster_centers_[:,1],
c='black', marker='X', s=200, label='Centroids')
[Link]('K-Means Clustering (K=4)', fontweight='bold')
[Link]() ; [Link]()
Output
Graph / Plot
Page 60 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import SVC
from [Link] import accuracy_score,
classification_report
X, y = make_classification(n_samples=200, n_features=2,
n_redundant=0, random_state=42)
X_train,X_test,y_train,y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
# Plot accuracy vs C
C_values = [0.01,0.1,1,10,100]
accs = []
for c in C_values:
Page 61 of 72
ML&DA using Python 2024-
2026
m = SVC(kernel='rbf',C=c).fit(X_train_s, y_train)
[Link](accuracy_score(y_test, [Link](X_test_s)))
[Link](C_values, accs, 'o-', linewidth=2)
[Link]('SVM: Accuracy vs C (RBF kernel)',
fontweight='bold')
[Link]('C') ; [Link]('Accuracy') ;
[Link](alpha=0.3)
[Link]('ml_p5_svm.png', dpi=150) ; [Link]()
Output
Graph / Plot
Page 62 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import load_iris
from [Link] import StandardScaler
from [Link] import PCA
# Plot 2D projection
[Link](figsize=(10, 4))
colors = ['steelblue', 'crimson', 'forestgreen']
for i, name in enumerate(iris.target_names):
[Link](X_2d[y==i,0], X_2d[y==i,1], c=colors[i],
Page 63 of 72
ML&DA using Python 2024-
2026
label=name, s=50)
[Link]('PC1') ; [Link]('PC2')
[Link]('PCA: 2D Projection of Iris (95.81% variance
retained)',
fontweight='bold')
[Link]() ; [Link](alpha=0.3)
[Link]('ml_p6_pca.png', dpi=150) ; [Link]()
Output
Graph / Plot
Page 64 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier, plot_tree
from [Link] import accuracy_score,
classification_report
X, y = make_classification(n_samples=200, n_features=2,
n_redundant=0, random_state=42)
X_train,X_test,y_train,y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
best_depth = list(depths)[[Link](test_acc)]
print(f'Best Depth: {best_depth}')
Page 65 of 72
ML&DA using Python 2024-
2026
y_pred = [Link](X_test)
print('Accuracy:', accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
Output
Graph / Plot
Page 66 of 72
ML&DA using Python 2024-
2026
Page 67 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score,
classification_report
X, y = make_classification(n_samples=200, n_features=2,
n_redundant=0, random_state=42)
X_train,X_test,y_train,y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
Page 68 of 72
ML&DA using Python 2024-
2026
[Link](figsize=(10, 4))
[Link](n_vals, accs, 'o-', linewidth=2, color='green')
[Link]('Number of Trees') ; [Link]('Accuracy')
[Link]('Random Forest: Accuracy vs # Trees',
fontweight='bold')
[Link](alpha=0.3)
[Link]('ml_p8_random_forest.png', dpi=150) ; [Link]()
Output
Graph / Plot
Page 69 of 72
ML&DA using Python 2024-
2026
Program
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.linear_model import LinearRegression,
LogisticRegression
from [Link] import KNeighborsClassifier
from [Link] import SVC
from [Link] import DecisionTreeClassifier
from [Link] import RandomForestClassifier
from [Link] import accuracy_score
Page 70 of 72
ML&DA using Python 2024-
2026
[Link](X_test))
svm = SVC(kernel='rbf',C=1).fit(Xs_train, y_train)
results['SVM (RBF)'] = accuracy_score(y_test,
[Link](Xs_test))
dt =
DecisionTreeClassifier(max_depth=5,random_state=42).fit(X_tr
ain, y_train)
results['Decision Tree'] = accuracy_score(y_test,
[Link](X_test))
rf =
RandomForestClassifier(n_estimators=100,random_state=42).fit
(X_train, y_train)
results['Random Forest'] = accuracy_score(y_test,
[Link](X_test))
Output
Page 71 of 72
ML&DA using Python 2024-
2026
Graph / Plot
Page 72 of 72