Mastering Classification Algorithms: When Perfect Scores Become Red Flags
Week 17 with Dataraflow: A Deep Dive into KNN, SVM, and Naive Bayes
Introduction: The Week Everything Went "Too Well"
Week 17 was supposed to be my introduction to classification algorithms. What I didn't expect was to stumble into one of the most important lessons in data science: perfect scores are usually lies.
Across six different projects, three fundamental tasks and three advanced assignments. I built ten different models. Every single one achieved 100% accuracy. Not 99.8%. Not 99%. Perfect 1.0 scores across the board.
For a beginner, this might feel like victory. For anyone who's spent time with real-world data, this should trigger alarm bells.
This week taught me three fundamental classification algorithms:
K-Nearest Neighbors (KNN) - The intuitive distance-based classifier
Support Vector Machines (SVM) - The margin-maximizing powerhouse
Naive Bayes - The probabilistic speed champion
But more importantly, it taught me when to trust perfect scores, how to validate results properly, and why simpler models sometimes deserve the win even when complex ones perform equally well.
Part 1: Fundamental Tasks
Task 1: K-Nearest Neighbors - The Perfect Score Paradox
The Challenge: Build a KNN classifier to predict customer purchase behavior based on age and annual salary.
Dataset: 100 customers, 80/20 train-test split
The Implementation
I followed the standard workflow, being careful about the naming conventions since I'd be juggling seven different datasets throughout the week:
# Load and explore the dataset
task1_df = pd.read_csv('Task-Datasets/task1_knn_customer_data.csv')
# Separate features and target
X_task1 = task1_df[['Age', 'Annual_Salary']]
y_task1 = task1_df['Purchased']
# Split the data (80/20)
X_train_task1, X_test_task1, y_train_task1, y_test_task1 = train_test_split(
X_task1, y_task1, test_size=0.2, random_state=42
)
# Feature scaling - CRITICAL for KNN
scaler_task1 = StandardScaler()
X_train_scaled_task1 = scaler_task1.fit_transform(X_train_task1)
X_test_scaled_task1 = scaler_task1.transform(X_test_task1)
# Build and train KNN model (K=5)
knn_task1 = KNeighborsClassifier(n_neighbors=5)
knn_task1.fit(X_train_scaled_task1, y_train_task1)
# Make predictions
y_pred_task1 = knn_task1.predict(X_test_scaled_task1)
The Result That Raised Questions:
--- Task 1: Performance Evaluation ---
Confusion Matrix:
[[10 0]
[ 0 10]]
Accuracy Score: 1.0
[!] AUDIT NOTE: Perfect Accuracy (1.0000) observed.
Image1:

My first reaction: Excitement! 100% accuracy!
My second reaction: Wait. Something's wrong here.
Critical Learning #1: Perfect Scores Need Validation
The warning signs were clear:
Tiny test set: Only 20 samples - one lucky/unlucky split could skew everything
Too clean: Real-world customer data is never this neat
Suspiciously perfect: No noise, no edge cases, no confusion
This is where I learned to be professionally skeptical. I implemented cross-validation:
# Perform 5-Fold Cross-Validation
cv_scores_task1 = cross_val_score(
knn_task1, X_train_scaled_task1, y_train_task1, cv=5
)
print("--- Task 1: Cross-Validation Audit ---")
print(f"Individual Fold Accuracies: {cv_scores_task1}")
print(f"Mean CV Accuracy: {cv_scores_task1.mean():.4f}")
print(f"Standard Deviation: {cv_scores_task1.std():.4f}")
The Truth Revealed:
--- Task 1: Cross-Validation Audit ---
Individual Fold Accuracies: [0.9375 1. 1. 0.875 1. ]
Mean CV Accuracy: 0.9625
Standard Deviation: 0.0500
The "Aha!" Moment:
My "perfect" 1.0 test score was just a lucky split. Cross-validation revealed:
One fold scored only 87.5% (definitely not perfect!)
Average performance: 96.25% - excellent but realistic
The model is genuinely strong, but not magically flawless
This single exercise fundamentally changed how I view model evaluation. Perfect scores on small test sets mean nothing without cross-validation.
Why Feature Scaling Matters for KNN
KNN uses Euclidean distance to find the nearest neighbors. Without scaling:
# Raw data ranges:
# Age: 20-60 (range of 40)
# Annual_Salary: 20,000-150,000 (range of 130,000)
# Problem: Salary completely dominates the distance calculation!
# The model would essentially ignore age entirely.
StandardScaler fixes this by centering features at mean=0 with std=1, giving both equal weight.
Key Takeaways:
✅ KNN requires feature scaling (distance-based algorithm)
✅ Perfect scores on small datasets need cross-validation
✅ 96.25% validated accuracy is better than 100% lucky accuracy
✅ Sample size matters: 20 test samples can give misleading results
Task 2: Support Vector Machine - Linear vs RBF Kernels
The Challenge: Implement SVM classifiers with different kernel functions to understand their impact on classification.
Dataset: 148 samples with Feature1, Feature2, and binary Class
Understanding SVM Kernels:
Linear Kernel: Finds a straight line (hyperplane) to separate classes - fast and simple
RBF (Radial Basis Function) Kernel: Maps data to higher dimensions to find complex, non-linear boundaries - more powerful but slower
The Implementation:
# Load and prepare data
task2_df = pd.read_csv('Task-Datasets/task2_svm_classification_data.csv')
X_task2 = task2_df[['Feature1', 'Feature2']]
y_task2 = task2_df['Class']
# Split and scale
X_train_task2, X_test_task2, y_train_task2, y_test_task2 = train_test_split(
X_task2, y_task2, test_size=0.2, random_state=42
)
scaler_task2 = StandardScaler()
X_train_scaled_task2 = scaler_task2.fit_transform(X_train_task2)
X_test_scaled_task2 = scaler_task2.transform(X_test_task2)
# Build LINEAR SVM
svm_linear_task2 = SVC(kernel='linear', random_state=42)
svm_linear_task2.fit(X_train_scaled_task2, y_train_task2)
# Build RBF SVM
svm_rbf_task2 = SVC(kernel='rbf', random_state=42)
svm_rbf_task2.fit(X_train_scaled_task2, y_train_task2)
Results:
Linear SVM Accuracy: 1.0
Confusion Matrix:
[[15 0]
[ 0 15]]
RBF SVM Accuracy: 1.0
Confusion Matrix:
[[15 0]
[ 0 15]]
[Image 2: confusion matrices for Linear SVM and RBF SVM, both showing perfect classification]


Critical Learning #2: When Simple Beats Complex
Both kernels achieved 100% accuracy. This reveals something important about the dataset:
The Data is Linearly Separable!
Since the Linear kernel (simpler, faster) achieved perfect accuracy, the complex RBF kernel offers no advantage here. In fact, using RBF would be:
Computationally wasteful - More processing time for no benefit
Potentially risky - More prone to overfitting on new data
Harder to interpret - Complex decision boundaries without added value
Decision Rule: Always start with Linear kernel. Only switch to RBF if Linear performs poorly.
Why Both SVMs Need Scaling:
SVM finds the maximum-margin hyperplane. Without scaling, features with larger magnitudes disproportionately influence the margin calculation.
Key Insights:
Linear SVM: Best for linearly separable data - fast and interpretable
RBF SVM: Needed when data has non-linear patterns - slower but more flexible
Occam's Razor: If simple works, don't use complex
Perfect scores here are valid: Dataset is genuinely well-separated (confirmed by balanced 74:74 class distribution)
Task 3: Naive Bayes - The Probabilistic Speed Champion
The Challenge: Build a Naive Bayes classifier for email spam detection.
Dataset: Email features including Word_Count, Link_Count, Uppercase_Ratio, Special_Char_Count, Contains_Urgent
Why Naive Bayes?
Naive Bayes is based on Bayes' Theorem and assumes features are independent (the "naive" assumption). Despite this unrealistic assumption, it works remarkably well for text classification!
The Implementation:
# Load spam detection dataset
task3_df = pd.read_csv('Task-Datasets/task3_naive_bayes_data.csv')
X_task3 = task3_df[['Word_Count', 'Link_Count', 'Uppercase_Ratio',
'Special_Char_Count', 'Contains_Urgent']]
y_task3 = task3_df['Is_Spam']
# Split data
X_train_task3, X_test_task3, y_train_task3, y_test_task3 = train_test_split(
X_task3, y_task3, test_size=0.2, random_state=42
)
# Build Gaussian Naive Bayes
nb_task3 = GaussianNB()
nb_task3.fit(X_train_task3, y_train_task3)
# Make predictions
y_pred_task3 = nb_task3.predict(X_test_task3)
Results:
Accuracy Score: 1.0
Confusion Matrix:
[[13 0]
[ 0 11]]
[Image 3: Confusion matrix for Naive Bayes spam detection showing perfect classification]

Critical Learning #3: Understanding When Scaling Matters
Naive Bayes doesn't need scaling!
Unlike KNN and SVM which use distances or margins, Naive Bayes works with probabilities. Each feature is evaluated independently, so different scales don't affect classification.
| Algorithm | Scaling Required? | Why? |
| KNN | ✅ YES | Uses Euclidean distance |
| SVM | ✅ YES | Margin calculation sensitive to scale |
| Naive Bayes | ❌ NO | Uses probabilities, not distances |
| Decision Trees | ❌ NO | Uses thresholds, not distances |
Pattern Recognition from the Data
The model learned clear spam characteristics:
Spam emails:
Shorter (avg ~80 words)
High link density (3-5 links)
Excessive uppercase (>30%)
Many special characters (!!!, $$$)
Legitimate emails:
Longer content (avg 250+ words)
Fewer links (0-1)
Normal capitalization (<10%)
Standard punctuation
Why Naive Bayes Excels Here:
⚡ Fastest training and prediction
📊 Probabilistic output (confidence scores)
🎯 Independence assumption works (each spam signal is independent)
📈 Scales well to massive datasets
Part 2: Advanced Assignments
Assignment 1: KNN Hyperparameter Optimization - Finding the Perfect K
The Challenge: Find the optimal K value for a KNN classifier predicting premium product purchases.
Dataset: E-commerce customer data with demographics and purchase history
The Optimization Process:
# Test different K values from 1 to 20
k_values = range(1, 21)
accuracy_scores = []
for k in k_values:
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train_scaled, y_train)
y_pred = knn.predict(X_test_scaled)
accuracy = accuracy_score(y_test, y_pred)
accuracy_scores.append(accuracy)
# Find optimal K
optimal_k = k_values[np.argmax(accuracy_scores)]
print(f"Optimal K Value: {optimal_k}")
# Visualize K vs Accuracy
plt.figure(figsize=(10, 6))
plt.plot(k_values, accuracy_scores, marker='o', linestyle='-', color='blue')
plt.xlabel('K Value')
plt.ylabel('Accuracy Score')
plt.title('KNN Hyperparameter Tuning: K Value vs Accuracy')
plt.grid(True, alpha=0.3)
plt.show()
Results:
Optimal K Value: 5
KNN Final Evaluation (K=5):
Accuracy: 1.0
Confusion Matrix:
[[29 0]
[ 0 21]]
[Image 4: Line plot showing accuracy scores for K values 1-20, with K=5 marked as optimal]

Critical Learning #4: Understanding the K Value Trade-off
Small K (K=1, K=3):
✅ Captures local patterns well
❌ Sensitive to noise and outliers
❌ Can overfit - memorizes training data
Large K (K=15, K=20):
✅ Smoother decision boundaries
✅ More resistant to noise
❌ Can underfit - misses local patterns
❌ Slower predictions (more neighbors to check)
Optimal K (K=5):
✅ Balanced approach
✅ Good generalization
✅ Reasonable speed
The Odd Number Rule:
Always use odd K values for binary classification to avoid ties! With K=4, you could get 2 votes for each class.
Key Insights:
K is a critical hyperparameter: Can make or break model performance
Test multiple values: Don't assume default K=5 is optimal
Visualize the trade-off: Plot helps identify the sweet spot
Cross-validation recommended: For more robust K selection
Assignment 2: SVM for Medical Diagnosis - When Stakes Are High
The Challenge: Build SVM models to diagnose medical conditions where false negatives are costly.
The Medical Context:
In healthcare:
False Negative (missed diagnosis): Patient has disease but model says healthy - DANGEROUS
False Positive (false alarm): Patient is healthy but model says diseased - Extra tests, anxiety, but safer
Comparing Multiple SVM Configurations:
# Test different SVM configurations
configs = [
('Linear (C=1)', SVC(kernel='linear', C=1, random_state=42)),
('RBF (C=1)', SVC(kernel='rbf', C=1, random_state=42)),
('RBF (C=10)', SVC(kernel='rbf', C=10, random_state=42))
]
results = []
for name, model in configs:
model.fit(X_train_scaled, y_train)
y_pred = model.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
prec = precision_score(y_test, y_pred)
rec = recall_score(y_test, y_pred)
results.append({
'Model': name,
'Accuracy': acc,
'Precision': prec,
'Recall': rec
})
comparison_df = pd.DataFrame(results)
print("--- Model Comparison Table ---")
print(comparison_df)
Results:
--- Model Comparison Table ---
Model Accuracy Precision Recall
0 Linear (C=1) 1.0 1.0 1.0
1 RBF (C=1) 1.0 1.0 1.0
2 RBF (C=10) 1.0 1.0 1.0
[Image 5: Bar chart comparing accuracy, precision, and recall across three SVM configurations, all at 1.0]

Critical Learning #5: Understanding the C Parameter
The C parameter controls the trade-off between:
Maximizing margin (wider decision boundary)
Minimizing misclassifications (tighter fit to training data)
Low C (C=0.1):
Wider margin
More tolerant of misclassifications
Less likely to overfit
Better for noisy data
High C (C=10):
Narrower margin
Strictly enforces correct classification
More likely to overfit
Better for clean data
Why All Achieved 1.0:
The medical dataset is well-separated with clear diagnostic patterns. All three configurations found perfect decision boundaries.
In Medical Context - Prioritize Recall:
For disease diagnosis, Recall (sensitivity) is most critical:
High Recall ensures we catch most actual cases (minimize false negatives)
We can afford some false positives (extra tests) to avoid missing diseases
Key Insights:
C parameter matters: Controls model complexity
Start with C=1: Default balanced approach
Increase C for clean data: Decrease C for noisy data
Medical ML priorities: Recall > Precision for disease detection
Assignment 3: Comprehensive Classifier Comparison - The Ultimate Showdown
The Challenge: Compare KNN, SVM (Linear and RBF), and Naive Bayes on a multi-class classification problem.
Dataset: 350 samples across 3 classes (Class_A, Class_B, Class_C)
The Comprehensive Comparison:
# Train all models
models = {
'KNN': KNeighborsClassifier(n_neighbors=3),
'SVM Linear': SVC(kernel='linear', random_state=42),
'SVM RBF': SVC(kernel='rbf', random_state=42),
'Naive Bayes': GaussianNB()
}
results = []
for name, model in models.items():
start_time = time.time()
model.fit(X_train_scaled, y_train)
train_time = time.time() - start_time
y_pred = model.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
prec = precision_score(y_test, y_pred, average='weighted')
rec = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average='weighted')
results.append({
'Model': name,
'Accuracy': acc,
'Precision': prec,
'Recall': rec,
'F1-Score': f1,
'Training Time': train_time
})
comparison_df = pd.DataFrame(results)
print("--- Model Comparison Table ---")
print(comparison_df)
Results:
--- Model Comparison Table ---
Model Accuracy Precision Recall F1-Score Training Time
KNN 1.0 1.0 1.0 1.0 0.009320
SVM Linear 1.0 1.0 1.0 1.0 0.011374
SVM RBF 1.0 1.0 1.0 1.0 0.007280
Naive Bayes 1.0 1.0 1.0 1.0 0.004303
Critical Learning #6: When Performance Is Equal, Speed Wins
All four models achieved perfect classification. In this scenario, the decision criteria shifts to:
1. Training Speed:
Naive Bayes: 0.0043s 🏆 (FASTEST)
SVM RBF: 0.0073s
KNN: 0.0093s
SVM Linear: 0.0114s
2. Prediction Speed (on new data):
Naive Bayes: Fastest - Simple probability calculations
SVM: Fast - Only needs support vectors
KNN: Slowest - Must compare to all training samples
3. Memory Usage:
Naive Bayes: Lowest - Only stores probability distributions
SVM: Low - Only stores support vectors
KNN: Highest - Must store entire training set
Detailed Classification Reports:
All models achieved perfect multi-class classification:
KNN (K=3) Classification Report:
precision recall f1-score support
Class_A 1.00 1.00 1.00 30
Class_B 1.00 1.00 1.00 19
Class_C 1.00 1.00 1.00 21
When to Choose Each Algorithm:
KNN:
✅ Simple to understand and explain
✅ No training required (lazy learner)
❌ Slow for large datasets
❌ Requires feature scaling
Use for: Small datasets, need interpretability
SVM Linear:
✅ Fast and efficient
✅ Works well in high dimensions
❌ Requires scaling
❌ Only for linearly separable data
Use for: Large datasets, text classification
SVM RBF:
✅ Handles non-linear patterns
✅ Powerful for complex boundaries
❌ Slower than linear
❌ More hyperparameters to tune
Use for: Complex patterns, medium datasets
Naive Bayes:
✅ Fastest training and prediction
✅ No scaling needed
✅ Probabilistic output
❌ Independence assumption may not hold
Use for: Text classification, real-time systems, large datasets
Key Insights:
Equal accuracy → Consider speed: When models perform equally, choose the fastest
Naive Bayes wins for speed: Perfect for production systems needing fast responses
KNN is slowest: Every prediction requires scanning all training data
Multi-class extends naturally: All algorithms handle 3+ classes well
Assessment - End-to-End Loan Approval System
The Ultimate Challenge: Build a complete ML pipeline for automating loan approval decisions.
Dataset: Historical loan applications with demographics, income, credit history, and approval outcomes
Section A-C: Data Loading, EDA, and Preprocessing
I approached this systematically:
Identified the key driver: Credit History had a perfect 1.0 correlation with loan approval
Recognized secondary factors: Income, education, employment years
Handled categorical variables: Used one-hot encoding with
drop_first=Trueto avoid multicollinearityApplied appropriate scaling: StandardScaler for distance-based algorithms (KNN, SVM)
EDA Findings:
Credit History dominance: Single most critical factor
Educational gap: Graduates approved significantly more
Geographic influence: Urban/Semiurban outperform Rural
Income threshold effects: Clear separation at certain income levels
Section D: Model Building
python
# D1. K-Nearest Neighbors - Tested K from 1-15
optimal_k = 1 # Found through systematic testing
# D2. Support Vector Machine - Both kernels
svm_linear = SVC(kernel='linear', random_state=42)
svm_rbf = SVC(kernel='rbf', random_state=42)
# D3. Naive Bayes
nb = GaussianNB()
Section E: Final Model Comparison
--- Model Comparison Table ---
Model Accuracy Precision Recall F1-Score Training Time
KNN 1.0 1.0 1.0 1.0 0.002194
SVM Linear 1.0 1.0 1.0 1.0 0.001541
SVM RBF 1.0 1.0 1.0 1.0 0.001767
Naive Bayes 1.0 1.0 1.0 1.0 0.001241
Section F: Final Recommendation
Winner: Gaussian Naive Bayes
Reasoning:
Performance: Perfect scores with all models, so performance is equal
Speed: Fastest at 0.0012s training time
Business Impact: In loans, false positives (denying good applicants) are costly but safer than false negatives (approving bad loans)
Scalability: Lightweight, can handle thousands of concurrent requests
Interpretability: Provides probability scores for confidence levels
Business Recommendations:
✅ Automate initial screening for high-confidence cases
✅ Monitor for feature drift (changing applicant demographics)
✅ Quarterly retraining schedule
✅ Human oversight for edge cases
⚠️ Add debt-to-income ratio and asset valuation for robustness
Code Repository
All code, analysis, and visualizations from this week are available in my Week 17 notebook. Feel free to explore, critique, and learn from my journey.
About the author
- Turning raw data into insights, models, and tools that feel human.
Comments
Join the discussionNo comments yet. Be the first to comment.