from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import…
- User
from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split, cross_val_score, KFold import matplotlib.pyplot as plt
def knn_raw_data_metrics(data): """ Perform k-NN classification on raw data and compute the confusion matrix based on the testing set.
Parameters: - data: A pandas DataFrame containing the dataset. Returns: - A dictionary containing the confusion matrix and other relevant metrics based on the testing set. """ # Split the data into features and target # TODO: Replace None with the appropriate code to extract features and target X = data.dataset(columns = "Target") y = data["Target"] # TODO: Replace None with the appropriate code to split the data # Use a fixed random_state to ensure reproducibility X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Initialize the k-NN classifier with k=5 =>n_neighbors=5 knn = KNeighborsClassifier(n_neighbors = 5) knn.fit( X_train, y_train) # TODO: Replace None with the appropriate code to fit the classifier and make predictions on the training set y_predection = knn.predict(X_test) # Compute the confusion matrix based on the testing set cm_test = confusion_matrix(y_test, y_predection) # TODO: Replace None with the appropriate code to calculate other metrics based on the testing set accuracy = accuracy_score(y_test, y_predection) * 100 precision = precision_score(y_test, y_predection, average = "binary", pos_lable = 1) * 100 recall = recall_score(y_test, y_predection, average = "binary", pos_lable = 1) * 100 # Note: Convert the metrics to percentage(out of 100) and round them to the nearest integer metrics_test = { 'accuracy': round(accuracy, 2), 'precision': round(precision, 2), 'recall': round(recall, 2), } return metrics_test, cm_testknn_raw_data_metrics(dataset)
- Assistant