0% found this document useful (0 votes)
4 views34 pages

Ahsham.ml file

The document contains a series of practical exercises for an Introduction to Machine Learning course, focusing on NumPy and Pandas operations. Each practical includes an aim, input code, and expected output, covering topics such as array manipulation, statistical calculations, and DataFrame operations. The exercises are designed to help students understand and implement fundamental concepts in data manipulation and analysis.

Uploaded by

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

Ahsham.ml file

The document contains a series of practical exercises for an Introduction to Machine Learning course, focusing on NumPy and Pandas operations. Each practical includes an aim, input code, and expected output, covering topics such as array manipulation, statistical calculations, and DataFrame operations. The exercises are designed to help students understand and implement fundamental concepts in data manipulation and analysis.

Uploaded by

cgcgxfvc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:

EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 2.1
Aim - Write a NumPy program to implement following operation
 to convert a list of numeric values into a one-dimensional NumPy array

Input

import numpy as np
l=[1,2,3,4,5]
print("Original List :" , l)
arr1=np.array(l)
print("One Dimesional Array : ",arr1)

Output

Machine Learning (4350702) 1


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 2.2
Aim - Write a NumPy program to implement following operation
 to create a 3x3 matrix with values ranging from 2 to 10.

Input

import numpy as np
x = np.arange(2, 11).reshape(3,
3) print(x)

Output

Machine Learning (4350702) 2


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 2.3
Aim - Write a NumPy program to implement following operation
 to append values at the end of an array.

Input

import numpy as np
x = [10, 20, 30]
print("Original array:")
print(x)
x = np.append(x, [[40, 50], [ 80, 90]])
print("After append values to the end of the array:")
print(x)

Output

Machine Learning (4350702) 3


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 2.3
Aim - Write a NumPy program to implement following operation
 to create another shape from an array without changing its data(3*2 to 2*3)

Input

import numpy as np
l=[[1,2,3],[4,5,6]]
print("3 * 2 shape of array : \n" , np.reshape(l, (3,2)))
print("2 * 3 shape of previous array : \n" , np.reshape(l, (2,3)))

Output

Machine Learning (4350702) 4


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 3.1
Aim - Write a NumPy program to implement following operation
 to split an array of 14 elements into 3 arrays, each with 2, 4, and 8
elements in the original order

Input

import numpy as np
l=np.arange(1,15)
print("original array : \n",l)
print("After splitting : \n",np.split(l, [2, 6]))

Output

Machine Learning (4350702) 5


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 3.1
Aim - Write a NumPy program to implement following operation
 to stack arrays horizontally (column wise)

Input

import numpy as np
x=[1,2,3]
y=[4,5,6]
print("Array-1 : ", np.array(x))
print("Array-2 : ", np.array(y))
print("After horizontally : ", np.hstack((x,y)))

Output

Machine Learning (4350702) 6


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 4.1
Aim - Write a NumPy program to implement following operation
 to add, subtract, multiply, divide arguments element-wise.

Input

import numpy as np
x=[1,2,3]
y=[4,5,6]
print("addition of two array : ",np.add(x,y))
print("subtract of two array : ",np.subtract(x,y))
print("multiply of two array : ",np.multiply(x,y))
print("divide of two array : ",np.divide(x,y))

Output

Machine Learning (4350702) 7


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 4.2
Aim - Write a NumPy program to implement following operation
 to round elements of the array to the nearest integer

Input

import numpy as np
l=[1.1,0.4,1.5,1.7]
print("original array : " , l)
x=np.rint(l)
print("Nearest of original array : " , x)

Output

Machine Learning (4350702) 8


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 4.3
Aim - Write a NumPy program to implement following operation
 to calculate mean across dimension, in a 2D numpy array

Input

import numpy as np
x=np.array([[1,2],[3,4]])
print("Original Array : \n",x)
print("Mean of each column : ",x.mean(axis=0))
print("Mean of each row : ",x.mean(axis=1))

Output

Machine Learning (4350702) 9


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 4.4
Aim - Write a NumPy program to implement following operation
 to calculate the difference between neighboring elements, elementwise
of a given array

Input

import numpy as np
x=np.array([1,3,7,10,15,19])
print("original list : " , x)
y=np.diff(x)
print("Difference of Original List : ",y)

Output

Machine Learning (4350702) 10


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 5.1
Aim - Write a NumPy program to implement following operation
 to find the maximum and minimum value of a given flattened array

Input

import numpy as np
arr=np.arange(4).reshape((2,2))
print("original array : \n",arr)
print("Maximum array from flattened array : \n",np.max(arr))
print("Minimum array from flattened array : \n",np.min(arr))

Output

Machine Learning (4350702) 11


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 5.2
Aim - Write a NumPy program to implement following operation
 to compute the mean, standard deviation, and variance of a given
array along the second axis

Input

import numpy as np
arr=np.arange(6)
print("original array is : ",arr)
print("mean of original array is : ",np.mean(arr))
print("standard deviation of original array is :",np.std(arr))
print("variation of original array is : ",np.var(arr))

Output

Machine Learning (4350702) 12


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 6.1
Aim - Write a Pandas program to implement following operation
 to convert a NumPy array to a Pandas series

Input

import numpy as
np import pandas
as pd

arr1=np.array([1,2,3,4])
print("Original Array : ",arr1)

arr2=pd.Series(arr1)
print("Pandas Array :
",arr2)

Output

Machine Learning (4350702) 13


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 6.1
Aim - Write a Pandas program to implement following operation
 to convert the first column of a DataFrame as a Series

Input

import pandas as pd
dit = {'August': [10, 25, 34, 4.85, 71.2, 1.1],
'September': [4.8, 54, 68, 9.25, 58, 0.9],
'October': [78, 5.8, 8.52, 12, 1.6, 11],
'November': [100, 5.8, 50, 8.9, 77, 10]
}
print("original dictionary : \
n",dit) df=pd.DataFrame(dit)
print("After converting into Datadrame : ",df)

Output

Machine Learning (4350702) 14


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 6.2
Aim - Write a Pandas program to implement following operation
 to create the mean and standard deviation of the data of a given Series

Input

import pandas as pd
data=pd.Series([1,2,3,4,5])
print("original data : ",
data)
print("mean of original data : ", data.mean())
print("standard deviation of original data : ", data.std())

Output

Machine Learning (4350702) 15


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 6.3
Aim - Write a Pandas program to implement following operation
 to sort a given Series

Input

import pandas as pd
data=pd.Series([21,425,12,67,1])
print("original data : ", data)
print("Sort values of original data : \n",data.sort_values())

Output

Machine Learning (4350702) 16


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 7.1
Aim – Write a Pandas program to implement following operation
 to create a dataframe from a dictionary and display it

Input

import pandas as
pd data= {
"name" :
['atif','rayhan','hanif','taiyab'],
"age" : [19,20,21,20],
"city" : ['Surat','Bharuch','Surat','Navsari']
}
print("Original DataFrame : \n",pd.DataFrame(data))

Output

Machine Learning (4350702) 17


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 7.2
Aim – Write a Pandas program to implement following operation
 to sort the DataFrame first by 'name' in ascending order

Input

import pandas as pd
data = {'name': ['Atif', 'Bob', 'Charlie',
'David'], 'age': [25, 30, 28, 32],
'city': ['New York', 'Los Angeles', 'Chicago', 'Houston']}

df = pd.DataFrame(data)

print("Original DataFrame:")
print(df)

df_sorted = df.sort_values(by='name', ascending=True)


print("\nSorted DataFrame:")
print(df_sorted)

Output

Machine Learning (4350702) 18


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 7.3
Aim – Write a Pandas program to implement following operation
 to delete the one specific column from the DataFrame

Input

import pandas as pd
data = {'name': ['Atif', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 28, 32],
'city': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df_sorted = df.sort_values(by='name', ascending=True) print("\
nSorted DataFrame:")
print(df_sorted)
df_modified = df.drop(columns='age') print("\
nDataFrame after deleting 'age' column:")
print(df_modified)

Output

Machine Learning (4350702) 19


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 7.4
Aim – Write a Pandas program to implement following operation
 to write a DataFrame to CSV file using tab separator

Input

import pandas as pd
data = {'name': ['Atif', 'Bob', 'Charlie', 'David'],
'age': [25, 30, 28, 32],
'city': ['New York', 'Los Angeles', 'Chicago',
'Houston']} df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df_sorted = df.sort_values(by='name', ascending=True)
print("\nSorted DataFrame:")
print(df_sorted)
df_modified = df.drop(columns='age') print("\
nDataFrame after deleting 'age' column:")
print(df_modified)
# Write the DataFrame to a CSV file with tab separator
df_modified.to_csv('output.csv', sep='\t', index=False)

Output

Machine Learning (4350702) 20


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 8
Aim – Write a Pandas program to create a line plot of the opening, closing
stock prices of given company between two specific dates.

Input
import pandas as pd
import matplotlib.pyplot as plt

data = {
'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'],
'Open': [100, 102, 99, 105],
'Close': [98, 101, 100, 103]
}
df = pd.DataFrame(data)

df['Date'] = pd.to_datetime(df['Date'])

company_name = 'Apple Company '


start_date = '2023-01-01'
end_date = '2023-01-04'

filtered_data = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]

plt.figure(figsize=(10, 6))
plt.plot(filtered_data['Date'], filtered_data['Open'], label='Open')
plt.plot(filtered_data['Date'], filtered_data['Close'],
label='Close') plt.title(f'Stock Price Analysis for
{company_name}') plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Machine Learning (4350702) 21


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Output

Machine Learning (4350702) 22


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 9
Aim – Write a Pandas program to create a plot of Open, High, Low, Close,
Adjusted Closing prices and Volume of given company between two specific
dates.

Input
import pandas as pd
import matplotlib.pyplot as plt
# Sample CSV data (replace with your actual
data) data = {
'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04'],
'Open': [100, 102, 99, 105],
'High': [103, 105, 102, 107],
'Low': [98, 100, 97, 101],
'Close': [98, 101, 100, 103],
'Adj Close': [98, 101, 100, 103],
'Volume': [10000, 12000, 8000, 15000]}
df = pd.DataFrame(data)
# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])
# Specify the company name and date range
company_name = 'Apple Company' # Replace with your desired company
start_date = '2023-01-01'
end_date = '2023-01-04'
# Filter data for the specified date range (removed company filter)
filtered_data = df[(df['Date'] >= start_date) & (df['Date'] <=
end_date)] # Create subplots for each price and volume
# Increased number of columns to match the number of items we want to plot
fig, axs = plt.subplots(nrows=2, ncols=5, figsize=(15, 8))
# Plot Open, High, Low, Close, Adjusted Close
columns = ['Open', 'High', 'Low', 'Close', 'Adj Close']
for i, col in enumerate(columns):
axs[0, i].plot(filtered_data['Date'],
filtered_data[col]) axs[0, i].set_title(col)
axs[0, i].set_xlabel('Date')
axs[0, i].set_ylabel('Price')
# Plot Volume
axs[1, 0].bar(filtered_data['Date'],
filtered_data['Volume']) axs[1, 0].set_title('Volume')
axs[1, 0].set_xlabel('Date')
axs[1,
0].set_ylabel('Volume')

Machine Learning (4350702) 23


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702
# Adjust spacing and show the plot

Machine Learning (4350702) 24


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

plt.tight_layout()
plt.show()

Machine Learning (4350702) 25


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Output

Machine Learning (4350702) 26


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 10.1
Aim – Write a Pandas program to implement following operation
 to find and drop the missing values from the given dataset

Input

import pandas as pd

# Sample data with missing values and duplicates


data = {
'column1': [1, 2, None, 4, 5, 1],
'column2': ['a', 'b', 'c', None, 'e', 'a'],
'column3': [True, False, True, None, True, True]
}

# Create a DataFrame from the sample


data df = pd.DataFrame(data)

# Find and drop missing


values df_cleaned =
df.dropna() print(df_cleaned)

Output

Machine Learning (4350702) 27


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 10.2
Aim – Write a Pandas program to implement following operation
 to remove the duplicates from the given dataset

Input

import pandas as pd

# Sample data with missing values and duplicates


data = {
'column1': [1, 2, None, 4, 5, 1],
'column2': ['a', 'b', 'c', None, 'e', 'a'],
'column3': [True, False, True, None, True, True]
}
# Create a DataFrame from the sample
data df = pd.DataFrame(data)

# Find and drop missing


values df_cleaned =
df.dropna()

print(df_cleaned)

# Remove duplicates
df_cleaned = df_cleaned.drop_duplicates()

# Display the cleaned DataFrame


print("\nDataFrame after dropping missing values and duplicates:")
print(df_cleaned)

Output

Machine Learning (4350702) 28


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Machine Learning (4350702) 29


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 11
Aim - Write a Pandas program to filter all columns where all entries present,
check which rows and columns has a NaN and finally drop rows with any
NaNs from the given dataset.

Input
import pandas as pd

# Sample data with missing values


data = {
'column1': [1, 2, None, 4, 5],
'column2': ['a', 'b', 'c', None, 'e'],
'column3': [True, False, True, None, True]
}

# Create a DataFrame from the sample data


df = pd.DataFrame(data)

# Filter columns where all entries are present


columns_without_missing = df.dropna(axis=1, how='all')

# Check rows and columns with NaNs


rows_with_missing = df[df.isnull().any(axis=1)].index
columns_with_missing =
df.columns[df.isnull().any()]

# Drop rows with any NaNs


df_cleaned = df.dropna()

# Display the results


print("Columns without missing values:")
print(columns_without_missing.columns)

print("\nRows with missing values:")


print(rows_with_missing)

print("\nColumns with missing values:")


print(columns_with_missing)

print("\nDataFrame after dropping rows with NaNs:")


print(df_cleaned)
Machine Learning (4350702) 30
Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Output

Machine Learning (4350702) 31


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Practical No – 12
Aim - Write a Python program using Scikit-learn to print the keys, number
of rows-columns, feature names and the description of the given data.

Input

from sklearn.datasets import load_iris


# Load the Iris dataset
iris = load_iris()
# Print the keys of the dataset
print("Keys of the dataset:",
iris.keys())
# Print the shape of the data (number of rows and columns)
print("Shape of the data:", iris.data.shape)
# Print the feature names
print("Feature names:", iris.feature_names)
# Print the description of the dataset
print("Description of the dataset:\n", iris.DESCR)

Output

Machine Learning (4350702) 32


Name:Ahsham Danawala Subject Name: Introduction to Machine Learning Batch No:
EnrolmentNo:22601030713 CO1 Subject Code: 4350702

Machine Learning (4350702) 33


Name:Malek Safin Subject Name: Introduction to Machine Learning Batch No: CO2
EnrolmentNo:22601030749 Subject Code: 4350702

Practical No – 13
Aim - Write a Python program to implement K-Nearest Neighbour supervised
machine learning algorithm for given dataset

Input

import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import
train_test_split from sklearn.metrics import
accuracy_score

# Sample dataset (replace with your own data)


data = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8],
[8, 9], [9, 10]])
labels = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])

# Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(data, labels,
test_size=0.2, random_state=42)

# Create a KNN classifier with k=3


knn = KNeighborsClassifier(n_neighbors=3)

# Train the classifier on the training


data knn.fit(X_train, y_train)

# Make predictions on the testing data


y_pred = knn.predict(X_test)

# Calculate the accuracy of the model


accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

Output

Machine Learning (4350702) 34

You might also like