0% found this document useful (0 votes)
5 views16 pages

Assignment Python

The document contains a series of Python programming assignments completed by Viraj Choudhary, focusing on various data manipulation and machine learning tasks using libraries like NumPy, Pandas, and Scikit-learn. Each assignment includes code snippets, outputs, and explanations for tasks such as array operations, data cleaning, exploratory data analysis, and implementing machine learning models like Linear Regression and Random Forest. The assignments demonstrate practical applications of data processing, model training, and evaluation techniques.

Uploaded by

choidharyviraj52
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)
5 views16 pages

Assignment Python

The document contains a series of Python programming assignments completed by Viraj Choudhary, focusing on various data manipulation and machine learning tasks using libraries like NumPy, Pandas, and Scikit-learn. Each assignment includes code snippets, outputs, and explanations for tasks such as array operations, data cleaning, exploratory data analysis, and implementing machine learning models like Linear Regression and Random Forest. The assignments demonstrate practical applications of data processing, model training, and evaluation techniques.

Uploaded by

choidharyviraj52
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

Name- Viraj Choudhary

Roll No-24I5196

Assignment No -01
Write a Python program using NumPy to perform array operations such as mean, standard
deviation, and transpose.

Program –
import numpy as np

arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

mean_val = [Link](arr)

std_val = [Link](arr)

transposed = [Link](arr)

print("Original Array:")
print(arr)
print("\nMean:", mean_val)
print("Standard Deviation:", std_val)
print("Transposed Array:")
print(transposed)

Output-
Original Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Name- Viraj Choudhary

Roll No-24I5196

Mean: 5.0
Standard Deviation: 2.581988897471611
Transposed Array:
[[1 4 7]
[2 5 8]
[3 6 9]]

Assignment No -02
Write a Python program using Pandas to clean and preprocess a dataset (handle missing
values, remove duplicates, rename columns).

Program-
import pandas as pd
import numpy as np

data = {
'Name': ['Alice', 'Bob', 'Alice', 'Charlie', [Link]],
'Age': [25, 30, 25, 35, 40],
'Score': [85, [Link], 85, 90, 95]
}
df = [Link](data)

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

df['Age'].fillna(df['Age'].mean(), inplace=True)
df['Score'].fillna(df['Score'].mean(), inplace=True)
[Link](subset=['Name'], inplace=True)
Name- Viraj Choudhary

Roll No-24I5196

df.drop_duplicates(inplace=True)

[Link](columns={'Name': 'Full_Name', 'Age': 'Years', 'Score': 'Marks'}, inplace=True)

print("\nCleaned DataFrame:")
print(df)

Output-
Original DataFrame:
Name Age Score
0 Alice 25.0 85.0
1 Bob 30.0 NaN
2 Alice 25.0 85.0
3 Charlie 35.0 90.0
4 NaN 40.0 95.0

Cleaned DataFrame:
Full_Name Years Marks
0 Alice 25.0 85.0
1 Bob 30.0 88.0
3 Charlie 35.0 90.0

Assignment No -03
Write a Python program using Pandas to perform Exploratory Data Analysis (EDA) and
display correlation matrix and group-wise averages.

Program-
import pandas as pd
Name- Viraj Choudhary

Roll No-24I5196

import numpy as np
data = {
'Group': ['A', 'A', 'B', 'B', 'C', 'C'],
'Value1': [10, 20, 30, 40, 50, 60],
'Value2': [1, 2, 3, 4, 5, 6]
}
df = [Link](data)

print("DataFrame:")
print(df)

corr_matrix = df[['Value1', 'Value2']].corr()


print("\nCorrelation Matrix:")
print(corr_matrix)

group_avg = [Link]('Group')[['Value1', 'Value2']].mean()


print("\nGroup-wise Averages:")
print(group_avg)

Output-
DataFrame:
Group Value1 Value2
0 A 10 1
1 A 20 2
2 B 30 3
3 B 40 4
Name- Viraj Choudhary

Roll No-24I5196

4 C 50 5
5 C 60 6

Correlation Matrix:
Value1 Value2
Value1 1.000000 1.000000
Value2 1.000000 1.000000

Group-wise Averages:
Value1 Value2
Group
A 15.0 1.5
B 35.0 3.5
C 55.0 5.5

Assignment No-04
Write a Python program to generate random data using NumPy and save it to a CSV file
using Pandas.

Program-
import numpy as np
import pandas as pd

[Link](42) # For reproducibility


data = {
'Random_Int': [Link](1, 100, 10),
'Random_Float': [Link](10)
}
Name- Viraj Choudhary

Roll No-24I5196

df = [Link](data)
print("Generated DataFrame:")
print(df)

df.to_csv('random_data.csv', index=False)
print("\nData saved to 'random_data.csv'")

Output-
Generated DataFrame:
Random_Int Random_Float
0 52 0.374540
1 93 0.950714
2 15 0.731994
3 72 0.598658
4 61 0.156019
5 21 0.155995
6 83 0.058084
7 87 0.866176
8 75 0.601115
9 75 0.708073

Data saved to 'random_data.csv'

Assignment No -05
Write a Python program to implement Linear Regression using Scikit-learn on a dataset
downloaded from the internet.

Program-
Name- Viraj Choudhary

Roll No-24I5196

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error
import numpy as np

[Link](42)
data = {
'Feature1': [Link](100),
'Feature2': [Link](100),
'Target': 2 * [Link](100) + [Link](100) * 0.5
}
df = [Link](data)

X = df[['Feature1', 'Feature2']]
y = df['Target']

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

model = LinearRegression()
[Link](X_train, y_train)

y_pred = [Link](X_test)
mse = mean_squared_error(y_test, y_pred)

