Repository navigation
Expand file tree
/
Copy pathOptimizeKNN.py
More file actions
80 lines (64 loc) · 2.99 KB
/
Copy pathOptimizeKNN.py
File metadata and controls
80 lines (64 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier # Updated import for classifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, roc_auc_score
from scipy.stats import randint
def optimize_knn(train_x, train_y,test_x, test_y, fig):
# Define KNN hyperparameter search space
param_dist = {
'n_neighbors': randint(1, 20),
'weights': ['uniform', 'distance'],
'p': [1, 2] # 1 for Manhattan distance (L1), 2 for Euclidean distance (L2)
}
# Create KNN model
knn_model = KNeighborsClassifier() # Use KNeighborsClassifier
# Use RandomizedSearchCV for random search
random_search = RandomizedSearchCV(
knn_model,
param_distributions=param_dist,
n_iter=10, # Set the number of search iterations
scoring='accuracy', # Use accuracy for classification problems
cv=5, # Number of cross-validation folds
random_state=42
)
# Perform the search
random_search.fit(train_x, train_y)
# Extract the results from the random search
results_df = pd.DataFrame(random_search.cv_results_)
# Output the best parameters
best_params = random_search.best_params_
print("Evaluate K-Nearest Neighbors (KNN) Model:")
print("Best Parameters:", best_params)
# Output the performance of the best model
best_model = random_search.best_estimator_
print("Best Model Performance(accuracy):", random_search.best_score_)
# Make predictions
predictions = best_model.predict(test_x)
# Calculate evaluation metrics
accuracy = accuracy_score(test_y, predictions)
# For multiclass classification, use average='weighted' for precision, recall, and f1
precision = precision_score(test_y, predictions, average='weighted', zero_division=0)
recall = recall_score(test_y, predictions, average='weighted', zero_division=0)
f1 = f1_score(test_y, predictions, average='weighted', zero_division=0)
# Calculate AUC
if best_model.classes_.shape[0] > 2: # For multiclass classification
auc = roc_auc_score(pd.get_dummies(test_y), best_model.predict_proba(test_x), multi_class='ovr')
else: # For binary classification
auc = roc_auc_score(test_y, best_model.predict_proba(test_x)[:, 1])
# Print other metrics
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 Score: {f1:.4f}")
print(f"AUC: {auc:.4f}")
print("")
if fig:
# Visualize the relationship between 'n_neighbors' and performance
plt.figure(figsize=(10, 6))
plt.scatter(results_df['param_n_neighbors'], results_df['mean_test_score'])
plt.title('KNN Hyperparameter Tuning')
plt.xlabel('Number of Neighbors')
plt.ylabel('Accuracy')
plt.show()
return best_model