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. """)