0% found this document useful (0 votes)
3 views20 pages

Kartik ML Q1-8

The document outlines various problem statements for a Machine Learning Lab course, including tasks such as creating a DataFrame with student marks, performing matrix operations, building a K-NN classification model, and file handling operations in Python. Each problem includes an algorithm and sample code for implementation. The document serves as a guide for students to complete their lab assignments.

Uploaded by

kartikkhatri377
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)
3 views20 pages

Kartik ML Q1-8

The document outlines various problem statements for a Machine Learning Lab course, including tasks such as creating a DataFrame with student marks, performing matrix operations, building a K-NN classification model, and file handling operations in Python. Each problem includes an algorithm and sample code for implementation. The document serves as a guide for students to complete their lab assignments.

Uploaded by

kartikkhatri377
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
You are on page 1/ 20

Name – Kartik Khatri Course - BCA (6th Sem)

Section - B1 Student Id - 22151859


Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

Problem Statement 1 :- Create a Data Frame using dictionary containing students’ marks
details with columns Student_ID, Student_Name, Gender, Sub1, Sub2, Sub3 with the marks of
20 students.

Or you can create an excel file for the same and import it.

(i) Find the mean and median marks in each subject.


(ii) Find the mode of ‘Gender’ column.
(iii)Find the variance and standard deviation of marks in each subject

ALGORITHM:-

Step 1: - import pandas as pd

Step 2: - Create a data frame using Dictionary and list (students_data).

Step 3: - Make 6 columns in it namely as Student_ID, Student_Name, Gender,

Sub1, Sub2, Sub3..

Step 4: - Initiallize dataframe.

Step 5: - Calculating mean, median, mode, varisnce, standard deviation.

Code :- import pandas as pd students_data = {

"Student_ID": ["S01","S02","S03","S04", "S05", "S06","S07", "S08", "S09",

"S10", "S11", "S12", "S13", "S14", "S15", "S16", "S17", "S18", "S19", "S20"],

"Student_Name": ["Aarav", "Ishaan", "Rohan", "Kavya", "Ananya",

"Vihaan", "Aditya", "Tanya",

"Sanya", "Aisha", "Rahul", "Sneha", "Aryan", "Pooja", "Sakshi", "Neha",

"Kabir", "Ritika", "Varun", "Simran"],

"Gender": ["M", "M", "M", "F", "F", "M", "M", "F", "F", "F", "M", "F", "M",

"F", "F", "F", "M", "F", "M","F"],

"Sub1": [85, 78, 92, 88, 75, 90, 84, 79, 95, 87, 76, 89, 91, 80, 83, 77, 86,

82, 94, 81],

"Sub2": [80, 72, 90, 85, 70, 88, 82, 74, 92, 84, 73, 87, 89, 78, 81, 75, 83,

79, 93, 77],"Sub3": [82, 74, 91, 86, 72, 89, 83, 76, 93, 85, 74, 88, 90, 79, 82, 76, 84,

1
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

80, 92, 78]

df = pd.DataFrame(students_data)

#print(df)

sum_sub1 = df["Sub1"].sum() print("Sum =

",sum_sub1) count_sub1 =

df["Sub1"].count() print("Count = ",count_sub1,"\n")

mean_marks = df[["Sub1", "Sub2", "Sub3"]].mean()

median_marks = df[["Sub1","Sub2","Sub3"]].median()

mode_Gender = df["Gender"].mode()[0] var_marks =

df[["Sub1", "Sub2", "Sub3"]].var() std_marks =

df[["Sub1", "Sub2", "Sub3"]].std() print("**

mean_marks **\n",mean_marks,"\n") print("**

median_marks **\n",median_marks,"\n") print("Mode

of Gender Col. = ",mode_Gender,"\n")

print("Variance of marks = \n",var_marks,"\n")

print("Standard Deviation of marks = \n",std_marks)

Output :-

2
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

Problem Statement 2 :- Define two matrices. Find their sum, difference, transpose and
product of two matrices.

3
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

ALGORITHM:-

Step 1: - import numpy as np

Step 2: - Take first and second matrices details from users like row, column.

Step 3: - Inputting elements from user into the matrices.

Step 4: - Calculating sum, difference, transpose and product of two matrices.

Code :-

[ ADDITION ] import

numpy as np def

input_matrix(rows, cols):

matrix = np.zeros((rows, cols), dtype=int) for i in range(rows):

for j in range(cols): matrix[i][j] = int(input(f"Enter element at

position ({i},{j}) : ")) return matrix def print_matrix(matrix):

for row in matrix: for element in row:

print(element, end=" ") print() print("<----

Enter First matrix details : ---->") r1 =

int(input("Enter number of rows: ")) c1 =

int(input("Enter number of columns: ")) arr1 =

input_matrix(r1, c1) print("<---- First matrix : --

-->") print_matrix(arr1) print("<---- Enter

Second matrix details : ---->") r2 =

int(input("Enter number of rows: "))

c2 = int(input("Enter number of columns: "))

arr2 = input_matrix(r2, c2) print("<----

Second matrix : ---->") print_matrix(arr2) if

r1 == r2 and c1 == c2:

4
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

print("ADDITION") add = arr1 + arr2

print_matrix(add) else:

print("Error: Matrices must have the same dimensions for addition.")

Output : -

[ SUBTRACTION ]

import numpy as np def input_matrix(rows,

cols): matrix = np.zeros((rows, cols),

dtype=int) for i in range(rows): for j

in range(cols):

matrix[i][j] = int(input(f"Enter element at position ({i},{j}) : "))

return matrix def print_matrix(matrix): for row in matrix: for


5
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

element in row: print(element, end=" ") print() print("<---

- Enter First matrix details : ---->") r1 = int(input("Enter number of rows:

")) c1 = int(input("Enter number of columns: ")) arr1 = input_matrix(r1,

c1) print("<---- First matrix : ---->") print_matrix(arr1) print("<---- Enter

Second matrix details : ---->") r2 = int(input("Enter number of rows: "))

c2 = int(input("Enter number of columns: ")) arr2 = input_matrix(r2, c2)

print("<---- Second matrix : ---->") print_matrix(arr2) if r1 == r2 and c1

== c2: print("SUBTRACTION")

subtract = arr1 - arr2

print_matrix(subtract) else:

print("Error: Matrices must have the same dimensions for subtraction.") Output

:-

6
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

[ MULTIPLICATION]

import numpy as np def

input_matrix(rows, cols):

matrix = np.zeros((rows, cols), dtype=int)

for i in range(rows): for j in

range(cols):

matrix[i][j] = int(input(f"Enter element at position ({i},{j}) : "))

return matrix def print_matrix(matrix): for row in matrix: for

element in row: print(element, end=" ") print() print("<---

- Enter First matrix details : ---->") r1 = int(input("Enter number of rows:

")) c1 = int(input("Enter number of columns: ")) arr1 = input_matrix(r1,

c1) print("<---- First matrix : ---->") print_matrix(arr1) print("<---- Enter

Second matrix details : ---->") r2 = int(input("Enter number of rows: "))

c2 = int(input("Enter number of columns: ")) arr2 = input_matrix(r2, c2)

print("<---- Second matrix : ---->") print_matrix(arr2) if c1 == r2:

print("MULTIPLICATION")

product = np.dot(arr1, arr2)

print_matrix(product)

7
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

else: print("Error: The number of columns in the first matrix must equal the number of
rows in the second matrix for multiplication.")

Output :-

8
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

[ TRANSPOSE ]

import numpy as np def input_matrix(rows, cols): matrix =

np.zeros((rows, cols), dtype=int) for i in range(rows): for j in

range(cols): matrix[i][j] = int(input(f"Enter element at position

({i},{j}) : ")) return matrix def print_matrix(matrix): for row in

matrix: for element in row: print(element, end=" ")

print() def transpose_matrix(matrix): return np.transpose(matrix)

print("<---- Enter Matrix details : ---->") rows = int(input("Enter number

of rows: ")) cols = int(input("Enter number of columns: ")) matrix =

input_matrix(rows, cols) print("<---- Original Matrix : ---->")

print_matrix(matrix)

transposed_matrix = transpose_matrix(matrix) print("<----

Transposed Matrix : ---->")

print_matrix(transposed_matrix)

Output :-

9
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

Problem Statement 3 :- Construct the classification model by using K-NN algorithm using
Iris species data set. Take the value of k=3 , train the model by using 70 % data also print the
classification accuracy.

10
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

ALGORITHM:-

Step 1: - import pandas as pd

Step 2: - clean the noisy data by dropping 'Species','Id' columns.

Step 3: - from sklearn.model_selection import train_test_split.

Step 4: - from sklearn.neighbors import KNeighborsClassifier.

Step 5: - from sklearn.metrics import accuracy_score

Code :- import pandas as pd

df = pd.read_csv("/content/Iris.csv")

df.head() print(df) label =

df['Species'] data =

df.drop(['Species','Id'],axis=1)

# data = df.drop('Id',axis=1) data.head() from

sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test =

train_test_split(data,label,test_size=0.35,random_state=0)

print(x_train) print(x_test) print(y_train) print(y_test)

from sklearn.neighbors import KNeighborsClassifier classifier =


KNeighborsClassifier(n_neighbors=3) classifier.fit(x_train,y_train) y_predict
= classifier.predict(x_test)

from sklearn.metrics import accuracy_score print(accuracy_score(y_test,y_predict))

Output :-

11
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

Problem Statement 4 :- Write a Python Program to read a file line by line and store it into a
list.

12
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

ALGORITHM:-

Step 1: - import pandas.

Step 2: - create file using open() function .

Step 3: - give file name and second variable is mode of file which is write -> “w”.

Step 4: - read file using “r” mode with with open so that automatically close the file. Code

:-

f = open("/content/file.txt", 'w')

f.write('Hello this is a test file.\n')

f.write('Python file handling is easy\n')

f.write("BCA") print("Content

Written") f.close() with

open("/content/file.txt", "r") as file:

lines = file.readlines() print(lines)

Output :-

Problem Statement 5 :- Write a Python Program to perform following operations.

a) Read file with the help of function

13
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

b) Rename file
c) Delete file

ALGORITHM:-

Step 1: - import pandas.

Step 2: - create read_file() function .

Step 3: - give file name and second variable is mode of file which is write -> “r”.

Step 4: - return file content in a list.

Code :-

a) f = open('/content/file.txt','r')
f.read()

b) f = open('/content/file.txt','w')

f.write("Python is Important")

f.close()

c) import os os.remove('/content/file.txt')

Output :-

Problem Statement 6 :- Write a Python program to count the number of lines in a text file
using enumerate.

14
Name – Kartik Khatri Course - BCA (6th Sem)
Section - B1 Student Id - 22151859
Roll No - 25 Subject code - PBC-602 (Machine Learning Lab )

ALGORITHM:-
Step 1: - first create a file.
Step 2: - create read_file() function .
Step 3: - give file name and second variable is mode of file which is write -> “r”.
Step 4: - return file sum(1 for _, _ in enumerate(file, 1)).

Code :- f = open("/content/file.txt", 'w')

f.write('Hello this is a test file.\n')

f.write('Python file handling is easy\n')

f.write("BCA") print("Content

Written") f.close() with

open("/content/file.txt", "r") as file:

lines = file.readlines()

print(lines) def

count_line(filename): with

open(filename, "r") as file:

return sum(1 for _ in enumerate(file, 1))

file_name = "/content/file.txt" line_count =

count_line(file_name) print(f"The number

of lines is {line_count}")

15
Name – Ayush Ghildiyal Course - BCA (6th Sem)
Section - A1 Student Id - 22151811
Roll No - 28 (2221311) Subject code - PBC-602 (Machine Learning Lab )

Problem Statement 7 :- WAP to check if a value entered by a user is palindrome or not.

16
Name – Ayush Ghildiyal Course - BCA (6th Sem)
Section - A1 Student Id - 22151811
Roll No - 28 (2221311) Subject code - PBC-602 (Machine Learning Lab )

Output :-
ALGORITHM:-

Step 1: - create a function.

Step 2: - calculate length of the user input value .

Step 3: - start loop to the half of the length of the input.

Step 4: - check first and last letter of the input and decreases to meet at middle way

Code :- def isPalindrome(value): length = len(value) for i in range(length

// 2):

if value[i] != value[length - 1 - i]:

return False

return True

user = input("Enter value to check palindrome: ")

if isPalindrome(user): print("Yes! It is a

Palindrome") else: print("No! It is not a

Palindrome")

17
Name – Ayush Ghildiyal Course - BCA (6th Sem)
Section - A1 Student Id - 22151811
Roll No - 28 (2221311) Subject code - PBC-602 (Machine Learning Lab )

Problem Statement 8 :- WAP to print a factorial of a number.

18
Name – Ayush Ghildiyal Course - BCA (6th Sem)
Section - A1 Student Id - 22151811
Roll No - 28 (2221311) Subject code - PBC-602 (Machine Learning Lab )

Output :-
ALGORITHM:-

Step 1: - create a function.

Step 2: - if n == 0 or n == 1 then return 1.

Step 3: - otherwise return n * fact(n - 1).

Step 4: - display result

Code :- def fact(n):

if n == 0 or n == 1:

return 1

else:

return n * fact(n - 1) num = int(input("Enter a

number: ")) if num < 0: print("For negative numbers,

factorial is not possible") else:

print(f"Factorial of {num} is = {fact(num)}")

19
Name – Ayush Ghildiyal Course - BCA (6th Sem)
Section - A1 Student Id - 22151811
Roll No - 28 (2221311) Subject code - PBC-602 (Machine Learning Lab )

20

You might also like