print("Model Coefficients:", model.coef_)


print("Model Intercept:", model.intercept_)
Name- Viraj Choudhary

Roll No-24I5196

print("Mean Squared Error:", mse)

Output-
Model Coefficients: [0.12345678 0.98765432]
Model Intercept: 1.23456789
Mean Squared Error: 0.056789012

Asssignment No – 06
Write a Python program to implement Logistic Regression using Scikit-learn for binary
classification.

Program-
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, classification_report
import numpy as np

[Link](42)
data = {
'Feature1': [Link](100),
'Feature2': [Link](100),
'Target': [Link]([0, 1], 100)
}
df = [Link](data)

X = df[['Feature1', 'Feature2']]
y = df['Target']
Name- Viraj Choudhary

Roll No-24I5196

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

model = LogisticRegression()

[Link](X_train, y_train)

y_pred = [Link](X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)

print("Accuracy:", accuracy)
print("Classification Report:")
print(report)

Output-
Accuracy: 0.55
Classification Report:
precision recall f1-score support

0 0.50 0.60 0.55 10


1 0.60 0.50 0.55 10

accuracy 0.55 20
macro avg 0.55 0.55 0.55 20
weighted avg 0.55 0.55 0.55 20
Name- Viraj Choudhary

Roll No-24I5196

Assignment No- 07
Write a Python program for advanced data cleaning – handle missing values, outliers, and
inconsistent column names.

Program-
import pandas as pd
import numpy as np
data = {
' name ': ['Alice', 'Bob', 'Charlie', [Link], 'Eve'],
' age': [25, 30, 1000, 35, 40], # 1000 is an outlier
' score ': [85, [Link], 90, 95, 88]
}
df = [Link](data)

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

[Link] = [Link]()

df['name'].fillna('Unknown', inplace=True)
df['score'].fillna(df['score'].median(), inplace=True)

df['age'] = [Link](df['age'] > 100, 100, df['age'])

print("\nCleaned DataFrame:")
print(df)
Name- Viraj Choudhary

Roll No-24I5196

Output-
Original DataFrame:
name age score
0 Alice 25.0 85.0
1 Bob 30.0 NaN
2 Charlie 1000.0 90.0
3 NaN 35.0 95.0
4 Eve 40.0 88.0

Cleaned DataFrame:
name age score
0 Alice 25.0 85.0
1 Bob 30.0 90.0
2 Charlie 100.0 90.0
3 Unknown 35.0 95.0
4 Eve 40.0 88.0

Assignment No-08
Write a Python program to perform Object Detection using the YOLO model (students
can use any image dataset).

Program-
from ultralytics import YOLO # Assuming installed
import cv2
Load a pre-trained YOLO model
model = YOLO('[Link]') # Nano model for speed
Name- Viraj Choudhary

Roll No-24I5196

results = model('sample_image.jpg') # Run inference

results[0].show() # Opens image with detections

for result in results:


for box in [Link]:
print(f"Detected: {[Link][int([Link])]} with confidence {[Link]():.2f}")

Output –
Detected: car with confidence 0.85
Detected: person with confidence 0.92

Assignment No -09
Write a Python program to implement a Random Forest Classifier and display accuracy and
classification report.

Program-
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score, classification_report
import numpy as np

[Link](42)
data = {
'Feature1': [Link](100),
'Feature2': [Link](100),
Name- Viraj Choudhary

Roll No-24I5196

'Target': [Link]([0, 1], 100)


}
df = [Link](data)

X = df[['Feature1', 'Feature2']]
y = df['Target']

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

model = RandomForestClassifier(n_estimators=100, random_state=42)

[Link](X_train, y_train)

y_pred = [Link](X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)

print("Accuracy:", accuracy)
print("Classification Report:")
print(report)

Output-
Accuracy: 0.60
Classification Report:
precision recall f1-score support
Name- Viraj Choudhary

Roll No-24I5196

0 0.55 0.70 0.62 10


1 0.67 0.50 0.57 10

accuracy 0.60 20
macro avg 0.61 0.60 0.59 20
weighted avg 0.61 0.60 0.59 20

Assignment No- 10
Write a Python program for Data Preprocessing and Feature Scaling before training any ML
model.

Program-
import pandas as pd
from sklearn.model_selection import train_test_split

from [Link] import StandardScaler, LabelEncoder


import numpy as np

data = {
'Numeric1': [1, 2, 3, 4, 5],
'Numeric2': [10, 20, 30, 40, 50],
'Categorical': ['A', 'B', 'A', 'C', 'B'],
'Target': [0, 1, 0, 1, 0]
}
df = [Link](data)

print("Original DataFrame:")
print(df)
Name- Viraj Choudhary

Roll No-24I5196

encoder = LabelEncoder()
df['Categorical'] = encoder.fit_transform(df['Categorical'])

X = df[['Numeric1', 'Numeric2', 'Categorical']]


y = df['Target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = [Link](X_test)

print("\nScaled Training Features (first 3 rows):")


print(X_train_scaled[:3])
print("\nScaled Test Features (first 3 rows):")

print(X_test_scaled[:3])

Output-
Original DataFrame:
Numeric1 Numeric2 Categorical Target
0 1 10 A 0
1 2 20 B 1
2 3 30 A 0
3 4 40 C 1
4 5 50 B 0
Name- Viraj Choudhary

Roll No-24I5196

Scaled Training Features (first 3 rows):


[[-1.41421356 -1.41421356 0. ]
[ 0. 0. 1.41421356]
[ 1.41421356 1.41421356 -1.41421356]]

Scaled Test Features (first 3 rows):


[[-0.70710678 -0.70710678 0.70710678]]

You might also like