Preview:
import pandas as pd 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import StandardScaler 
from sklearn.neighbors import KNeighborsClassifier 
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report 
# Load the dataset 
df = pd.read_csv('diabetes.csv') 
# Display the first few rows to understand the dataset structure (optional) 
print(df.head()) 
# Separate features and target 
X = df.drop(columns=['Outcome'])  # Assuming 'Outcome' is the target column (0 = No Diabetes, 1 = Diabetes) 
y = df['Outcome'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the k-NN classifier 
k = 5  # You can tune this value 
knn = KNeighborsClassifier(n_neighbors=k) 
knn.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = knn.predict(X_test_scaled) 
# Calculate performance measures 
accuracy = accuracy_score(y_test, y_pred) 
precision = precision_score(y_test, y_pred) 
recall = recall_score(y_test, y_pred) 
f1 = f1_score(y_test, y_pred) 
# Display the performance measures 
print("Performance Measures for k-NN Classifier:") 
print(f"Accuracy: {accuracy:.4f}") 
print(f"Precision: {precision:.4f}") 
print(f"Recall: {recall:.4f}") 
print(f"F1-Score: {f1:.4f}") 
# Detailed classification report 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter