Question

In: Computer Science

kNN Function: Create a function called predictKNN(). Your function will return the classification of your data-pointIn...

kNN Function: Create a function called predictKNN(). Your function will return the classification of your data-pointIn addition to any parameters you see fit, your function should accept:

  • k
  • a data-point: a vector of r numbers
  • a dataframe with r columns.
    Run your function at least 5 times with different parameters.

If your data does not have a classification column, use the results from your unsupervised learning as the classification.

sl_no gender  ssc_p    ssc_b  hsc_p    hsc_b     hsc_s  degree_p   degree_t workex  etest_p specialisation  mba_p      status    salary
0        1      M  67.00   Others  91.00   Others  Commerce     58.00   Sci&Tech     No     55.0         Mkt&HR  58.80      Placed  270000.0
1        2      M  79.33  Central  78.33   Others   Science     77.48   Sci&Tech    Yes     86.5        Mkt&Fin  66.28      Placed  200000.0
2        3      M  65.00  Central  68.00  Central      Arts     64.00  Comm&Mgmt     No     75.0        Mkt&Fin  57.80      Placed  250000.0
3        4      M  56.00  Central  52.00  Central   Science     52.00   Sci&Tech     No     66.0         Mkt&HR  59.43  Not Placed       NaN
4        5      M  85.80  Central  73.60  Central  Commerce     73.30  Comm&Mgmt     No     96.8        Mkt&Fin  55.50      Placed  425000.0

Solutions

Expert Solution

SOLUTION:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix


# In os.chdir() provide the address of your working directory which is where your dataset is stored.
import os
os.chdir(r"C:\Users\LENOVO\Documents\Data Science\DataSets") 


def predictKNN(k,dataframe):
    #Loading the dataframe
    dataframe = pd.read_csv(dataframe)
    
    # Dividing dataframe into indepent variable(X) and dependent or target variable(Y)
    X = dataframe.iloc[:, :-1].values
    y = dataframe.iloc[:, -1].values
    
    # Dividing dataset into training and testing sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
    
    # Preprocessing the data
    scaler = StandardScaler()
    scaler.fit(X_train)
    X_train = scaler.transform(X_train)
    X_test = scaler.transform(X_test)
    
    #Applying KNN
    classifier = KNeighborsClassifier(n_neighbors=2)
    classifier.fit(X_train, y_train)
    y_pred = classifier.predict(X_test)
    
    # Checking the performance
    from sklearn.metrics import classification_report, confusion_matrix
    print(confusion_matrix(y_test, y_pred))
    print(classification_report(y_test, y_pred))
    
    return 

Note :

  1. In order to run successfully this code, make sure you provide right working directory and import right library functions.
  2. This code is written on assumptions that target variable column is the last column of the dataframe, incase you want another column to be your target variable then you have to manually edit X and Y.
  3. Since every dataset is unique and different you may need to do some changes in this code in order to successfully run your code, but don't worry this is the main code. You might need to do some data pre processing like converting string columns into integers one or dropping them out which again depends on your dataset and one's personal choice. If you want you can do all data preprocessing step outside the function and then pass X_train, Y_train, y_test, y_train to the function.

**Fell free to ask any queries in the comment section. I am happy to help you. if you like our work, please give Thumbs up**


Related Solutions

Using R Question 3. kNN Classification 3.1 Read in iris dataset using “data(iris)”. Describe the features...
Using R Question 3. kNN Classification 3.1 Read in iris dataset using “data(iris)”. Describe the features in the data using summary 3.2 Randomize the iris data set, mix it up and normalize it 3.3 split data into training & testing (70/30 split) 3.4 Train model in data and use crosstable function to evaluate the results 3.5 Rerun your code for K=10 and 100. Compare results and explain
In Python Create a function called ℎ?????. The function has as arguments a list called ??????...
In Python Create a function called ℎ?????. The function has as arguments a list called ?????? and a list call center. • List ?????? contains lists that represent points. o For example, if ?????? = [[4,2], [3,2], [6,1]], the list [4,2] represents the point with coordinate ? at 4 and y coordinate at 2, and so on for the other lists. Assume that all lists within points contain two numbers (that is, they have x, y coordinates). • List ??????...
knn based classification with pcasvd reduction technique apply it for classification.function parts are nedded. Write a...
knn based classification with pcasvd reduction technique apply it for classification.function parts are nedded. Write a matlab code if you know the answer then only write.or else leave it for others. image processing ELETRICAL
Your code needs to do the following: Create a function called pigLatin that accepts a string...
Your code needs to do the following: Create a function called pigLatin that accepts a string of English words in the parameter sentence and returns a string of those words translated into Pig Latin. English is translated to Pig Latin by taking the first letter of every word, moving it to the end of the word and adding ‘ay’. For example the sentence “The quick brown fox” becomes “hetay uickqay rownbay oxfay”. You may assume the words in the parameter...
In Python Create a function called ????. The function receives a "string" that represents a year...
In Python Create a function called ????. The function receives a "string" that represents a year (the variable with this "String" will be called uve) and a list containing "strings" representing bank accounts (call this list ????). • Each account is represented by 8 characters. The format of each account number is "** - ** - **", where the asterisks are replaced by numeric characters. o For example, “59-04-23”. • The two central characters of the "string" of each account...
in phyton programming: with numpy Create a function called biochild.  The function has as parameters...
in phyton programming: with numpy Create a function called biochild.  The function has as parameters the number m and the lists ??????h?? and ??????h??.  The lists ??????h?? and ??????h?? contain 0’s and 1’s.  For example: ??????h?? = [1,0,0,1,0,1] and ??????h?? = [1,1,1,0,0,1]  Both lists have the same length ?.  The 0's and 1's represent bits of information (remember that a bit is 0 or 1).  The function has to generate a new list (child)....
IN PYTHON Create a function called biochild.  The function has as parameters the number m...
IN PYTHON Create a function called biochild.  The function has as parameters the number m and the lists biomother and biofather.  The biomother and biofather lists contain 0’s and 1’s.  For example: biomother = [1,0,0,1,0,1] and biofather = [1,1,1,0,0,1]  Both lists have the same length n.  The 0's and 1's represent bits of information (remember that a bit is 0 or 1).  The function has to generate a new list (child).  The child...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called main that does the following: Creates a directory called CyberSecurity-Notes in the current working directory Within the CyberSecurity-Notes directory, creates 24 sub-directories (sub-folders), called Week 1, Week 2, Week 3, and so on until up through Week 24 Within each week directory, create 3 sub-directories, called Day 1, Day 2, and Day 3 Bonus Challenge: Add a conditional statement to abort the script if...
Please provide your own example of KNN algorithm
Please provide your own example of KNN algorithm
PYTHON PLS 1) Create a function search_by_pos. This function only has one return statement. This function...
PYTHON PLS 1) Create a function search_by_pos. This function only has one return statement. This function returns a set statement that finds out the same position and same or higher skill number. This function searches the dictionary and returns the same position and same or higher skill level. The function output the set statements that include the position only. For example input : dict = {'Fiora': {'Top': 1, 'Mid': 4, 'Bottom': 3},'Olaf': {'Top': 3, 'Mid': 2, 'Support': 4},'Yasuo': {'Mid': 2,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT