Question

In: Computer Science

In Python. Create a function called predictKNN(). Your function will return the classification of your data-pointIn...

In Python. 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.

Solutions

Expert 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 :

  • In order to run successfully this code, make sure you provide right working directory and import right library functions.
  • 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.
  • 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.

I am attaching the code where I used diabetes dataset saved in my pc


Related Solutions

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...
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 ??????...
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 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...
Python pls create a function called search_position. This function returns a list. team1 = {'Fiora': {'Top':...
Python pls create a function called search_position. This function returns a list. team1 = {'Fiora': {'Top': 1, 'Mid': 4, 'Bottom': 3},'Olaf': {'Top': 3, 'Mid': 2, 'Support': 4},'Yasuo': {'Mid': 2, 'Top': 5},'Shaco': {'Jungle': 4, 'Top': 2, 'Mid': 1}} def search_position(team1): returns [(5, [('Top', ['Yasuo'])]), (4, [('Mid', ['Fiora']), ('Support',['Olaf']), ('Jungle',['Shaco'])])   (3, [('Bottom', ['Fiora']), ('Top', ['Olaf'])]), (2, [('Mid', ['Olaf','Yasuo']), ('Top', ['Shaco'])]), (1, [('Mid', ['Shaco'])])]
Python pls create a function called search_position. This function returns a dictionary. team1 = {'Fiora': {'Top':...
Python pls create a function called search_position. This function returns a dictionary. team1 = {'Fiora': {'Top': 1, 'Mid': 4, 'Bottom': 3},'Olaf': {'Top': 3, 'Mid': 2, 'Support': 4},'Yasuo': {'Mid': 2, 'Top': 5},'Shaco': {'Jungle': 4, 'Top': 2, 'Mid': 1}} def search_position(team1): should return {'Top': {'Fiora': 1, 'Yasuo':5,'Olaf':3,'Shaco':}, 'Jungle': {'Shaco': 4}, 'Mid': {'Yasuo', 2, 'Fiora': 4,'Olaf':2}, 'Bottom': {'Fiora': 3}, 'Support': {'Olaf': 4}} *******IMPORTANT*************** The result should be alphabetical order.
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,...
PYTHON: This is the posted problem: General Instructions Create a function called DeterminePrice that will determine...
PYTHON: This is the posted problem: General Instructions Create a function called DeterminePrice that will determine the cost of purchased software. The price is of the software is $350 per license. However, when purchased in larger quantities a discount is given. For quantites less than 10 copies, there is no discount. For quantities greater than 10 and less than and including 20, a 10% discount is given. For quantities greater than 20 and less than and including 30, a discount...
Python Create a move function that is only defined in the base class called Objects. The...
Python Create a move function that is only defined in the base class called Objects. The move function will take two parameters x,y and will also return the updated x,y parameters.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT