Download pages/Algorithms.py from Phaneendrabayi/Zero_To_Hero_Machine_Learning: direct link, hf CLI and curl.
- Browser
- Download file 34.9 kB
-
https://huggingface.co/spaces/Phaneendrabayi/Zero_To_Hero_Machine_Learning/resolve/main/pages/Algorithms.py
- Command line
-
hf download hf://spaces/Phaneendrabayi/Zero_To_Hero_Machine_Learning/pages/Algorithms.py
-
curl -L -o Algorithms.py https://huggingface.co/spaces/Phaneendrabayi/Zero_To_Hero_Machine_Learning/resolve/main/pages/Algorithms.py
34.9 kB
| import streamlit as st | |
| import pandas as pd | |
| st.set_page_config(page_title="ML Model Explorer") | |
| # Sidebar for algorithm selection | |
| algorithm = st.sidebar.radio( | |
| "π Choose an ML Algorithm to Explore:", | |
| [ | |
| "Linear Regression", | |
| "Logistic Regression", | |
| "KNN", | |
| "SVM", | |
| "DecisionTree", | |
| "Random Forest", | |
| "Ensemble Techniques" | |
| ] | |
| ) | |
| # Title | |
| if algorithm == "Linear Regression": | |
| st.title("π Linear Regression") | |
| st.markdown(""" | |
| ## π What is Linear Regression? | |
| ##### Linear Regression is a **supervised learning algorithm** used for predicting **continuous numerical values**. It models the relationship between one or more input features (independent variables) and a target variable (dependent variable) by fitting a **linear equation** to the observed data. | |
| Types of Linear Regression: | |
| - **Simple Linear Regression**: One feature (X) and one target (y) | |
| - **Multiple Linear Regression**: Multiple features (X1, X2, ..., Xn) and one target (y) | |
| --- | |
| ## π Mathematical Formulation | |
| The hypothesis function in Linear Regression is given by: | |
| \[ y = w_1x_1 + w_2x_2 + ... + w_nx_n + b = w^T x + b \] | |
| Where: | |
| - `x`: input features | |
| - `w`: weights/coefficients | |
| - `b`: bias or intercept | |
| - `y`: predicted output | |
| The model is trained using **Ordinary Least Squares (OLS)** to minimize the **Mean Squared Error (MSE)**: | |
| \text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2 | |
| --- | |
| ## π Key Concepts | |
| ### 1. **Least Squares Estimation** | |
| Method to minimize the sum of squared differences between actual and predicted values. | |
| ### 2. **Residuals** | |
| Difference between actual and predicted values: \( e_i = y_i - \hat{y}_i \) | |
| ### 3. **R-squared (RΒ²)** | |
| Indicates the proportion of variance in the target variable explained by the model: | |
| \[ R^2 = 1 - \frac{\text{SSR}}{\text{SST}} \] | |
| ### 4. **Assumptions** | |
| - **Linearity**: Target has a linear relationship with inputs | |
| - **Independence**: Observations are independent | |
| - **Homoscedasticity**: Constant variance in errors | |
| - **Normality**: Residuals are normally distributed | |
| - **No multicollinearity**: Independent variables are not highly correlated | |
| --- | |
| ### βοΈ Hyperparameters (Scikit-learn `LinearRegression`) | |
| | Hyperparameter | Description | | |
| |--------------------|-----------------------------------------------------------------------------| | |
| | `fit_intercept` | If True, model calculates intercept. If False, no intercept added. | | |
| | `copy_X` | If True, X is copied; if False, changes X in-place for efficiency. | | |
| | `n_jobs` | Number of CPU cores used. -1 uses all available processors. | | |
| **Note**: `normalize` is deprecated. Use `StandardScaler` or pipelines for preprocessing. | |
| --- | |
| ### βοΈ Advantages | |
| - Easy to implement | |
| - Interpretable coefficients | |
| - Requires less computational resources | |
| - Fast training time | |
| ### π« Limitations | |
| - Assumes linearity | |
| - Sensitive to outliers | |
| - Poor with irrelevant or highly correlated features | |
| - Can underperform on complex datasets | |
| --- | |
| ### π§ͺ Hyperparameter Tuning with Optuna (Conceptual) | |
| Although Linear Regression itself has few tunable parameters, Optuna can be valuable in these contexts: | |
| - **Polynomial Regression**: Tune the degree of the polynomial | |
| - **Regularized models** (e.g., Ridge, Lasso): Tune `alpha`, `l1_ratio` | |
| - **Feature Engineering**: Select optimal features for better prediction | |
| Optuna uses **Bayesian Optimization** to explore parameter space and optimize a target metric (e.g., RMSE). | |
| --- | |
| ### π‘ Real-World Applications | |
| - Forecasting sales based on trends and features | |
| - Predicting house prices by area, bedrooms, location | |
| - Estimating insurance or healthcare costs | |
| - Demand prediction in supply chain analytics | |
| π **Best Practice**: Always visualize residuals and check assumptions. Consider using cross-validation and pipelines. | |
| """) | |
| elif algorithm == "Logistic Regression": | |
| st.title("π Logistic Regression - Classifier") | |
| st.header("π Logistic Regression - In Depth") | |
| st.markdown(""" | |
| ## π What is Logistic Regression? | |
| ###### Logistic Regression is a **supervised learning** algorithm used for **binary or multi-class classification** tasks. Despite the name, it's a classification algorithm (not regression). | |
| It predicts the **probability** of a class label using the **logistic (sigmoid)** function. | |
| --- | |
| ## π Mathematical Formulation | |
| The model predicts: | |
| \[ P(y=1|x) = \frac{1}{1 + e^{-z}} \quad \text{where} \quad z = w^Tx + b \] | |
| - `x`: input features | |
| - `w`: weights | |
| - `b`: bias | |
| - `sigmoid(z)`: squashes values between 0 and 1 | |
| --- | |
| ## π Key Concepts | |
| - **Linear Decision Boundary**: Separates classes using a straight line/hyperplane. | |
| - **Sigmoid Activation**: Converts linear output into probability. | |
| - **Cross Entropy Loss**: Cost function to optimize. | |
| - **Maximum Likelihood Estimation (MLE)**: Estimates the best-fit parameters. | |
| --- | |
| ## π§ Hyperparameters Explained | |
| | Parameter | Description | | |
| |-----------|-------------| | |
| | `penalty` | Regularization method (`l1`, `l2`, `elasticnet`, `none`). | | |
| | `C` | Inverse of regularization strength. Smaller values mean stronger regularization. | | |
| | `solver` | Algorithm to optimize weights (e.g., `liblinear`, `saga`, `lbfgs`). | | |
| | `max_iter` | Maximum number of iterations for convergence. | | |
| | `fit_intercept` | Whether to include the bias term. | | |
| | `class_weight` | Assigns weights to classes (e.g., `balanced` handles imbalanced data). | | |
| | `multi_class` | Type of classification problem (`ovr`, `multinomial`). | | |
| --- | |
| ## β Advantages | |
| - Simple and efficient for binary classification. | |
| - Outputs probability values. | |
| - Works well when the relationship is approximately linear. | |
| ## β Disadvantages | |
| - Not suitable for non-linear problems (unless using feature engineering). | |
| - Assumes no multicollinearity and linear separability. | |
| --- | |
| ## π§ͺ Optuna for Hyperparameter Tuning (Explanation Only) | |
| - `Optuna` is a powerful library for **automated hyperparameter optimization**. | |
| - For Logistic Regression, Optuna can help optimize: | |
| - `C` (regularization strength) | |
| - `solver` | |
| - `penalty` | |
| - Objective: **maximize validation accuracy** or **F1-score**. | |
| It performs trials to find the best parameter combination, using techniques like TPE (Tree Parzen Estimator). | |
| --- | |
| ## π Use Cases | |
| - Spam detection | |
| - Medical diagnosis (disease prediction) | |
| - Customer churn prediction | |
| - Credit risk assessment | |
| --- | |
| π **Tip**: Scale your data before applying Logistic Regression (especially with `l1` or `l2` regularization). | |
| """) | |
| elif algorithm == "KNN": | |
| 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! | |
| """) | |
| elif algorithm == "SVM": | |
| import pandas as pd | |
| st.title("π€ Support Vector Machine (SVM) - In Depth") | |
| st.markdown(""" | |
| Support Vector Machine (SVM) is a **supervised learning algorithm** used for both **classification** and **regression** tasks. It finds the optimal hyperplane that best separates data points of different classes (in classification) or fits the best margin for predicting continuous values (in regression). | |
| --- | |
| ## π Key Concepts | |
| ### 1. **Hyperplane** | |
| A decision boundary that separates different classes. In higher dimensions, it's a plane or manifold. | |
| ### 2. **Support Vectors** | |
| The data points that are closest to the hyperplane and influence its position. | |
| ### 3. **Margin** | |
| The distance between the hyperplane and the nearest data points (support vectors). SVM maximizes this margin. | |
| --- | |
| ## π Mathematical Formulation | |
| ### Classification Objective: | |
| For a binary classification task with input vector `x`, label `y β {-1, 1}`: | |
| SVM aims to solve: | |
| \[ \min_{w, b} \ \frac{1}{2} \|w\|^2 \quad \text{subject to} \quad y_i(w^T x_i + b) \geq 1 \] | |
| ### Regression (SVR) Objective: | |
| Support Vector Regression (SVR) aims to find a function that deviates from the actual values by a margin \( \varepsilon \): | |
| \[ \min_{w, b} \ \frac{1}{2} \|w\|^2 \quad \text{subject to} \quad |y_i - (w^T x_i + b)| \leq \varepsilon \] | |
| --- | |
| ## βοΈ SVM Kernels | |
| Kernels transform data into higher dimensions to make it linearly separable: | |
| - **Linear Kernel**: \( K(x, x') = x^T x' \) | |
| - **Polynomial Kernel**: \( K(x, x') = (\gamma x^T x' + r)^d \) | |
| - **RBF (Gaussian) Kernel**: \( K(x, x') = \exp(-\gamma \|x - x'\|^2) \) | |
| - **Sigmoid Kernel**: \( K(x, x') = \tanh(\gamma x^T x' + r) \) | |
| --- | |
| ## π Hyperparameters of SVM (`sklearn.svm.SVC` and `SVR`) | |
| | Parameter | Description | | |
| |----------------|-------------| | |
| | `C` | Regularization parameter. High value = low bias, high variance | | |
| | `kernel` | Type of kernel function (linear, poly, rbf, sigmoid) | | |
| | `degree` | Degree for polynomial kernel | | |
| | `gamma` | Kernel coefficient for 'rbf', 'poly', and 'sigmoid' | | |
| | `coef0` | Independent term in kernel function (used with 'poly' and 'sigmoid') | | |
| | `epsilon` | (SVR only) Epsilon-tube within which no penalty is associated | | |
| | `shrinking` | Whether to use shrinking heuristic | | |
| | `probability` | Enable probability estimates (slower) | | |
| --- | |
| ### π§ͺ Hyperparameter Tuning with Optuna (Conceptual) | |
| Optuna can help optimize: | |
| - `C` and `gamma` values | |
| - Kernel type | |
| - `degree` and `coef0` for poly/sigmoid kernels | |
| - Cross-validation scores (accuracy, RMSE) | |
| Optuna uses **Bayesian Optimization** to efficiently explore the parameter space. | |
| --- | |
| ### β Advantages | |
| - Effective in high-dimensional spaces | |
| - Memory efficient (uses support vectors only) | |
| - Works with nonlinear data using kernels | |
| ### π« Limitations | |
| - Not suitable for very large datasets | |
| - Choosing the right kernel and parameters can be tricky | |
| - Less interpretable compared to tree-based models | |
| --- | |
| ### π‘ Real-World Applications | |
| - Email spam detection | |
| - Image classification | |
| - Stock price prediction (SVR) | |
| - Face and handwriting recognition | |
| π **Tip**: Always scale features (e.g., StandardScaler) before using SVM for optimal performance. | |
| """) | |
| elif algorithm == "DecisionTree": | |
| st.title("π³ Understanding Decision Tree Algorithms") | |
| # Button-like radio selector | |
| view = st.radio("π§ͺ Select Topic Mode", ["π About Decision Tree Classification", "π About Decision Tree Regression"], horizontal=True) | |
| if view == "π About Decision Tree Classification": | |
| st.header("π§ Decision Tree Classification") | |
| st.markdown(""" | |
| Decision Tree Classification is a **supervised learning algorithm** used for classifying data by learning simple decision rules inferred from the data features. | |
| ### π How Decision Tree Classification Works: | |
| 1. Select the **best feature** to split the dataset based on a criterion (e.g., Gini impurity or entropy). | |
| 2. Split the dataset into subsets. | |
| 3. Repeat recursively for each subset until the stopping condition is met (e.g., max depth, minimum samples). | |
| ### β Example Use Cases: | |
| - Medical diagnosis (disease prediction) | |
| - Customer churn prediction | |
| - Loan approval classification | |
| ### π§ Important Parameters in `DecisionTreeClassifier`: | |
| - **`criterion`**: Metric to evaluate the quality of a split: | |
| - `'gini'`: Gini Impurity (default) | |
| - `'entropy'`: Information Gain | |
| - **`max_depth`**: Maximum depth of the tree | |
| - **`min_samples_split`**: Minimum number of samples to split an internal node | |
| - **`min_samples_leaf`**: Minimum number of samples in a leaf node | |
| - **`max_features`**: Number of features to consider when looking for the best split | |
| - **`random_state`**: Controls the randomness of the estimator | |
| ### π Pros: | |
| - Easy to understand and interpret | |
| - Requires little data preparation | |
| - Handles both numerical and categorical data | |
| ### β οΈ Cons: | |
| - Prone to overfitting | |
| - Unstable with small data changes | |
| - Biased with imbalanced datasets | |
| ### π Hyperparameter Tuning with Optuna (Example with Iris Dataset): | |
| ```python | |
| import optuna | |
| from sklearn.datasets import load_iris | |
| from sklearn.model_selection import train_test_split, cross_val_score | |
| from sklearn.tree import DecisionTreeClassifier | |
| # Load and split data | |
| data = load_iris() | |
| X_train, _, y_train, _ = train_test_split(data.data, data.target, test_size=0.2, random_state=42) | |
| def objective(trial): | |
| model = DecisionTreeClassifier( | |
| criterion=trial.suggest_categorical('criterion', ['gini', 'entropy']), | |
| max_depth=trial.suggest_int('max_depth', 1, 20), | |
| min_samples_split=trial.suggest_int('min_samples_split', 2, 20), | |
| min_samples_leaf=trial.suggest_int('min_samples_leaf', 1, 20), | |
| max_features=trial.suggest_categorical('max_features', ['auto', 'sqrt', 'log2', None]), | |
| random_state=42 | |
| ) | |
| 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 Decision Tree Regression": | |
| st.header("π Decision Tree Regression") | |
| st.markdown(""" | |
| Decision Tree Regression is used for **predicting continuous values** by learning decision rules that split data to minimize variance. | |
| ### π How Decision Tree Regression Works: | |
| 1. The dataset is split based on a feature that minimizes variance (MSE). | |
| 2. These splits form decision nodes and terminal leaves with average target values. | |
| 3. Recursively build the tree until the stopping condition is reached. | |
| ### β Example Use Cases: | |
| - Predicting housing prices | |
| - Estimating demand or consumption | |
| - Financial forecasting | |
| ### π§ Important Parameters in `DecisionTreeRegressor`: | |
| - **`criterion`**: Function to measure the quality of a split: | |
| - `'squared_error'`, `'absolute_error'`, `'friedman_mse'`, `'poisson'` | |
| - **`max_depth`**, **`min_samples_split`**, **`min_samples_leaf`**, **`max_features`**, **`random_state`** (same as classifier) | |
| ### π Pros: | |
| - Simple and non-linear relationships can be captured | |
| - No need for feature scaling | |
| - Flexible to feature types | |
| ### β οΈ Cons: | |
| - Overfitting is common without pruning | |
| - Sensitive to outliers and noise | |
| ### π Hyperparameter Tuning with Optuna (Example with California Housing Dataset): | |
| ```python | |
| import optuna | |
| from sklearn.datasets import fetch_california_housing | |
| from sklearn.model_selection import train_test_split, cross_val_score | |
| from sklearn.tree import DecisionTreeRegressor | |
| # Load and split data | |
| data = fetch_california_housing() | |
| X_train, _, y_train, _ = train_test_split(data.data, data.target, test_size=0.2, random_state=42) | |
| def objective(trial): | |
| model = DecisionTreeRegressor( | |
| criterion=trial.suggest_categorical('criterion', ['squared_error', 'friedman_mse', 'absolute_error']), | |
| max_depth=trial.suggest_int('max_depth', 1, 20), | |
| min_samples_split=trial.suggest_int('min_samples_split', 2, 20), | |
| min_samples_leaf=trial.suggest_int('min_samples_leaf', 1, 20), | |
| max_features=trial.suggest_categorical('max_features', ['auto', 'sqrt', 'log2', None]), | |
| random_state=42 | |
| ) | |
| 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 | Decision Tree Classification | Decision Tree Regression | | |
| |--------------------|----------------------------------|------------------------------------| | |
| | Output Type | Class label (categorical) | Numeric value (continuous) | | |
| | Decision Mechanism | Gini/Entropy-based Splits | MSE/MAE-based Splits | | |
| | Metrics | Accuracy, F1, ROC-AUC | RMSE, MAE, RΒ² Score | | |
| --- | |
| ## π§ͺ Tips for Both Models | |
| - **Prune your tree** with max depth or minimum samples. | |
| - **Use GridSearchCV or Optuna** for hyperparameter tuning. | |
| - **Be cautious of overfitting**, especially on small datasets. | |
| - **Visualize trees** with `plot_tree` from `sklearn.tree`. | |
| --- | |
| β¨ Decision Trees offer an intuitive, powerful approach to both classification and regression β especially when tuned and interpreted effectively! | |
| """) | |
| elif algorithm == "Ensemble Techniques": | |
| st.title("π§ Ensemble Machine Learning Techniques") | |
| # Topic selector | |
| view = st.radio("π Select Ensemble Technique", [ | |
| "π³ Random Forest (Classification)", | |
| "π³ Random Forest (Regression)", | |
| "π² Gradient Boosting (Classification)", | |
| "π² Gradient Boosting (Regression)", | |
| "π₯ AdaBoost (Classification)", | |
| "π₯ AdaBoost (Regression)" | |
| ], horizontal=True) | |
| if view == "π³ Random Forest (Classification)": | |
| st.header("π³ Random Forest Classifier") | |
| st.markdown(""" | |
| Random Forest is an ensemble method that builds multiple **decision trees** and combines their results to improve accuracy and reduce overfitting. | |
| ### π How it Works: | |
| - Trains multiple decision trees on bootstrapped samples. | |
| - Each tree votes; majority class wins. | |
| ### β Use Cases: | |
| - Spam detection | |
| - Medical diagnosis | |
| ### π§ Key Parameters: | |
| - `n_estimators`: Number of trees in the forest. | |
| - `max_depth`: Maximum depth of each tree. | |
| - `min_samples_split`: Minimum samples to split a node. | |
| - `min_samples_leaf`: Minimum samples in a leaf node. | |
| - `max_features`: Number of features to consider when looking for best split. | |
| - `bootstrap`: Whether bootstrap samples are used. | |
| ### Pros: | |
| - Handles high-dimensional data well | |
| - Reduces variance (robust to overfitting) | |
| ### Cons: | |
| - Slower for real-time predictions | |
| - Can be less interpretable | |
| """) | |
| elif view == "π³ Random Forest (Regression)": | |
| st.header("π³ Random Forest Regressor") | |
| st.markdown(""" | |
| Random Forest for regression aggregates the output of multiple regression trees by **averaging their outputs**. | |
| ### π How it Works: | |
| - Each tree predicts a value. | |
| - Final output = average of all tree outputs. | |
| ### β Use Cases: | |
| - Price prediction | |
| - Forecasting trends | |
| ### π§ Key Parameters: | |
| - Same as classifier (`n_estimators`, `max_depth`, etc.) | |
| ### Pros: | |
| - Captures complex relationships | |
| - Handles non-linearity well | |
| ### Cons: | |
| - Slower than simpler models | |
| - Overfitting if not tuned properly | |
| """) | |
| elif view == "π² Gradient Boosting (Classification)": | |
| st.header("π² Gradient Boosting Classifier") | |
| st.markdown(""" | |
| Gradient Boosting is a sequential ensemble technique that builds trees one after another, **each trying to correct the error** of the previous one. | |
| ### π How it Works: | |
| - Uses gradient descent to minimize the loss. | |
| - Trees are shallow (weak learners). | |
| ### β Use Cases: | |
| - Customer churn prediction | |
| - Credit scoring | |
| ### π§ Key Parameters: | |
| - `n_estimators`: Number of boosting stages. | |
| - `learning_rate`: Shrinks the contribution of each tree. | |
| - `max_depth`: Depth of each individual tree. | |
| - `subsample`: Fraction of samples used for fitting. | |
| ### Pros: | |
| - High accuracy | |
| - Handles mixed data well | |
| ### Cons: | |
| - Sensitive to hyperparameters | |
| - Can overfit on noisy data | |
| """) | |
| elif view == "π² Gradient Boosting (Regression)": | |
| st.header("π² Gradient Boosting Regressor") | |
| st.markdown(""" | |
| Similar to classification but optimized for **continuous values** using gradient descent on regression loss functions. | |
| ### β Use Cases: | |
| - Demand forecasting | |
| - House price prediction | |
| ### π§ Parameters: | |
| - Same as classification (`n_estimators`, `learning_rate`, etc.) | |
| ### Pros: | |
| - Excellent performance on tabular data | |
| ### Cons: | |
| - Training is slower | |
| """) | |
| elif view == "π₯ AdaBoost (Classification)": | |
| st.header("π₯ AdaBoost Classifier") | |
| st.markdown(""" | |
| AdaBoost stands for **Adaptive Boosting**. It combines weak learners sequentially, **giving more weight to misclassified instances**. | |
| ### π How it Works: | |
| - Learns sequentially. | |
| - Harder instances are focused in later learners. | |
| ### β Use Cases: | |
| - Fraud detection | |
| - Face detection | |
| ### π§ Key Parameters: | |
| - `n_estimators`: Number of weak learners. | |
| - `learning_rate`: Weight given to each learner. | |
| - `base_estimator`: Default is decision stump. | |
| ### Pros: | |
| - Simple and effective | |
| - Works well with fewer features | |
| ### Cons: | |
| - Sensitive to noise | |
| - Poor with complex data unless base estimator is strong | |
| """) | |
| elif view == "π₯ AdaBoost (Regression)": | |
| st.header("π₯ AdaBoost Regressor") | |
| st.markdown(""" | |
| Boosts weak regressors sequentially, correcting residual errors of previous models. | |
| ### β Use Cases: | |
| - Stock price prediction | |
| - Insurance risk modeling | |
| ### π§ Parameters: | |
| - Same as classifier (`n_estimators`, `learning_rate`, `loss`, etc.) | |
| ### Pros: | |
| - Robust to overfitting if tuned | |
| ### Cons: | |
| - Sensitive to outliers | |
| """) | |
| st.markdown(""" | |
| --- | |
| π **Note**: Ensemble methods perform better with **hyperparameter tuning**. Use tools like `Optuna`, `GridSearchCV`, or `RandomizedSearchCV` to find the best model parameters. | |
| π **Pro Tip**: Feature importance scores from tree-based models help in **feature selection** and **interpretability**. | |
| """) | |
| elif algorithm == "Random Forest": | |
| st.title("π³ Random Forest Algorithm - Classifier & Regressor") | |
| # Topic selector | |
| view = st.radio("π Select Task Type", [ | |
| "π³ Random Forest Classifier", | |
| "π³ Random Forest Regressor" | |
| ], horizontal=True) | |
| if view == "π³ Random Forest Classifier": | |
| st.header("π³ Random Forest Classifier - In Depth") | |
| st.markdown(""" | |
| ## π What is Random Forest Classifier? | |
| A Random Forest Classifier is an ensemble learning method that constructs multiple decision trees on various sub-samples of the dataset and uses **majority voting** for classification. | |
| --- | |
| ## π§ Key Concepts | |
| - **Bootstrap Aggregation (Bagging)**: Training data is sampled with replacement to build multiple trees. | |
| - **Feature Randomness**: Each split only considers a random subset of features. | |
| - **Majority Voting**: Predictions from all trees are combined by majority vote. | |
| --- | |
| ## β Advantages | |
| - Handles large datasets efficiently. | |
| - Reduces overfitting compared to a single decision tree. | |
| - Automatically handles missing values and maintains accuracy. | |
| ## β Disadvantages | |
| - Not interpretable like a decision tree. | |
| - Can be slow with a large number of trees. | |
| --- | |
| ## π§ Hyperparameters Explained | |
| | Parameter | Description | | |
| |-----------|-------------| | |
| | `n_estimators` | Number of trees in the forest (more trees can improve performance but slow down computation). | | |
| | `criterion` | Splitting metric (`gini`, `entropy`). | | |
| | `max_depth` | Maximum depth of each tree (limits model complexity). | | |
| | `min_samples_split` | Minimum samples required to split a node. | | |
| | `min_samples_leaf` | Minimum samples required in a leaf node. | | |
| | `max_features` | Number of features considered when splitting a node. | | |
| | `bootstrap` | Whether bootstrap samples are used. | | |
| | `oob_score` | Use out-of-bag samples to estimate accuracy. | | |
| --- | |
| ## π§ͺ Optuna for Hyperparameter Tuning (Explanation) | |
| - `Optuna` is a Python library for hyperparameter optimization using intelligent sampling. | |
| - It builds a search space, samples combinations, and optimizes performance metrics. | |
| - Best suited for finding optimal values of: | |
| - `n_estimators`, `max_depth` | |
| - `min_samples_split`, `min_samples_leaf` | |
| - `max_features` | |
| - Objective: **maximize classification accuracy** or **F1-score** on validation set. | |
| """) | |
| elif view == "π³ Random Forest Regressor": | |
| st.header("π³ Random Forest Regressor - In Depth") | |
| st.markdown(""" | |
| ## π What is Random Forest Regressor? | |
| A Random Forest Regressor is an ensemble learning model that combines predictions from multiple decision trees to produce a **continuous output** by averaging the results. | |
| --- | |
| ## π§ Key Concepts | |
| - **Bootstrap Sampling**: Builds trees on random samples. | |
| - **Feature Subsets**: Random subset of features considered at each split. | |
| - **Averaging**: Final prediction is the **mean** of predictions from all trees. | |
| --- | |
| ## β Advantages | |
| - Handles complex, non-linear relationships. | |
| - Reduces variance and improves generalization. | |
| - Robust to noise and outliers. | |
| ## β Disadvantages | |
| - Less interpretable. | |
| - Slower for large datasets. | |
| --- | |
| ## π§ Hyperparameters Explained | |
| | Parameter | Description | | |
| |-----------|-------------| | |
| | `n_estimators` | Number of regression trees. | | |
| | `criterion` | Loss function to minimize (`squared_error`, `absolute_error`). | | |
| | `max_depth` | Controls overfitting by limiting tree depth. | | |
| | `min_samples_split` | Minimum samples to split a node. | | |
| | `min_samples_leaf` | Minimum samples in a terminal node. | | |
| | `max_features` | Fraction/number of features to consider. | | |
| | `bootstrap` | Enable/disable bootstrapping. | | |
| | `oob_score` | Use unused (out-of-bag) data for evaluation. | | |
| --- | |
| ## π§ͺ Optuna for Hyperparameter Tuning (Explanation) | |
| - `Optuna` helps search for hyperparameters by optimizing a regression loss (e.g., **MAE**, **MSE**, **RMSE**). | |
| - Works well with Random Forest when tuning: | |
| - `n_estimators`, `max_depth` | |
| - `min_samples_split`, `min_samples_leaf` | |
| - `max_features` | |
| - Use validation error as objective for better generalization. | |
| --- | |
| ## π Use Cases | |
| - Predicting prices (real estate, stocks) | |
| - Sales forecasting | |
| - Weather predictions | |
| """) | |
| st.markdown(""" | |
| --- | |
| π **Note**: Always validate model performance using cross-validation. Feature importance from Random Forest (`.feature_importances_`) gives insight into what the model has learned. | |
| """) |