Question

Using the data in the attached table info.csv Find the k-nearest neighbors for record #10 using...

Using the data in the attached table info.csv

Find the k-nearest neighbors for record #10 using k = 3

Write a Python 3 program that solves the above problem

Python program must read the info.csv file from within the program

The info.csv file contains the following data table

1, 22, Single, 46156.98, Bad loss

2, 33, Married, 24188.10, Bad loss

3, 28, Other, 28787.34, Bad loss

4, 51, Other, 23886.72, Bad loss

5, 25, Single, 47281.44, Bad loss

6, 39, Single, 33994.90, Good risk

7, 54, Single, 28716.50, Good risk

8, 55, Married, 49186.75, Good risk

9, 50, Married, 46726.50, Good risk

10, 66, Married, 36120.34, Good risk

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

# importing the required libraries

import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
from sklearn import preprocessing
# Storing the data provided and converting it to dataframe

data= [[1, 22, "Single", 46156.98, "Bad loss"],[2, 33, "Married", 24188.10, "Bad loss"],[3, 28, "Other", 28787.34, "Bad loss"],
[4, 51, "Other", 23886.72, "Bad loss"],[5, 25, "Single", 47281.44, "Bad loss"],[6, 39, "Single", 33994.90, "Good risk"],
[7, 54, "Single", 28716.50, "Good risk"],[8, 55, "Married", 49186.75, "Good risk"],[9, 50, "Married", 46726.50, "Good risk"],
[10, 66, "Married", 36120.34, "Good risk"]]

df = pd.DataFrame(data, columns = ['rec','Age', 'Status', 'val', 'risk'])

# droping(deleting) the column representing the record number since it is managed by the df.

df.drop(columns=['rec'])
#converting string values to integer so that it can be operated by the model

le = preprocessing.LabelEncoder()

le.fit(df.Status)
df.Status = le.transform(df.Status)

le.fit(df.risk)
df.risk = le.transform(df.risk)

df
# creating the model and fitting into the model

neigh = NearestNeighbors(n_neighbors=3)
neigh.fit(df)
# 1st array represents the distance and second shows the record number (starting from 0) from which the distance is displayed

print(neigh.kneighbors(df.loc[[9]]))

Add a comment
Know the answer?
Add Answer to:
Using the data in the attached table info.csv Find the k-nearest neighbors for record #10 using...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT