knn assignments in machine learning

Assignment 1 — Employee Salary Category Prediction using K-Nearest Neighbors (KNN)

Objective

Build a K-Nearest Neighbors (KNN) Classification model to predict whether an employee belongs to the High Salary or Low Salary category.

Dataset

File Name

employee_salary_knn.csv
EmployeeIDExperienceYearsEducationSkillsInterviewScoreSalaryCategory
11BachelorsPython55Low
22BachelorsJava58Low
33MastersPython65Low
44MastersJava68Low
55MastersPython72High
66MastersPython75High
77PhDPython80High
88PhDData Science85High
92DiplomaJava52Low
103DiplomaJava60Low
114BachelorsPython66Low
125BachelorsData Science70High
136MastersData Science74High
147MastersPython79High
158PhDAI90High
161DiplomaJava50Low
172DiplomaPython57Low
183BachelorsJava63Low
194MastersAI69Low
205MastersAI73High
216MastersPython76High
227PhDAI82High
238PhDData Science88High
242DiplomaPython56Low
253BachelorsPython64Low
264BachelorsJava67Low
275MastersData Science71High
286MastersAI77High
297PhDPython83High
308PhDAI91High
311DiplomaJava51Low
322BachelorsJava59Low
333BachelorsPython62Low
344MastersData Science68Low
355MastersPython72High
366MastersAI75High
377PhDAI81High
388PhDData Science86High
392DiplomaPython54Low
403DiplomaJava61Low
414BachelorsAI66Low
425BachelorsData Science70High
436MastersPython74High
447MastersAI80High
458PhDPython87High
462DiplomaJava53Low
473BachelorsPython65Low
485MastersAI73High
496MastersData Science78High
508PhDAI92High

Before Training

This dataset cannot be used directly.

The following preprocessing is required.

Step 1 — Handle Missing Values (if any)

Check whether the dataset contains missing values.


Step 2 — Encode Categorical Columns

Use Label Encoding for:

  • Education

  • Skills

  • SalaryCategory

Example

OriginalEncoded
Diploma0
Bachelors1
Masters2
PhD3

Step 3 — Feature Scaling

Since KNN is a distance-based algorithm, apply StandardScaler (or MinMaxScaler) to the input features before training.


Features (X)

ExperienceYears
Education
Skills
InterviewScore

Target (y)

SalaryCategory

Practical Questions

Question 1

Load the dataset using Pandas.


Question 2

Check the first five records.


Question 3

Display the shape of the dataset.


Question 4

Check the data types of all columns.


Question 5

Check whether the dataset contains missing values.


Question 6

Apply Label Encoding to all categorical columns.


Question 7

Separate the features (X) and target (y).


Question 8

Split the dataset into training and testing sets using an 80:20 ratio.


Question 9

Apply StandardScaler to the training and testing data.


Question 10

Create a KNN classifier with:

K = 3

Train the model.


Question 11

Predict the salary category for the test dataset.


Question 12

Calculate the Accuracy of the model.


Question 13

Generate the Confusion Matrix.


Question 14

Calculate:

  • Precision

  • Recall

  • F1-Score


Question 15

Repeat the experiment using:

  • K = 5

  • K = 7

  • K = 9

Compare the accuracy of each model.


Question 16

Which value of K gives the best accuracy?


Question 17

Predict the salary category of the following employee:

ExperienceEducationSkillsInterview Score
6 YearsMastersAI78



# ==========================================

# Employee Salary Category Prediction using KNN

# ==========================================


import pandas as pd


# Machine Learning Libraries

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import LabelEncoder

from sklearn.preprocessing import StandardScaler

from sklearn.neighbors import KNeighborsClassifier


# Evaluation Metrics

from sklearn.metrics import accuracy_score

from sklearn.metrics import confusion_matrix

from sklearn.metrics import precision_score

from sklearn.metrics import recall_score

from sklearn.metrics import f1_score

from sklearn.metrics import classification_report


# ==========================================

# Load Dataset

# ==========================================


df = pd.read_csv("employee_salary_knn.csv")


print("Dataset Loaded Successfully\n")


# ==========================================

# Display Dataset

# ==========================================


print("First 5 Records")

print(df.head())


print("\nLast 5 Records")

print(df.tail())


print("\nShape")

print(df.shape)


print("\nInformation")

print(df.info())


print("\nData Types")

print(df.dtypes)


print("\nMissing Values")

print(df.isnull().sum())


# ==========================================

# Label Encoding

# ==========================================


education_encoder = LabelEncoder()

skills_encoder = LabelEncoder()

salary_encoder = LabelEncoder()


df["Education"] = education_encoder.fit_transform(df["Education"])


df["Skills"] = skills_encoder.fit_transform(df["Skills"])


df["SalaryCategory"] = salary_encoder.fit_transform(df["SalaryCategory"])


print("\nEncoded Dataset")

print(df.head())


# ==========================================

# Features and Target

# ==========================================


X = df[

    [

        "ExperienceYears",

        "Education",

        "Skills",

        "InterviewScore"

    ]

]


y = df["SalaryCategory"]


# ==========================================

# Split Dataset

# ==========================================


X_train, X_test, y_train, y_test = train_test_split(

    X,

    y,

    test_size=0.20,

    random_state=42

)


# ==========================================

# Feature Scaling

# ==========================================


scaler = StandardScaler()


X_train = scaler.fit_transform(X_train)


X_test = scaler.transform(X_test)


# ==========================================

# Create KNN Model

# ==========================================


model = KNeighborsClassifier(

    n_neighbors=3

)


# ==========================================

# Train Model

# ==========================================


model.fit(

    X_train,

    y_train

)


print("\nModel Trained Successfully")


# ==========================================

# Prediction

# ==========================================


y_pred = model.predict(X_test)


print("\nActual Values")

print(y_test.values)


print("\nPredicted Values")

print(y_pred)


# ==========================================

# Accuracy

# ==========================================


accuracy = accuracy_score(

    y_test,

    y_pred

)


print("\nAccuracy")

print(accuracy)


print("Accuracy Percentage :", accuracy * 100)


# ==========================================

# Confusion Matrix

# ==========================================


cm = confusion_matrix(

    y_test,

    y_pred

)


print("\nConfusion Matrix")

print(cm)


# ==========================================

# Precision

# ==========================================


precision = precision_score(

    y_test,

    y_pred

)


print("\nPrecision")

print(precision)


# ==========================================

# Recall

# ==========================================


recall = recall_score(

    y_test,

    y_pred

)


print("\nRecall")

print(recall)


# ==========================================

# F1 Score

# ==========================================


f1 = f1_score(

    y_test,

    y_pred

)


print("\nF1 Score")

print(f1)


# ==========================================

# Classification Report

# ==========================================


print("\nClassification Report")


print(

    classification_report(

        y_test,

        y_pred

    )

)


# ==========================================

# Compare Different K Values

# ==========================================


print("\n==============================")

print("Compare Different K Values")

print("==============================")


for k in [3, 5, 7, 9]:


    model = KNeighborsClassifier(

        n_neighbors=k

    )


    model.fit(

        X_train,

        y_train

    )


    prediction = model.predict(X_test)


    accuracy = accuracy_score(

        y_test,

        prediction

    )


    print("K =", k, "Accuracy =", accuracy)


# ==========================================

# Best K

# ==========================================


best_accuracy = 0

best_k = 0


for k in range(1, 16):


    model = KNeighborsClassifier(

        n_neighbors=k

    )


    model.fit(

        X_train,

        y_train

    )


    prediction = model.predict(X_test)


    accuracy = accuracy_score(

        y_test,

        prediction

    )


    if accuracy > best_accuracy:


        best_accuracy = accuracy

        best_k = k


print("\nBest K :", best_k)

print("Best Accuracy :", best_accuracy)


# ==========================================

# Predict New Employee

# ==========================================


new_employee = pd.DataFrame(

    {

        "ExperienceYears": [6],

        "Education": ["Masters"],

        "Skills": ["AI"],

        "InterviewScore": [78]

    }

)


# Encode using previously trained encoders


new_employee["Education"] = education_encoder.transform(

    new_employee["Education"]

)


new_employee["Skills"] = skills_encoder.transform(

    new_employee["Skills"]

)


# Scale


new_employee = scaler.transform(new_employee)


# Prediction


prediction = model.predict(new_employee)


print("\nPrediction")


if prediction[0] == 1:


    print("High Salary Category")


else:


    print("Low Salary Category")







Assignment 2 — Loan Approval Prediction using K-Nearest Neighbors (KNN)

Objective

Build a K-Nearest Neighbors (KNN) model to predict whether a customer's loan application will be Approved or Rejected.

Banks often compare a new applicant with previous applicants having similar income, employment, credit history, and education. This makes KNN a suitable algorithm for this problem.


Dataset

File Name

loan_approval_knn.csv
CustomerIDAgeEducationEmploymentTypeMonthlyIncomeCreditScoreExistingLoansCityLoanApproved
124GraduatePrivate250006200DelhiNo
226GraduatePrivate280006401DelhiNo
328Post GraduateGovernment350006901MumbaiYes
430Post GraduateGovernment420007301MumbaiYes
522GraduatePrivate220006100JaipurNo
632Post GraduateGovernment500007602DelhiYes
735PhDGovernment650008101BangaloreYes
827GraduatePrivate300006601PuneNo
929GraduateBusiness450007101DelhiYes
1031Post GraduateBusiness520007502MumbaiYes
1125GraduatePrivate270006300DelhiNo
1233PhDGovernment700008201BangaloreYes
1334Post GraduateBusiness560007702MumbaiYes
1423GraduatePrivate240006150JaipurNo
1536PhDGovernment720008301DelhiYes
1626GraduatePrivate290006451PuneNo
1728GraduateBusiness400007001DelhiYes
1830Post GraduateGovernment480007402MumbaiYes
1921GraduatePrivate210006000JaipurNo
2037PhDGovernment760008402BangaloreYes
2124GraduatePrivate260006250DelhiNo
2227GraduateBusiness390006951PuneYes
2329Post GraduateGovernment460007251MumbaiYes
2431BusinessBusiness540007602DelhiYes
2522GraduatePrivate230006100JaipurNo
2634PhDGovernment680008151BangaloreYes
2728GraduatePrivate310006651DelhiNo
2830BusinessBusiness500007452MumbaiYes
2935Post GraduateGovernment620008001DelhiYes
3023GraduatePrivate240006200JaipurNo
3126GraduatePrivate280006401DelhiNo
3232GovernmentGovernment530007552MumbaiYes
3336PhDGovernment740008351BangaloreYes
3424GraduatePrivate255006280DelhiNo
3527GraduateBusiness410007051PuneYes
3629Post GraduateGovernment470007302MumbaiYes
3722GraduatePrivate225006080JaipurNo
3834BusinessBusiness590007851DelhiYes
3931Post GraduateGovernment510007502MumbaiYes
4037PhDGovernment780008452BangaloreYes
4125GraduatePrivate275006350DelhiNo
4228GraduateBusiness430007151PuneYes
4330Post GraduateGovernment495007402MumbaiYes
4421GraduatePrivate215006020JaipurNo
4535PhDGovernment710008251DelhiYes
4627GraduatePrivate300006601DelhiNo
4733BusinessBusiness570007752MumbaiYes
4829Post GraduateGovernment485007352DelhiYes
4923GraduatePrivate235006180JaipurNo
5038PhDGovernment800008502BangaloreYes

Data Cleaning Required

Check the dataset for:

  • Missing values

  • Duplicate records

  • Incorrect data types


Encoding Required

Use Label Encoding for the following columns:

  • Education

  • EmploymentType

  • City

  • LoanApproved


Feature Scaling Required

Since KNN is a distance-based algorithm, apply:

  • StandardScaler (recommended)

or

  • MinMaxScaler


Features (X)

Age
Education
EmploymentType
MonthlyIncome
CreditScore
ExistingLoans
City

Target (y)

LoanApproved

Practical Questions

Question 1

Load the dataset using Pandas.

Question 2

Display the first five records.

Question 3

Display the last five records.

Question 4

Display the shape of the dataset.

Question 5

Display the information (info()) of the dataset.

Question 6

Check all missing values.

Question 7

Check duplicate records.

Question 8

Apply Label Encoding to all categorical columns.

Question 9

Separate the input features (X) and target (y).

Question 10

Split the dataset into training and testing sets (80:20).

Question 11

Apply StandardScaler to the training and testing data.

Question 12

Train a KNN Classifier with:

K = 5

Question 13

Predict the loan approval status of the test dataset.

Question 14

Calculate the model accuracy.

Question 15

Generate the confusion matrix.

Question 16

Calculate:

  • Precision

  • Recall

  • F1-Score

Question 17

Display the classification report.

Question 18

Compare the model performance for:

  • K = 3

  • K = 5

  • K = 7

  • K = 9

  • K = 11

Which value of K gives the highest accuracy?

Question 19

Predict the loan approval status of the following new customer:

AgeEducationEmploymentTypeMonthlyIncomeCreditScoreExistingLoansCity
30Post GraduateGovernment520007601Delhi


0 Comments