<jupyter_start><jupyter_text>______Copyright by <NAME> Inc.For more information, visit us at www.pieriandata.com  KNN Project Exercise - SolutionsDue to the simplicity of KNN for Classification, let's focus on using a PipeLine and a GridSearchCV tool, since these skills can be generalized for any model.  The Sonar Data  Detecting a Rock or a MineSonar (sound navigation ranging) is a technique that uses sound propagation (usually underwater, as in submarine navigation) to navigate, communicate with or detect objects on or under the surface of the water, such as other vessels.The data set contains the response metrics for 60 separate sonar frequencies sent out against a known mine field (and known rocks). These frequencies are then labeled with the known object they were beaming the sound at (either a rock or a mine). Our main goal is to create a machine learning model capable of detecting the difference between a rock or a mine based on the response of the 60 separate sonar frequencies.Data Source: https://archive.ics.uci.edu/ml/datasets/Connectionist+Bench+(Sonar,+Mines+vs.+Rocks) Complete the Tasks in bold**TASK: Run the cells below to load the data.**<jupyter_code>import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('../DATA/sonar.all-data.csv')
df.head()<jupyter_output><empty_output><jupyter_text>Data Exploration**TASK: Create a heatmap of the correlation between the difference frequency responses.**<jupyter_code># CODE HERE
plt.figure(figsize=(8,6))
sns.heatmap(df.corr(),cmap='coolwarm')<jupyter_output><empty_output><jupyter_text>**TASK: What are the top 5 correlated frequencies with the target\label?***Note: You many need to map the label to 0s and 1s.**Additional Note: We're looking for **absolute** correlation values.*<jupyter_code>#CODE HERE
df['Target'] = df['Label'].map({'R':0,'M':1})
np.abs(df.corr()['Target']).sort_values().tail(6)<jupyter_output><empty_output><jupyter_text>Train | Test SplitOur approach here will be one of using Cross Validation on 90% of the dataset, and then judging our results on a final test set of 10% to evaluate our model.**TASK: Split the data into features and labels, and then split into a training set and test set, with 90% for Cross-Validation training, and 10% for a final test set.**<jupyter_code># CODE HERE
from sklearn.model_selection import train_test_split 
X = df.drop(['Target','Label'],axis=1)
y = df['Label']
X_cv, X_test, y_cv, y_test = train_test_split(X, y, test_size=0.1, random_state=42)<jupyter_output><empty_output><jupyter_text>**TASK: Create a PipeLine that contains both a StandardScaler and a KNN model**<jupyter_code>from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
scaler = StandardScaler()
knn = KNeighborsClassifier()
operations = [('scaler',scaler),('knn',knn)]
from sklearn.pipeline import Pipeline
pipe = Pipeline(operations)<jupyter_output><empty_output><jupyter_text>**TASK: Perform a grid-search with the pipeline to test various values of k and report back the best performing parameters.**<jupyter_code>from sklearn.model_selection import GridSearchCV
k_values = list(range(1,30))
param_grid = {'knn__n_neighbors': k_values}
full_cv_classifier = GridSearchCV(pipe,param_grid,cv=5,scoring='accuracy')
full_cv_classifier.fit(X_cv,y_cv)
full_cv_classifier.best_estimator_.get_params()<jupyter_output><empty_output><jupyter_text>**(HARD) TASK: Using the .cv_results_ dictionary, see if you can create a plot of the mean test scores per K value.**<jupyter_code>#CODE HERE
full_cv_classifier.cv_results_['mean_test_score']
scores = full_cv_classifier.cv_results_['mean_test_score']
plt.plot(k_values,scores,'o-')
plt.xlabel("K")
plt.ylabel("Accuracy")<jupyter_output><empty_output><jupyter_text>Final Model Evaluation**TASK: Using the grid classifier object from the previous step, get a final performance classification report and confusion matrix.**<jupyter_code>#Code Here
pred = full_cv_classifier.predict(X_test)
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
confusion_matrix(y_test,pred)
print(classification_report(y_test,pred))<jupyter_output>precision    recall  f1-score   support

           M       0.92      0.92      0.92        13
           R       0.88      0.88      0.88         8

    accuracy                           0.90        21
   macro avg       0.90      0.90      0.90        21
weighted avg       0.90      0.90      0.90        21
StarcoderdataJupyterStructuredCleanDedup