File size: 6,102 Bytes
ca25c9e addfd03 ca25c9e addfd03 ca25c9e addfd03 ca25c9e addfd03 ca25c9e addfd03 | 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | import streamlit as st
st.set_page_config(page_title="KNN: Classification & Regression")
st.title("π Understanding K-Nearest Neighbors (KNN)")
# Button-like radio selector
view = st.radio("π§ͺ Select Topic Mode", ["π About KNN Classification", "π About KNN Regression"], horizontal=True)
if view == "π About KNN Classification":
st.header("π§ KNN Classification")
st.markdown("""
KNN Classification is a **supervised learning algorithm** used to classify data points based on the majority class of their nearest neighbors.
### π How KNN Classification Works:
1. Select a value for **K** (number of nearest neighbors).
2. Calculate the **distance** between the query point and training points (using a chosen metric).
3. Identify **K nearest neighbors**.
4. Assign the **most frequent class** among those neighbors to the query point.
### β
Example Use Cases:
- Spam vs. non-spam classification
- Image recognition (e.g. handwritten digits)
- Classifying types of flowers (e.g., Iris dataset)
### π§ Important Parameters in KNN Classifier:
- **`n_neighbors`**: Number of neighbors to use. Small K may lead to overfitting, large K may underfit.
- **`weights`**: Determines how neighbors contribute to the prediction:
- `'uniform'`: All neighbors have equal influence.
- `'distance'`: Closer neighbors contribute more.
- **`algorithm`**: Strategy to compute nearest neighbors:
- `'auto'`, `'ball_tree'`, `'kd_tree'`, `'brute'`
- **`leaf_size`**: Affects tree-based search speed.
- **`p`**: Power parameter for Minkowski distance:
- `p=1`: Manhattan
- `p=2`: Euclidean (default)
- **`metric`**: Type of distance metric, e.g. `'minkowski'`, `'cosine'`, `'hamming'`
- **`n_jobs`**: Number of CPU cores to use. `-1` means use all available cores.
### π Pros:
- Simple and interpretable
- No training phase
- Good for small datasets
### β οΈ Cons:
- Slow for large datasets
- Requires scaling
- Sensitive to irrelevant features and noise
### π Hyperparameter Tuning with Optuna (Concept Only):
```python
import optuna
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score
def objective(trial):
model = KNeighborsClassifier(
n_neighbors=trial.suggest_int('n_neighbors', 1, 30),
weights=trial.suggest_categorical('weights', ['uniform', 'distance']),
p=trial.suggest_int('p', 1, 2),
algorithm=trial.suggest_categorical('algorithm', ['auto', 'ball_tree', 'kd_tree', 'brute']),
leaf_size=trial.suggest_int('leaf_size', 10, 100)
)
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=50)
```
""")
elif view == "π About KNN Regression":
st.header("π KNN Regression")
st.markdown("""
KNN Regression predicts **continuous values** by averaging the target values of the nearest neighbors.
### π How KNN Regression Works:
1. Choose a value for **K**.
2. Calculate the distance between the input and training samples.
3. Pick K nearest data points.
4. Predict the output as the **mean (or weighted mean)** of neighbors' target values.
### β
Example Use Cases:
- House price prediction
- Forecasting temperature or humidity
- Predicting sales or stock values
### π§ Important Parameters (same as Classification):
- **`n_neighbors`**: Number of neighbors used in averaging
- **`weights`**:
- `'uniform'`: Equal contribution
- `'distance'`: Nearer points have more weight
- **`algorithm`**: Nearest neighbor search strategy
- **`leaf_size`**: Tree-based algorithm speed control
- **`p`**: Distance metric power
- **`metric`**: Type of distance
- **`n_jobs`**: CPU cores to use
### π Pros:
- Non-linear model without needing equations
- Flexible and intuitive
### β οΈ Cons:
- Sensitive to irrelevant features
- Slow prediction time for large datasets
### π Hyperparameter Tuning with Optuna (Concept Only):
```python
import optuna
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import cross_val_score
def objective(trial):
model = KNeighborsRegressor(
n_neighbors=trial.suggest_int('n_neighbors', 1, 30),
weights=trial.suggest_categorical('weights', ['uniform', 'distance']),
p=trial.suggest_int('p', 1, 2),
algorithm=trial.suggest_categorical('algorithm', ['auto', 'ball_tree', 'kd_tree', 'brute']),
leaf_size=trial.suggest_int('leaf_size', 10, 100)
)
return cross_val_score(model, X_train, y_train, cv=5, scoring='neg_mean_squared_error').mean()
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=50)
```
""")
st.markdown("""
---
## π Classification vs Regression Summary
| Feature | KNN Classification | KNN Regression |
|--------------------|-----------------------------------|------------------------------------|
| Output Type | Class label (categorical) | Numeric value (continuous) |
| Decision Mechanism | Majority vote | Mean of neighbors |
| Metrics | Accuracy, F1, ROC-AUC | RMSE, MAE, RΒ² Score |
---
## π§ͺ Tips for Both Models
- **Always scale your features** using StandardScaler or MinMaxScaler.
- **Use Optuna/GridSearchCV** for tuning hyperparameters.
- **Use PCA or feature selection** in high-dimensional data.
- **Remove noise and irrelevant features** before training.
- **Use smaller datasets** or fast search algorithms for scalability.
---
β¨ KNN is a solid, interpretable, and powerful lazy-learning algorithm β especially when tuned correctly!
""")
|