DEV Community

Ragib Hasan
Ragib Hasan Subscriber

Posted on

Mental Health Score Prediction Project — সম্পূর্ণ Bangla Explanation

এই guide-টি তোমার দেওয়া video transcript এবং Mental-Health-Score-main project-এর notebook, FastAPI backend, frontend JavaScript এবং deployment flow দেখে তৈরি করা হয়েছে। লক্ষ্য হলো তুমি যেন শুধু code copy না করো, বরং প্রতিটি step কেন করা হচ্ছে, কোন concept কোথায় লাগছে, input থেকে prediction পর্যন্ত data কীভাবে যাচ্ছে—সব পরিষ্কারভাবে বুঝতে পারো।


সূচিপত্র

  1. Project Overview
  2. End-to-End Architecture
  3. Problem Statement ও Regression
  4. Dataset বোঝা
  5. Libraries
  6. Data Loading ও Initial Inspection
  7. Missing Value, Duplicate, Data Types
  8. Descriptive Statistics ও Invalid Value
  9. EDA — কেন এবং কীভাবে
  10. Target Distribution
  11. Correlation Heatmap
  12. Stress vs Mental Health
  13. Social Media Usage vs Mental Health
  14. Sleep vs Mental Health
  15. Platform Count Plot
  16. Outlier ও IQR
  17. Data Cleaning
  18. Skewness
  19. Feature Engineering
  20. Country Grouping / High Cardinality
  21. Encoding Strategy
  22. Train-Test Split ও Data Leakage
  23. Pipeline এবং ColumnTransformer
  24. Preprocessing Pipelines
  25. Linear Regression
  26. Random Forest
  27. Overfitting / Underfitting
  28. Hyperparameter Tuning
  29. RandomizedSearchCV ও Cross Validation
  30. Model Evaluation — R², MAE, RMSE
  31. Actual Project Results
  32. Model Saving with Joblib
  33. FastAPI Backend
  34. Pydantic Validation
  35. /predict Endpoint
  36. Frontend — HTML/CSS/JavaScript
  37. Frontend Validation ও API Call
  38. Result Gauge ও UI State
  39. CORS
  40. Deployment on Render
  41. Complete Request Flow
  42. Important Project Mismatches / Bugs / Improvements
  43. Viva / Interview Questions
  44. Final Mental Model

1. Project Overview

এই project-এর মূল কাজ হলো একজন student-এর social media habit, study habit, sleep, physical activity, stress level এবং কিছু demographic information ব্যবহার করে একটি numerical Mental Health Score predict করা।

সহজভাবে:

Student-এর তথ্য
      ↓
Machine Learning Model
      ↓
Mental Health Score
Enter fullscreen mode Exit fullscreen mode

উদাহরণ:

Age                  = 23
Gender               = Female
Country              = Bangladesh
Academic Level       = Undergraduate
Most Used Platform   = Instagram
Purpose              = Entertainment
Daily Usage          = 6.5 hours
Daily Unlocks        = 90
Study Hours          = 4
Physical Activity    = 1 hour
Sleep                = 6 hours
Stress               = High
Enter fullscreen mode Exit fullscreen mode

Model output দিতে পারে:

Predicted Mental Health Score = 5.82 / 10
Enter fullscreen mode Exit fullscreen mode

এখানে 5.82 শুধু একটি numerical prediction। এটি কোনো clinical diagnosis নয়।


2. কেন এই project শুধু “ML notebook project” না

ভিডিওতে শুরুতেই emphasize করা হয়েছে যে এটা শুধু Jupyter Notebook-এ model train করার project না। এখানে পুরো end-to-end workflow আছে:

Dataset
  ↓
EDA + Cleaning
  ↓
Feature Engineering
  ↓
Preprocessing
  ↓
Machine Learning
  ↓
Model Evaluation
  ↓
Model Save (.pkl)
  ↓
FastAPI Backend
  ↓
Pydantic Validation
  ↓
HTML + CSS + JavaScript Frontend
  ↓
Deployment
Enter fullscreen mode Exit fullscreen mode

অর্থাৎ তুমি এক project-এ Data Science + Machine Learning + Backend + Frontend + Deployment—সবকিছুর সংযোগ দেখছ।


3. Problem Statement — Regression কেন?

Project-এর target column:

Mental_Health_Score
Enter fullscreen mode Exit fullscreen mode

এটি category নয়; এটি একটি continuous numerical value।

উদাহরণ:

3.8
5.4
7.2
8.9
Enter fullscreen mode Exit fullscreen mode

তাই এটি Regression Problem

Classification হলে কেমন হতো?

যদি target হতো:

Healthy / Unhealthy
Enter fullscreen mode Exit fullscreen mode

অথবা:

Low / Medium / High Risk
Enter fullscreen mode Exit fullscreen mode

তাহলে problem classification হতো।

Regression-এর সাধারণ algorithm

ভিডিওতে basic হিসেবে বলা হয়েছে:

  • Linear Regression
  • KNN Regressor
  • Decision Tree Regressor
  • Random Forest Regressor

এই project-এ মূল comparison:

  • Linear Regression
  • Random Forest
  • Tuned Random Forest

4. Dataset

Dataset file:

Student Social Media And Mental Health Impact.csv
Enter fullscreen mode Exit fullscreen mode

Notebook অনুযায়ী dataset-এর shape:

5000 rows × 13 columns
Enter fullscreen mode Exit fullscreen mode

অর্থাৎ 5000 student এবং 13টি columns।

Target বাদ দিলে 12টি input feature-এর ধারণা পাওয়া যায়।

প্রধান columns:

Age
Gender
Country
Academic_Level
Most_Used_Platform
Purpose_Of_Use
Avg_Daily_Usage_Hours
Daily_Unlocks
Study_Hours
Physical_Activity_Hours
Sleep_Hours_Per_Night
Stress_Level
Mental_Health_Score
Enter fullscreen mode Exit fullscreen mode

Input vs Target

Input Features (X)
        ↓
Machine Learning Algorithm
        ↓
Target (y)
Enter fullscreen mode Exit fullscreen mode

এখানে:

X = student information

y = Mental_Health_Score
Enter fullscreen mode Exit fullscreen mode

5. Libraries Import

Notebook শুরু হয় data manipulation ও visualization libraries দিয়ে:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
Enter fullscreen mode Exit fullscreen mode

NumPy

Numerical operation-এর জন্য। যেমন:

np.log1p()
np.sqrt()
Enter fullscreen mode Exit fullscreen mode

Pandas

Tabular data নিয়ে কাজ করার জন্য:

pd.read_csv()
df.head()
df.info()
df.describe()
Enter fullscreen mode Exit fullscreen mode

Matplotlib

Graph/plot তৈরির foundation library।

Seaborn

Statistical visualization সহজ ও সুন্দরভাবে করতে ব্যবহৃত হয়:

sns.histplot()
sns.heatmap()
sns.boxplot()
sns.scatterplot()
sns.countplot()
Enter fullscreen mode Exit fullscreen mode

ভিডিওতে একটি ভালো practice বলা হয়েছে: সব library শুরুতে randomly import না করে প্রয়োজন অনুযায়ী import করা যায়। তবে grouped imports readability বাড়ায়।


6. Dataset Load

df = pd.read_csv('Student Social Media And Mental Health Impact.csv')
Enter fullscreen mode Exit fullscreen mode

এই line-এর মানে:

CSV File
   ↓
pandas read_csv
   ↓
DataFrame
   ↓
df variable
Enter fullscreen mode Exit fullscreen mode

এখন df-এর মধ্যে পুরো dataset আছে।


7. Shape Check

df.shape
Enter fullscreen mode Exit fullscreen mode

Output:

(5000, 13)
Enter fullscreen mode Exit fullscreen mode

মানে:

5000 rows
13 columns
Enter fullscreen mode Exit fullscreen mode

এটি dataset understand করার প্রথম basic step।


8. First 5 Rows

df.head()
Enter fullscreen mode Exit fullscreen mode

head() default 5 rows দেখায়।

কেন দরকার?

  • Column name ঠিক আছে কি না
  • Data কেমন format-এ আছে
  • String/numeric mix আছে কি না
  • Weird value চোখে পড়ে কি না
  • Target কোথায় আছে

উদাহরণ:

Age Gender Country ... Stress_Level Mental_Health_Score
22  Female India  ... Medium        7.2
24  Male   USA    ... High          5.9
Enter fullscreen mode Exit fullscreen mode

9. Missing Values

df.isnull().sum()
Enter fullscreen mode Exit fullscreen mode

এটি প্রতিটি column-এ কতটি null/missing value আছে দেখায়।

উদাহরণ:

Age                   0
Gender                0
Sleep_Hours           5
Stress_Level          2
Enter fullscreen mode Exit fullscreen mode

Project dataset মোটামুটি clean।

Real-world data-তে কী হতে পারে?

Age = NaN
Sleep = NaN
Country = empty
Enter fullscreen mode Exit fullscreen mode

তখন imputation দরকার হতে পারে।

Numeric missing value example

Age missing → median age দিয়ে fill
Enter fullscreen mode Exit fullscreen mode

Categorical missing value example

Country missing → "Unknown" বা most frequent category
Enter fullscreen mode Exit fullscreen mode

ভিডিওতে emphasize করা হয়েছে Kaggle dataset অনেক সময় pre-cleaned হয়; real-world raw data সাধারণত অনেক messy হয়।


10. Duplicate Rows

df.duplicated().sum()
Enter fullscreen mode Exit fullscreen mode

Duplicate মানে একই row একাধিকবার আছে।

কেন problem?

ধরো একই student record 20 বার duplicate আছে। তাহলে model মনে করতে পারে ওই pattern অনেক বেশি important।

সাধারণ fix:

df = df.drop_duplicates()
Enter fullscreen mode Exit fullscreen mode

Notebook-এর markdown-এ zero duplicate বলা থাকলেও actual execution/history-তে transcript-এর একটি অংশে duplicate count নিয়ে mismatch দেখা যায়। তাই নিজের run-এর output-কে source of truth ধরবে।


11. df.info() — Data Type বোঝা

df.info()
Enter fullscreen mode Exit fullscreen mode

এখান থেকে জানতে পারি:

  • Column names
  • Non-null count
  • Data types

উদাহরণ:

Age                  int64
Gender               object
Country              object
Study_Hours          float64
Stress_Level         object
Mental_Health_Score  float64
Enter fullscreen mode Exit fullscreen mode

object মানে কী?

Pandas-এ object প্রায়ই string/text data বোঝায়।

যেমন:

Male
Female
Instagram
Facebook
High
Low
Enter fullscreen mode Exit fullscreen mode

Machine Learning model সরাসরি text বোঝে না। তাই categorical text feature encode করতে হয়।


12. df.describe() — Descriptive Statistics

df.describe()
Enter fullscreen mode Exit fullscreen mode

Numerical columns-এর জন্য দেয়:

count
mean
std
min
25%
50%
75%
max
Enter fullscreen mode Exit fullscreen mode

এখানেই project-এর একটি বাস্তব data issue ধরা পড়ে।

Physical Activity-এর invalid value

Physical_Activity_Hours min = -0.4
Enter fullscreen mode Exit fullscreen mode

এটা physically impossible। মানুষ negative hour exercise করতে পারে না।

তাই এটি real observation না, data-entry error।


13. EDA কী?

EDA = Exploratory Data Analysis

EDA-এর উদ্দেশ্য শুধু সুন্দর graph বানানো না। প্রতিটি plot ideally একটি প্রশ্নের উত্তর দেবে।

Notebook-এর philosophy:

“Chart-এর wall বানাব না; focused plots বানাব।”

Project-এ ছয়টি প্রধান plot করা হয়েছে।


14. Plot 1 — Target Distribution

sns.histplot(df['Mental_Health_Score'], kde=True)
Enter fullscreen mode Exit fullscreen mode

Question:

Mental Health Score কীভাবে distributed?

Histogram কী দেখায়?

Data-এর value কোন range-এ কতবার এসেছে তা bar আকারে দেখায়।

উদাহরণ:

Score 3–4 → 300 students
Score 4–5 → 700 students
Score 5–6 → 1200 students
...
Enter fullscreen mode Exit fullscreen mode

KDE কী?

KDE = Kernel Density Estimate

Histogram-এর উপর smooth curve দেয়, distribution-এর shape বোঝা সহজ হয়।

কেন target distribution দেখা দরকার?

Prediction করার আগে target:

  • balanced কি না
  • heavily skewed কি না
  • strange range আছে কি না
  • outlier আছে কি না

বোঝা দরকার।


15. Correlation Heatmap

sns.heatmap(df.corr(numeric_only=True), annot=True)
Enter fullscreen mode Exit fullscreen mode

Correlation কী?

দুই numerical variable একসাথে কীভাবে পরিবর্তিত হয় তার linear relationship-এর একটি measure।

Range:

-1 ←—— 0 ——→ +1
Enter fullscreen mode Exit fullscreen mode

Positive Correlation

একটা বাড়লে অন্যটা generally বাড়ে।

Sleep ↑
Mental Health Score ↑
Enter fullscreen mode Exit fullscreen mode

Negative Correlation

একটা বাড়লে অন্যটা generally কমে।

Social Media Usage ↑
Mental Health Score ↓
Enter fullscreen mode Exit fullscreen mode

Near Zero

Strong linear relation নেই।

numeric_only=True কেন?

DataFrame-এ string columns আছে। যেমন:

Gender
Country
Platform
Enter fullscreen mode Exit fullscreen mode

Correlation numeric data-তে apply করা হয়। তাই:

df.corr(numeric_only=True)
Enter fullscreen mode Exit fullscreen mode

ব্যবহার করা হয়েছে।

annot=True কেন?

Heatmap cell-এর ভেতরে correlation number দেখায়।

ভিডিওতে sleep বনাম score প্রায় positive 0.77 এবং daily usage বনাম score প্রায় -0.82 ধরনের strong relationship discuss করা হয়েছে।

গুরুত্বপূর্ণ সতর্কতা

Correlation ≠ Causation

Dataset-এ দুই feature correlated হলেই একটি অন্যটির সরাসরি কারণ প্রমাণ হয় না।


16. Stress Level vs Mental Health Score

প্রথমে categories দেখা হয়েছে:

df['Stress_Level'].unique()
Enter fullscreen mode Exit fullscreen mode

Categories:

Low
Medium
High
Very High
Enter fullscreen mode Exit fullscreen mode

তারপর order manually define:

order = ['Low', 'Medium', 'High', 'Very High']
Enter fullscreen mode Exit fullscreen mode

Boxplot:

sns.boxplot(
    x='Stress_Level',
    y='Mental_Health_Score',
    data=df,
    order=order
)
Enter fullscreen mode Exit fullscreen mode

কেন Boxplot?

Boxplot group-wise distribution compare করতে সাহায্য করে।

এতে দেখা যায়:

  • median
  • quartiles
  • spread
  • outliers

Project-এর observed pattern:

Stress বাড়ছে
      ↓
Mental Health Score কমছে
Enter fullscreen mode Exit fullscreen mode

এটা dataset-level relationship। Clinical conclusion নয়।


17. Daily Social Media Usage vs Mental Health

sns.scatterplot(
    x='Avg_Daily_Usage_Hours',
    y='Mental_Health_Score',
    data=df
)
Enter fullscreen mode Exit fullscreen mode

Scatter plot দুটি numerical variable-এর relationship visually দেখায়।

ভিডিওর interpretation:

Low usage → comparatively higher scores
High usage → comparatively lower scores
Enter fullscreen mode Exit fullscreen mode

অর্থাৎ graph top-left থেকে bottom-right trend করলে negative relation বোঝা যায়।


18. Sleep vs Mental Health

sns.scatterplot(
    x='Sleep_Hours_Per_Night',
    y='Mental_Health_Score',
    data=df
)
Enter fullscreen mode Exit fullscreen mode

Observed pattern:

Sleep Hours ↑
Score ↑
Enter fullscreen mode Exit fullscreen mode

Graph bottom-left → top-right গেলে positive relationship-এর visual indication পাওয়া যায়।


19. Most Used Platform

df['Most_Used_Platform'].value_counts()
Enter fullscreen mode Exit fullscreen mode

এটি প্রতিটি platform কতবার এসেছে দেখায়।

তারপর:

plt.figure(figsize=(8, 4))
sns.countplot(
    x=df['Most_Used_Platform'],
    order=df['Most_Used_Platform'].value_counts().index
)
Enter fullscreen mode Exit fullscreen mode

value_counts().index কেন?

value_counts() result roughly:

Instagram    1130
TikTok        918
Facebook      800
...
Enter fullscreen mode Exit fullscreen mode

Countplot নিজে count করে, তাই count values pass করার দরকার নেই। শুধু desired order দরকার। সেই order পাওয়া যায় .index থেকে।


20. Outlier কী?

Outlier হলো এমন value যা অন্য observations-এর তুলনায় অস্বাভাবিক দূরে।

উদাহরণ:

Study Hours:
2, 3, 4, 5, 4, 3, 50
Enter fullscreen mode Exit fullscreen mode

50 suspicious outlier।

Project-এ IQR method ব্যবহার করা হয়েছে।


21. IQR Method

num_features = df.select_dtypes(include='number')
Q1 = num_features.quantile(0.25)
Q3 = num_features.quantile(0.75)
IQR = Q3 - Q1

lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

outliers = (num_features < lower_bound) | (num_features > upper_bound)
print(outliers.sum())
Enter fullscreen mode Exit fullscreen mode

Formula

IQR = Q3 - Q1

Lower Bound = Q1 - 1.5 × IQR
Upper Bound = Q3 + 1.5 × IQR
Enter fullscreen mode Exit fullscreen mode

যদি value:

value < Lower Bound
Enter fullscreen mode Exit fullscreen mode

অথবা:

value > Upper Bound
Enter fullscreen mode Exit fullscreen mode

তাহলে potential outlier।

Example

ধরো:

Q1 = 3
Q3 = 7
Enter fullscreen mode Exit fullscreen mode

তাহলে:

IQR = 7 - 3 = 4
Lower = 3 - 1.5×4 = -3
Upper = 7 + 1.5×4 = 13
Enter fullscreen mode Exit fullscreen mode

20 → outlier।

গুরুত্বপূর্ণ

Outlier detect হলেই delete করতে হবে—এমন না। প্রথমে দেখতে হবে value logically possible কি না।


22. Data Cleaning

Notebook-এ দুইটি cleaning step আছে:

df = df.drop_duplicates()

df['Physical_Activity_Hours'] = \
    df['Physical_Activity_Hours'].clip(lower=0)
Enter fullscreen mode Exit fullscreen mode

clip(lower=0) কেন?

Suppose:

Physical Activity = -0.4
Enter fullscreen mode Exit fullscreen mode

এটি invalid।

clip(lower=0) করলে:

-0.4 → 0
Enter fullscreen mode Exit fullscreen mode

কেন পুরো row drop করা হয়নি?

কারণ একই student-এর:

  • Age
  • Sleep
  • Stress
  • Study time
  • Platform

সব valid হতে পারে। শুধু একটি field ভুল হওয়ায় পুরো row delete করা data waste।


23. Skewness

Skewness distribution-এর asymmetry measure।

num_cols = df.select_dtypes(include='number')
num_cols.skew()
Enter fullscreen mode Exit fullscreen mode

Rough interpretation:

Skew ≈ 0     → roughly symmetric
Skew > 0     → right skewed
Skew < 0     → left skewed
Enter fullscreen mode Exit fullscreen mode

Right Skew example

1 1 2 2 3 4 5 10 20 50
Enter fullscreen mode Exit fullscreen mode

ডান দিকে long tail।

Left Skew example

1 2 10 18 19 20 20 20
Enter fullscreen mode Exit fullscreen mode

বাম দিকে tail।

কেন Linear Regression-এর জন্য relevant?

Tree-based model যেমন Random Forest skewness নিয়ে খুব sensitive নয়। কিন্তু Linear Regression baseline-এর জন্য feature transformation helpful হতে পারে।

Project-এ Study_Hours skewed column হিসেবে separate pipeline-এ গেছে।


24. Feature Engineering — Country Grouping

Dataset-এ Country-এর unique value অনেক—Notebook markdown অনুযায়ী প্রায় 111টি।

যদি সরাসরি One-Hot Encoding করি:

Country_India
Country_USA
Country_Canada
Country_Bangladesh
...
Enter fullscreen mode Exit fullscreen mode

100+ sparse columns তৈরি হতে পারে। একে High Cardinality problem বলা হয়।

Solution

Top 10 frequent countries আলাদা রাখা, বাকিগুলো Other:

top_countries = df['Country'].value_counts().index[:10].tolist()
Enter fullscreen mode Exit fullscreen mode

Function:

def group_countries(country):
    if country in top_countries:
        return country
    else:
        return 'Other'
Enter fullscreen mode Exit fullscreen mode

Apply:

df['Grouped_country'] = df['Country'].apply(group_countries)
Enter fullscreen mode Exit fullscreen mode

ফলে:

111 categories
      ↓
Top 10 + Other
      ↓
11 categories
Enter fullscreen mode Exit fullscreen mode

কেন original Country পুরো drop করা হলো না?

Country-এর কিছু useful signal থাকতে পারে। কিন্তু full high-cardinality version model unnecessarily complex করতে পারে। Grouping balance তৈরি করে।


25. Encoding Strategy

Machine Learning model text বুঝে না। তাই categorical data numerical representation-এ convert করতে হয়।

দুই ধরনের encoding ব্যবহার হয়েছে:

  1. Ordinal Encoding
  2. One-Hot Encoding

26. Ordinal Encoding — Stress Level

Stress level-এর natural order আছে:

Low < Medium < High < Very High
Enter fullscreen mode Exit fullscreen mode

তাই:

Low       → 0
Medium    → 1
High      → 2
Very High → 3
Enter fullscreen mode Exit fullscreen mode

Code:

OrdinalEncoder(
    categories=[['Low', 'Medium', 'High', 'Very High']]
)
Enter fullscreen mode Exit fullscreen mode

কেন One-Hot না?

One-Hot করলে ordering information হারিয়ে যায়। Stress-এর meaningful rank আছে, তাই ordinal encoding logical।


27. One-Hot Encoding

Columns:

Gender
Academic_Level
Most_Used_Platform
Purpose_Of_Use
Grouped_country
Enter fullscreen mode Exit fullscreen mode

এই categories-এর natural ranking নেই।

উদাহরণ:

Instagram > Facebook
Enter fullscreen mode Exit fullscreen mode

এমন relationship নেই। তাই arbitrary number দেওয়া dangerous।

One-Hot Encoding:

Platform_Instagram = 1
Platform_Facebook  = 0
Platform_TikTok    = 0
Enter fullscreen mode Exit fullscreen mode

Code:

OneHotEncoder(handle_unknown='ignore')
Enter fullscreen mode Exit fullscreen mode

handle_unknown='ignore'

Production-এ training-এ না থাকা নতুন category এলে pipeline যেন crash না করে।


28. Train-Test Split

Feature group define করা হয়েছে:

skwewd_col = ['Study_Hours']

other_numeric_cols = [
    'Age',
    'Avg_Daily_Usage_Hours',
    'Daily_Unlocks',
    'Physical_Activity_Hours',
    'Sleep_Hours_Per_Night'
]

ordinal_col = ['Stress_Level']

normal_col = [
    'Gender',
    'Academic_Level',
    'Most_Used_Platform',
    'Purpose_Of_Use',
    'Grouped_country'
]
Enter fullscreen mode Exit fullscreen mode

তারপর:

feature_col = skwewd_col + other_numeric_cols + ordinal_col + normal_col
X = df[feature_col]
y = df['Mental_Health_Score']
Enter fullscreen mode Exit fullscreen mode

Actual split code:

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.30,
    random_state=42
)
Enter fullscreen mode Exit fullscreen mode

অর্থাৎ:

70% Training
30% Testing
Enter fullscreen mode Exit fullscreen mode

Note

Notebook markdown-এ 80/20 লেখা আছে, কিন্তু actual code 70/30। Implementation বোঝার সময় code-এর actual parameter follow করবে।


29. Train/Test কেন?

Training set দিয়ে model শেখে।

Testing set model আগে দেখে না।

Full Dataset
     ↓
 ┌──────────────┬──────────────┐
 │              │
Train          Test
70%            30%
 │              │
Fit model       Final evaluation
Enter fullscreen mode Exit fullscreen mode

যদি training data-তেই evaluation করো, model memorize করে artificially ভালো score দিতে পারে।


30. Data Leakage

এটি খুব গুরুত্বপূর্ণ interview topic।

Wrong approach:

Full Data
   ↓
Scaling / Encoding fit
   ↓
Train-Test Split
Enter fullscreen mode Exit fullscreen mode

এখানে test set-এর statistics preprocessing-এ leak হয়ে যেতে পারে।

Correct approach:

Full Data
   ↓
Train/Test Split
   ↓
Preprocessing fitted only on training data
   ↓
Same fitted transformer applied to test data
Enter fullscreen mode Exit fullscreen mode

Pipeline এই risk কমায়।


31. Pipeline এবং ColumnTransformer

ভিডিওর সবচেয়ে important নতুন concept দুটো:

  • ColumnTransformer
  • Pipeline

Problem

সব feature-এর preprocessing একই না।

Study_Hours      → log + scaling
Age              → scaling
Stress_Level     → ordinal encoding
Gender           → one-hot encoding
Platform         → one-hot encoding
Enter fullscreen mode Exit fullscreen mode

একটা single scaler বা encoder সব column-এ apply করা যাবে না।

ColumnTransformer কী করে?

এটি different columns-কে different pipelines-এ পাঠায়।

                  Raw Data
                     │
     ┌───────────────┼────────────────┐
     ↓               ↓                ↓
Study_Hours       Numeric        Categorical
     ↓               ↓                ↓
 log1p            scale         encode
     │               │                │
     └───────────────┴────────────────┘
                     ↓
             Combined Features
Enter fullscreen mode Exit fullscreen mode

32. Skewed Feature Pipeline

skew_pipeline = Pipeline(steps=[
    ('log_transform', FunctionTransformer(np.log1p)),
    ('scale', StandardScaler())
])
Enter fullscreen mode Exit fullscreen mode

Flow:

Study_Hours
    ↓
np.log1p
    ↓
StandardScaler
Enter fullscreen mode Exit fullscreen mode

np.log1p(x) কী?

এটি:

log(1 + x)
Enter fullscreen mode Exit fullscreen mode

ব্যবহার করে। x=0 হলেও safe।

Example:

x = 0 → log(1) = 0
x = 10 → log(11)
Enter fullscreen mode Exit fullscreen mode

Large values compress হয়, right skew কমতে পারে।


33. Numeric Pipeline

plain_numeric_pipeline = Pipeline(steps=[
    ('scale', StandardScaler())
])
Enter fullscreen mode Exit fullscreen mode

StandardScaler কী করে?

Feature-কে roughly zero mean এবং unit variance scale-এ আনে:

z = (x - mean) / standard_deviation
Enter fullscreen mode Exit fullscreen mode

উদাহরণ:

Daily Unlocks = 120
Age = 23
Sleep = 7
Enter fullscreen mode Exit fullscreen mode

raw scale খুব ভিন্ন। Scaling linear model-এর জন্য useful।


34. Ordinal Pipeline

ordinal_pipeline = Pipeline(steps=[
    ('encode', OrdinalEncoder(
        categories=[['Low', 'Medium', 'High', 'Very High']]
    ))
])
Enter fullscreen mode Exit fullscreen mode

Natural order preserve করে।


35. Nominal Pipeline

nominal_pipeline = Pipeline(steps=[
    ('encode', OneHotEncoder(handle_unknown='ignore'))
])
Enter fullscreen mode Exit fullscreen mode

যেসব category-এর order নেই তাদের জন্য।


36. ColumnTransformer

preprocessor = ColumnTransformer(transformers=[
    ('Skewed_Pipeline', skew_pipeline, skwewd_col),
    ('Plain_Numeric', plain_numeric_pipeline, other_numeric_cols),
    ('Ordinal', ordinal_pipeline, ordinal_col),
    ('Normal', nominal_pipeline, normal_col)
])
Enter fullscreen mode Exit fullscreen mode

এখানে tuple pattern:

(name, transformer, columns)
Enter fullscreen mode Exit fullscreen mode

মানে:

এই নামের transformer → এই columns-এর উপর apply করো
Enter fullscreen mode Exit fullscreen mode

37. Final Model Pipeline কেন?

ভিডিওর key idea:

Backend যেন scaling, encoding, log transformation কিছুই আলাদা করে না জানে। সে শুধু raw input দেবে এবং .predict() call করবে।

Pipeline:

Raw User Input
      ↓
ColumnTransformer
      ↓
Scaling + Encoding + Log transform
      ↓
Machine Learning Model
      ↓
Prediction
Enter fullscreen mode Exit fullscreen mode

এটা deployment অনেক safer করে।


38. Linear Regression Baseline

lr_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('regressor', LinearRegression())
])
Enter fullscreen mode Exit fullscreen mode

Fit:

lr_pipeline.fit(X_train, y_train)
Enter fullscreen mode Exit fullscreen mode

Predict:

lr_preds = lr_pipeline.predict(X_test)
Enter fullscreen mode Exit fullscreen mode

Training predictions:

lr_preds_train = lr_pipeline.predict(X_train)
Enter fullscreen mode Exit fullscreen mode

কেন baseline?

Linear Regression simple model। যদি simple model-ই ভালো করে, unnecessarily complex model দরকার নাও হতে পারে।


39. Linear Regression Result

Saved notebook output:

Training R² ≈ 0.7237
Testing R²  ≈ 0.7398
MAE         ≈ 0.5362
RMSE        ≈ 0.6760
Enter fullscreen mode Exit fullscreen mode

Interpretation:

  • Train এবং test score কাছাকাছি
  • Severe overfitting নেই
  • কিন্তু Random Forest-এর তুলনায় weaker performance

40. Random Forest

rf_pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('random forest', RandomForestRegressor(random_state=42))
])
Enter fullscreen mode Exit fullscreen mode

Random Forest অনেক Decision Tree combine করে।

Simple mental model:

Tree 1 → prediction
Tree 2 → prediction
Tree 3 → prediction
...
Tree N → prediction
       ↓
Average
       ↓
Final Regression Output
Enter fullscreen mode Exit fullscreen mode

Tree-based model nonlinear relation ও feature interaction ধরতে পারে।


41. Default Random Forest Result

Notebook output:

Training R² ≈ 0.9808
Testing R²  ≈ 0.8776
MAE         ≈ 0.3472
RMSE        ≈ 0.4637
Enter fullscreen mode Exit fullscreen mode

এটি Linear Regression-এর চেয়ে test set-এ ভালো।

কিন্তু training R² 0.98 আর testing R² 0.88 — gap আছে। এটি কিছু overfitting-এর sign হতে পারে।


42. Overfitting কী?

Model training data খুব ভালো শিখে ফেলেছে, কিন্তু unseen data-তে performance noticeably কম।

Train R² = 0.99
Test R²  = 0.70
Enter fullscreen mode Exit fullscreen mode

→ strong overfitting indication।

এই project-এ:

Train ≈ 0.98
Test  ≈ 0.88
Enter fullscreen mode Exit fullscreen mode

gap আছে, কিন্তু test performance still strong।

Underfitting কী?

Train এবং test দুটোতেই poor:

Train = 0.50
Test  = 0.48
Enter fullscreen mode Exit fullscreen mode

মানে model pattern ধরতেই পারছে না।


43. Hyperparameter Tuning

Random Forest-এর parameters model behavior control করে।

Project-এ tune করা হয়েছে:

param_grid = {
    'random forest__n_estimators': [100, 200, 300],
    'random forest__max_depth': [5, 10, 15],
    'random forest__min_samples_split': [2, 5, 10],
    'random forest__min_samples_leaf': [1, 2, 4]
}
Enter fullscreen mode Exit fullscreen mode

Parameters সহজভাবে

n_estimators

কতটি tree থাকবে।

max_depth

একটি tree কত deep যেতে পারবে।

min_samples_split

একটি node split করার জন্য minimum samples।

min_samples_leaf

Leaf node-এ minimum samples।


44. Pipeline parameter name-এ __ কেন?

Pipeline step name:

('random forest', RandomForestRegressor(...))
Enter fullscreen mode Exit fullscreen mode

তাই parameter refer করতে:

random forest__n_estimators
Enter fullscreen mode Exit fullscreen mode

দুই underscore __ দিয়ে:

pipeline_step__parameter
Enter fullscreen mode Exit fullscreen mode

format ব্যবহার হয়।


45. RandomizedSearchCV

random_search = RandomizedSearchCV(
    estimator=rf_pipeline,
    param_distributions=param_grid,
    n_iter=15,
    cv=5,
    scoring='r2',
    random_state=42,
    n_jobs=-1
)
Enter fullscreen mode Exit fullscreen mode

n_iter=15

সব possible combination test না করে 15টি random combination try করবে।

cv=5

5-fold cross validation।

scoring='r2'

Best model select করার metric R²।

n_jobs=-1

সব available CPU cores ব্যবহার করতে পারে।


46. Cross Validation

Training data 5 ভাগ:

Fold 1
Fold 2
Fold 3
Fold 4
Fold 5
Enter fullscreen mode Exit fullscreen mode

Round 1:

Train = Fold 2–5
Validate = Fold 1
Enter fullscreen mode Exit fullscreen mode

Round 2:

Train = 1,3,4,5
Validate = 2
Enter fullscreen mode Exit fullscreen mode

এভাবে প্রতিটি fold একবার validation হয়।

একটি single split-এর luck-এর উপর dependency কমে।


47. Best Hyperparameters

Notebook output:

{
 'random forest__n_estimators': 200,
 'random forest__min_samples_split': 5,
 'random forest__min_samples_leaf': 2,
 'random forest__max_depth': 15
}
Enter fullscreen mode Exit fullscreen mode

Best estimator:

rf_best_pipeline = random_search.best_estimator_
Enter fullscreen mode Exit fullscreen mode

48. Tuned Random Forest Result

Test R²      ≈ 0.8650
Training R²  ≈ 0.9547
MAE          ≈ 0.3689
RMSE         ≈ 0.4869
Enter fullscreen mode Exit fullscreen mode

Interesting finding:

Default Random Forest test result tuned model-এর চেয়ে সামান্য ভালো।

এটা শেখায়:

Hyperparameter tuning করলেই performance অবশ্যই improve করবে—এমন guarantee নেই।

Tuning overfitting gap reduce করতে পারে, কিন্তু chosen search space বা random combinations test score কমাতেও পারে।


49. Evaluation Metrics

R² Score

Target variation-এর কতটা model explain করছে তার measure।

R² = 1 → perfect prediction
R² = 0 → naive mean baseline-এর মতো
R² < 0 → mean prediction-এর থেকেও খারাপ
Enter fullscreen mode Exit fullscreen mode

Simple interpretation:

R² = 0.88
Enter fullscreen mode Exit fullscreen mode

মানে model dataset-এর variation-এর বড় অংশ explain করছে।


50. MAE

MAE = Mean Absolute Error

Formula idea:

|Actual - Prediction|
Enter fullscreen mode Exit fullscreen mode

সব absolute error-এর mean।

Example:

Actual      Prediction   Error
8.0         7.5          0.5
6.0         6.2          0.2
5.0         4.6          0.4
Enter fullscreen mode Exit fullscreen mode

Average:

(0.5 + 0.2 + 0.4) / 3
= 0.3667
Enter fullscreen mode Exit fullscreen mode

MAE original score unit-এ understandable।


51. RMSE

RMSE = Root Mean Squared Error

Large mistakes-কে বেশি penalty দেয়।

Error 0.5 → squared 0.25
Error 2.0 → squared 4.0
Enter fullscreen mode Exit fullscreen mode

তাই rare large error থাকলে RMSE বেড়ে যায়।


52. Model Comparison Table

Actual notebook output:

Model Test R² Train R² MAE RMSE
Linear Regression 0.7398 0.7237 0.5362 0.6760
Random Forest Default 0.8776 0.9808 0.3472 0.4637
Random Forest Tuned 0.8650 0.9547 0.3689 0.4869

Dataset/test split অনুযায়ী default Random Forest এখানে strongest test metrics দিয়েছে।


53. Model Save with Joblib

import joblib
joblib.dump(rf_pipeline, 'Mental_Health_Model.pkl')
Enter fullscreen mode Exit fullscreen mode

এখানে খুব গুরুত্বপূর্ণ বিষয়:

শুধু Random Forest object save করা হয়নি। rf_pipeline save হওয়ায় preprocessing + model একসাথে save হয়।

Mental_Health_Model.pkl
        │
        ├── ColumnTransformer
        ├── log1p transform
        ├── StandardScaler
        ├── OrdinalEncoder
        ├── OneHotEncoder
        └── RandomForestRegressor
Enter fullscreen mode Exit fullscreen mode

কেন ভালো?

FastAPI শুধু:

model.predict(raw_dataframe)
Enter fullscreen mode Exit fullscreen mode

call করবে। Backend-এ preprocessing পুনরায় manually লিখতে হবে না।


54. Important Model Save Mismatch

Notebook tuned model বানিয়েছে:

rf_best_pipeline = random_search.best_estimator_
Enter fullscreen mode Exit fullscreen mode

কিন্তু save করেছে:

joblib.dump(rf_pipeline, 'Mental_Health_Model.pkl')
Enter fullscreen mode Exit fullscreen mode

অর্থাৎ default Random Forest pipeline save হয়েছে, tuned one না।

এটি intentional হতে পারে কারণ default model-এর test metrics better ছিল। তবে code-এ comment দিয়ে reason clear করা উচিত ছিল।

যদি tuned model save করতে চাই:

joblib.dump(rf_best_pipeline, 'Mental_Health_Model.pkl')
Enter fullscreen mode Exit fullscreen mode

55. FastAPI Backend

Backend file:

main.py
Enter fullscreen mode Exit fullscreen mode

Imports:

import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field
from typing import Literal
from fastapi.middleware.cors import CORSMiddleware
Enter fullscreen mode Exit fullscreen mode

56. Load Model

model = joblib.load('Mental_Health_Model.pkl')
Enter fullscreen mode Exit fullscreen mode

Server start হলে saved pipeline memory-তে load হয়।

তারপর প্রতিটি prediction request-এ নতুন করে model load করতে হয় না।


57. FastAPI App

app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

এটাই application object।

Run command সাধারণত:

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Project JS error message-এ port example:

uvicorn main:app --port 2200 --reload
Enter fullscreen mode Exit fullscreen mode

58. Pydantic কেন?

Pydantic request body validate করে।

class StudentData(BaseModel):
Enter fullscreen mode Exit fullscreen mode

এটি বলে:

/predict-এ কী shape-এর data আসবে এবং কোন field-এর type/range কী হবে।


59. Age Validation

age: int = Field(..., ge=10, le=100)
Enter fullscreen mode Exit fullscreen mode

মানে:

Required
Integer
Age >= 10
Age <= 100
Enter fullscreen mode Exit fullscreen mode

যদি আসে:

{"age": 5}
Enter fullscreen mode Exit fullscreen mode

FastAPI/Pydantic 422 validation error দিতে পারে।


60. Literal Validation

gender: Literal['Male', 'Female']
Enter fullscreen mode Exit fullscreen mode

Valid:

Male
Female
Enter fullscreen mode Exit fullscreen mode

Invalid:

ABC
Unknown
Enter fullscreen mode Exit fullscreen mode

একইভাবে academic level, platform, purpose এবং stress level predefined category-তে restricted।


61. Numeric Field Validation

avg_daily_usage_hours: float = Field(..., ge=0, le=24)
daily_unlocks: int = Field(..., ge=0)
study_hours: float = Field(..., ge=0, le=24)
physical_activity_hours: float = Field(..., ge=0, le=24)
sleep_hours_per_night: float = Field(..., ge=0, le=24)
Enter fullscreen mode Exit fullscreen mode

এতে physically impossible বা clearly invalid inputs prevent করা হয়।


62. Prediction Response Model

class PredictionResponse(BaseModel):
    predicted_mental_health_score: float
Enter fullscreen mode Exit fullscreen mode

এটি API response-এর shape define করে।

Expected response:

{
  "predicted_mental_health_score": 6.78
}
Enter fullscreen mode Exit fullscreen mode

63. Root Route

@app.get('/')
def greet():
    return {'Welcome to Sheryians AI School Guys'}
Enter fullscreen mode Exit fullscreen mode

Browser-এ root URL hit করলে simple JSON response আসে।

এটা backend alive কি না basic check হিসেবে useful।


64. /predict Route

@app.post('/predict', response_model=PredictionResponse)
def predict(data: StudentData):
Enter fullscreen mode Exit fullscreen mode

এখানে:

  • Method = POST
  • Endpoint = /predict
  • Request validated by StudentData
  • Response validated by PredictionResponse

65. Backend Country Grouping

Training-এ Country grouping করা হয়েছিল। Prediction-এর সময় একই logic দরকার।

country_group = data.country if data.country in top_countries else 'Other'
Enter fullscreen mode Exit fullscreen mode

Training এবং inference preprocessing consistency খুব গুরুত্বপূর্ণ।


66. Input DataFrame তৈরি

input_row = pd.DataFrame([{
    'Age': data.age,
    'Gender': data.gender,
    'Country': data.country,
    'Academic_Level': data.academic_level,
    'Most_Used_Platform': data.most_used_platform,
    'Purpose_Of_Use': data.purpose_of_use,
    'Avg_Daily_Usage_Hours': data.avg_daily_usage_hours,
    'Daily_Unlocks': data.daily_unlocks,
    'Study_Hours': data.study_hours,
    'Physical_Activity_Hours': data.physical_activity_hours,
    'Sleep_Hours_Per_Night': data.sleep_hours_per_night,
    'Stress_Level': data.stress_level,
    'Grouped_country': country_group
}])
Enter fullscreen mode Exit fullscreen mode

কেন DataFrame?

Saved pipeline column names দিয়ে preprocessing route করে। তাই raw user data-কে training-এর মতো DataFrame schema-তে convert করা হচ্ছে।


67. Prediction

prediction = model.predict(input_row)[0]
Enter fullscreen mode Exit fullscreen mode

Flow:

input_row
   ↓
Saved Pipeline
   ↓
Feature preprocessing
   ↓
Random Forest
   ↓
Array-like prediction
   ↓
[0] দিয়ে first prediction
Enter fullscreen mode Exit fullscreen mode

তারপর:

round(float(prediction), 2)
Enter fullscreen mode Exit fullscreen mode

যেমন:

6.777777
   ↓
6.78
Enter fullscreen mode Exit fullscreen mode

68. CORS

Backend:

app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_methods=['*'],
    allow_headers=['*'],
)
Enter fullscreen mode Exit fullscreen mode

Browser security কারণে frontend এবং backend আলাদা origin/domain হলে request block হতে পারে। CORS policy দিয়ে অনুমতি দেওয়া হয়।

Production note

allow_origins=['*'] demo project-এর জন্য easy, কিন্তু production-এ specific frontend domain allow করা safer।


69. Frontend Technologies

ভিডিওতে বলা হয়েছে Streamlit ব্যবহার করা হয়নি। Frontend:

HTML
CSS
JavaScript
Enter fullscreen mode Exit fullscreen mode

এতে project traditional web app architecture follow করছে।


70. Frontend Form

User form-এ data দেয়:

Age
Gender
Country
Academic Level
Most Used Platform
Purpose of Use
Average Daily Usage Hours
Daily Unlocks
Study Hours
Physical Activity Hours
Sleep Hours
Stress Level
Enter fullscreen mode Exit fullscreen mode

Submit button চাপলে JavaScript payload বানায়।


71. collectPayload()

JavaScript form values collect করে exact Pydantic shape বানায়:

return {
  age: ..., 
  gender: ...,
  country: ...,
  academic_level: ...,
  most_used_platform: ...,
  purpose_of_use: ...,
  avg_daily_usage_hours: ...,
  daily_unlocks: ...,
  study_hours: ...,
  physical_activity_hours: ...,
  sleep_hours_per_night: ...,
  stress_level: ...
};
Enter fullscreen mode Exit fullscreen mode

এখানে frontend field names backend Pydantic model-এর field names-এর সাথে match করা খুব গুরুত্বপূর্ণ।


72. Client-side Validation

JavaScript backend-এ পাঠানোর আগে numeric ranges check করে:

Age                  10–100
Daily Usage           0–24
Daily Unlocks         >= 0
Study Hours           0–24
Physical Activity     0–24
Sleep                 0–24
Enter fullscreen mode Exit fullscreen mode

এতে user instant feedback পায়।

কিন্তু frontend validation security boundary না; backend Pydantic validation still required।


73. Stress Segmented Control

JavaScript stress level button click handle করে:

Low
Medium
High
Very High
Enter fullscreen mode Exit fullscreen mode

Selected value hidden input-এ রাখা হয়।

এটি UI সুন্দর করে, কিন্তু backend শেষ পর্যন্ত string value-টাই পায়।


74. API Call with fetch

Core code:

const res = await fetch(`${API_BASE}/predict`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(payload),
});
Enter fullscreen mode Exit fullscreen mode

Flow:

JavaScript Object
      ↓
JSON.stringify
      ↓
HTTP POST
      ↓
FastAPI /predict
Enter fullscreen mode Exit fullscreen mode

75. API Base URL

Project frontend:

const API_BASE = 'https://mansik-santulan-score.onrender.com';
Enter fullscreen mode Exit fullscreen mode

মানে backend Render-এ deployed।

Local development-এ এটি হতে পারে:

const API_BASE = 'http://127.0.0.1:8000';
Enter fullscreen mode Exit fullscreen mode

অথবা project-specific port।


76. 422 Validation Error Handling

FastAPI Pydantic validation fail করলে HTTP 422 দেয়।

Frontend code response-এর detail array parse করে relevant field-এর পাশে error message দেখানোর চেষ্টা করে।

এটি UX-এর জন্য ভালো design।


77. Loading / Result / Error UI States

JavaScript চারটি state manage করে:

idle
loading
result
error
Enter fullscreen mode Exit fullscreen mode

Submit:

Idle
 ↓
Loading
 ↓
Success → Result
     অথবা
Failure → Error
Enter fullscreen mode Exit fullscreen mode

এটি user-কে application কী করছে বুঝতে সাহায্য করে।


78. Result Gauge

Prediction score clamp করা হয়:

const clamped = Math.max(0, Math.min(10, score));
Enter fullscreen mode Exit fullscreen mode

মানে UI gauge 0–10 range-এর বাইরে যাবে না।

তারপর arc fill score অনুযায়ী animate হয়।


79. UI Score Bands

Frontend code-এ:

score < 4
→ Signal: strained

4 ≤ score < 7
→ Signal: balanced

score ≥ 7
→ Signal: strong
Enter fullscreen mode Exit fullscreen mode

এগুলো product UI labels; medical diagnosis না।

Mental-health-related application হলে এই distinction খুব important।


80. Complete Request-Response Example

ধরো user input:

Age = 23
Gender = Female
Country = Bangladesh
Academic Level = Undergraduate
Platform = Instagram
Purpose = Entertainment
Usage = 7 hours
Unlocks = 95
Study = 3 hours
Physical Activity = 1 hour
Sleep = 5.5 hours
Stress = High
Enter fullscreen mode Exit fullscreen mode

Step 1 — Frontend Payload

{
  "age": 23,
  "gender": "Female",
  "country": "Bangladesh",
  "academic_level": "Undergraduate",
  "most_used_platform": "Instagram",
  "purpose_of_use": "Entertainment",
  "avg_daily_usage_hours": 7,
  "daily_unlocks": 95,
  "study_hours": 3,
  "physical_activity_hours": 1,
  "sleep_hours_per_night": 5.5,
  "stress_level": "High"
}
Enter fullscreen mode Exit fullscreen mode

Step 2 — FastAPI

Pydantic validate করবে।

Step 3 — Country grouping

Bangladesh top list-এ না থাকলে:

Grouped_country = Other
Enter fullscreen mode Exit fullscreen mode

Step 4 — DataFrame

Input training schema-এর মতো row হবে।

Step 5 — Saved Pipeline

Study_Hours
   ↓ log1p + scale

Numeric features
   ↓ scale

Stress
   ↓ ordinal encode

Other categorical
   ↓ one-hot encode
Enter fullscreen mode Exit fullscreen mode

Step 6 — Random Forest

Transformed feature vector থেকে numerical score predict করবে।

Step 7 — API Response

{
  "predicted_mental_health_score": 5.43
}
Enter fullscreen mode Exit fullscreen mode

Step 8 — Frontend

Gauge এবং label update হবে।


81. Deployment Concept

ভিডিওতে project Render-এ deploy করার কথা বলা হয়েছে।

Basic deployment flow:

GitHub Repository
      ↓
Render Web Service
      ↓
Install requirements.txt
      ↓
Start FastAPI using Uvicorn
      ↓
Public API URL
Enter fullscreen mode Exit fullscreen mode

requirements.txt project-এ:

fastapi
uvicorn
pydantic
joblib
pandas
scikit-learn
Enter fullscreen mode Exit fullscreen mode

Typical Render Start Command

uvicorn main:app --host 0.0.0.0 --port $PORT
Enter fullscreen mode Exit fullscreen mode

Frontend-এ deployed API URL set করা হয়।


82. End-to-End Architecture Diagram

┌─────────────────────────────────────┐
│             USER / BROWSER          │
└──────────────────┬──────────────────┘
                   │
                   ▼
┌─────────────────────────────────────┐
│       HTML + CSS + JavaScript       │
│ Form, validation, loading, gauge    │
└──────────────────┬──────────────────┘
                   │ JSON POST /predict
                   ▼
┌─────────────────────────────────────┐
│              FASTAPI                │
│ Pydantic validation + route logic   │
└──────────────────┬──────────────────┘
                   │
                   ▼
┌─────────────────────────────────────┐
│     pandas DataFrame input row      │
└──────────────────┬──────────────────┘
                   │
                   ▼
┌─────────────────────────────────────┐
│        SAVED SKLEARN PIPELINE       │
│                                     │
│ ColumnTransformer                   │
│ ├── Study_Hours → log + scale       │
│ ├── Numeric → scale                 │
│ ├── Stress → ordinal encoding       │
│ └── Categories → one-hot encoding   │
│                 ↓                   │
│       RandomForestRegressor         │
└──────────────────┬──────────────────┘
                   │
                   ▼
┌─────────────────────────────────────┐
│        Predicted Score 0–10         │
└──────────────────┬──────────────────┘
                   │ JSON
                   ▼
┌─────────────────────────────────────┐
│         Frontend Result Gauge       │
└─────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

83. Video-এর Important Learning Philosophy

ভিডিওতে technical content-এর পাশাপাশি কয়েকটি mindset point repeated হয়েছে:

  1. শুধু notebook model বানানো যথেষ্ট না—deployment পর্যন্ত গেলে project অনেক stronger হয়।
  2. EDA random graph collection না; প্রতিটি graph-এর একটি question থাকা উচিত।
  3. Kaggle data clean হলেও real-world data messy—cleaning mindset develop করতে হবে।
  4. Categorical text model সরাসরি বুঝে না; encoding দরকার।
  5. Different columns-এর জন্য different preprocessing দরকার হতে পারে।
  6. Pipeline production deployment-এর জন্য খুব useful।
  7. Training score একা দেখে model choose করা উচিত না; unseen test data performance বেশি important।
  8. Single metric-এর উপর model decision না নেওয়া ভালো; R² + MAE + RMSE together দেখা উচিত।
  9. Hyperparameter tuning মানেই automatically better test score নয়।
  10. Frontend, backend এবং ML pipeline-এর schema consistent থাকা অত্যন্ত গুরুত্বপূর্ণ।

84. Important Mismatch / Improvement Notes

এগুলো project ভালোভাবে বুঝতে সবচেয়ে useful অংশগুলোর একটি।

84.1 80/20 লেখা, code 70/30

Markdown বলে 80/20। Actual code:

test_size=0.30
Enter fullscreen mode Exit fullscreen mode

অর্থাৎ 70/30। Documentation update করা উচিত।

84.2 Tuned model বানানো হলেও default pipeline save

joblib.dump(rf_pipeline, ...)
Enter fullscreen mode Exit fullscreen mode

এটি default RF। Notebook output-এ default model test metrics tuned model-এর চেয়ে better, তাই choice reasonable; কিন্তু explicit explanation থাকা উচিত।

84.3 Country list consistency

Training-এ top_countries dynamically dataset থেকে বের করা হয়েছে। Backend-এ list hard-coded:

top_countries = ['Other','India','USA','Canada','Australia','UK','Germany','Mexico','Turkey','France']
Enter fullscreen mode Exit fullscreen mode

Best practice:

  • Country grouping logic pipeline-এর ভেতরে রাখা, অথবা
  • fitted metadata save করা

যাতে training এবং inference mismatch না হয়।

84.4 Original Country input_row-এ আছে, কিন্তু model features-এ ব্যবহার হয় না

Model Grouped_country ব্যবহার করে; raw Country ColumnTransformer feature list-এ নেই। এটি harmless extra column হতে পারে, কিন্তু cleaner schema রাখা ভালো।

84.5 CORS *

Demo-র জন্য okay, production-এ specific origin safer।

84.6 Medical Interpretation

এই model educational dataset-এর statistical prediction। User-এর real mental health assessment হিসেবে present করা উচিত না। UI-তে clear disclaimer থাকা দরকার।


85. কীভাবে project explain করবে Viva-তে

Short answer:

“আমি একটি end-to-end regression application তৈরি করেছি যেখানে student-এর social media usage, study, sleep, physical activity, stress এবং demographic data থেকে Mental Health Score predict করা হয়। Data cleaning এবং EDA-এর পরে categorical variables ordinal ও one-hot encoding করেছি, numerical features scale করেছি, skewed study-hours feature log transform করেছি এবং এগুলো sklearn ColumnTransformer ও Pipeline-এর মধ্যে combine করেছি। Linear Regression baseline এবং Random Forest compare করেছি, RandomizedSearchCV দিয়ে tuning করেছি এবং R², MAE, RMSE দিয়ে evaluate করেছি। পুরো trained pipeline Joblib দিয়ে save করে FastAPI/Pydantic backend-এ expose করেছি এবং HTML/CSS/JavaScript frontend থেকে /predict endpoint call করে live prediction দেখিয়েছি।”


86. Viva Questions + Answers

Q1. কেন regression?

কারণ target Mental_Health_Score continuous numerical value।

Q2. কেন classification না?

Target class label না; number predict করছি।

Q3. df.info() কেন?

Column types, non-null count এবং schema বুঝতে।

Q4. negative physical activity কীভাবে handle করেছ?

clip(lower=0) ব্যবহার করেছি যাতে invalid negative hour zero হয় এবং পুরো row না হারায়।

Q5. Correlation কী?

দুই numerical feature-এর linear relationship-এর strength/direction।

Q6. Correlation causation প্রমাণ করে?

না।

Q7. IQR কেন?

Potential outlier detect করতে robust statistical method।

Q8. Country grouping কেন?

High cardinality reduce করতে।

Q9. Stress level-এ Ordinal Encoding কেন?

কারণ natural order আছে: Low < Medium < High < Very High।

Q10. Platform-এ One-Hot কেন?

কারণ natural order নেই।

Q11. ColumnTransformer কেন?

Different column groups-এ different preprocessing apply করতে।

Q12. Pipeline কেন?

Preprocessing + model এক object-এ chain করতে এবং training/inference consistency রাখতে।

Q13. Data leakage কী?

Test data-এর information training/preprocessing fitting-এ accidentally চলে যাওয়া।

Q14. Random Forest Linear Regression-এর চেয়ে কেন ভালো করতে পারে?

Nonlinear relation এবং feature interaction ধরতে পারে।

Q15. Hyperparameter কী?

Training-এর আগে configured model setting, যেমন max_depth, n_estimators

Q16. RandomizedSearchCV কেন?

সব combination exhaustive search না করে selected random combinations efficiently test করতে।

Q17. R² কী?

Target variation-এর কতটা model explain করছে তার measure।

Q18. MAE কী?

Average absolute prediction error।

Q19. RMSE কী?

Squared error-based metric যা large mistakes বেশি penalize করে।

Q20. Joblib দিয়ে পুরো pipeline save কেন?

Backend-এ preprocessing manually recreate না করতে।

Q21. Pydantic কেন?

API request validation ও type/range enforcement-এর জন্য।

Q22. POST কেন?

Prediction request-এ structured JSON payload পাঠাতে সুবিধাজনক এবং semantics অনুযায়ী data processing action।

Q23. CORS কেন?

Browser-এর cross-origin request restriction handle করতে।

Q24. 422 error কী?

FastAPI/Pydantic validation fail হলে সাধারণত Unprocessable Entity response।


87. Beginner-এর জন্য Project শেখার Order

তুমি যদি raw থেকে শিখতে চাও:

1. Python basics
2. NumPy basics
3. Pandas
4. Matplotlib / Seaborn
5. Basic Statistics
6. Regression concept
7. Data Cleaning
8. EDA
9. Encoding
10. Scaling
11. Train/Test Split
12. Linear Regression
13. Decision Tree
14. Random Forest
15. Evaluation Metrics
16. ColumnTransformer
17. Pipeline
18. Hyperparameter Tuning
19. Joblib
20. FastAPI
21. Pydantic
22. Basic HTML/CSS/JS
23. Fetch API
24. CORS
25. Render Deployment
Enter fullscreen mode Exit fullscreen mode

88. সবচেয়ে Important 4 Concepts

এই project থেকে যদি চারটি জিনিস সবচেয়ে ভালোভাবে শিখতে চাও:

1. ColumnTransformer

Different feature group → different preprocessing।

2. Pipeline

Preprocessing + model → single reliable object।

3. Train/Test + Leakage

Unseen data দিয়ে honest evaluation।

4. FastAPI Integration

ML model → usable real-world web API।


89. Full Project Mental Model

সবকিছু ভুলে গেলেও এই flow মনে রাখবে:

UNDERSTAND PROBLEM
       ↓
LOAD DATA
       ↓
CHECK SHAPE / HEAD / INFO
       ↓
MISSING / DUPLICATE / INVALID VALUES
       ↓
EDA
       ↓
OUTLIERS
       ↓
CLEAN DATA
       ↓
CHECK SKEWNESS
       ↓
FEATURE ENGINEERING
       ↓
DEFINE X AND y
       ↓
TRAIN / TEST SPLIT
       ↓
COLUMN TRANSFORMER
       ↓
PIPELINE
       ↓
LINEAR REGRESSION BASELINE
       ↓
RANDOM FOREST
       ↓
HYPERPARAMETER TUNING
       ↓
R² + MAE + RMSE
       ↓
SAVE PIPELINE
       ↓
FASTAPI
       ↓
PYDANTIC VALIDATION
       ↓
POST /predict
       ↓
HTML/CSS/JS FRONTEND
       ↓
FETCH API
       ↓
RESULT GAUGE
       ↓
RENDER DEPLOYMENT
Enter fullscreen mode Exit fullscreen mode

90. One Final Example — Raw Input থেকে Final Prediction

ধরো user:

Age = 21
Gender = Male
Country = Bangladesh
Academic Level = Undergraduate
Platform = TikTok
Purpose = Entertainment
Usage = 8 h/day
Unlocks = 120
Study = 2 h/day
Exercise = 0.5 h/day
Sleep = 5 h/night
Stress = Very High
Enter fullscreen mode Exit fullscreen mode

Backend Request

{
  "age": 21,
  "gender": "Male",
  "country": "Bangladesh",
  "academic_level": "Undergraduate",
  "most_used_platform": "TikTok",
  "purpose_of_use": "Entertainment",
  "avg_daily_usage_hours": 8,
  "daily_unlocks": 120,
  "study_hours": 2,
  "physical_activity_hours": 0.5,
  "sleep_hours_per_night": 5,
  "stress_level": "Very High"
}
Enter fullscreen mode Exit fullscreen mode

Internal transformation conceptually

Study_Hours = 2
   ↓ log1p
   ↓ scale

Age = 21
Usage = 8
Unlocks = 120
Exercise = 0.5
Sleep = 5
   ↓ StandardScaler

Stress = Very High
   ↓ OrdinalEncoder
   ↓ 3

Gender = Male
Platform = TikTok
Purpose = Entertainment
Academic = Undergraduate
Country Group = Other
   ↓ OneHotEncoder
Enter fullscreen mode Exit fullscreen mode

সব transformed features merge হয়।

Feature Vector
      ↓
Random Forest
      ↓
Predicted Mental Health Score
Enter fullscreen mode Exit fullscreen mode

ধরো result:

4.72
Enter fullscreen mode Exit fullscreen mode

FastAPI:

{
  "predicted_mental_health_score": 4.72
}
Enter fullscreen mode Exit fullscreen mode

Frontend result gauge update করবে।

এই পুরো sequence বুঝতে পারলে তুমি project-এর মূল architecture সত্যিই বুঝে গেছ, শুধু code মুখস্থ করোনি।


91. Summary Cheat Sheet

Problem Type       : Regression
Target             : Mental_Health_Score
Dataset Size       : ~5000 rows, 13 columns
EDA                : Histogram, Heatmap, Boxplot, Scatterplot, Countplot
Outlier Method     : IQR
Invalid Value Fix  : clip(lower=0)
Skew Fix           : log1p for Study_Hours
High Cardinality   : Country → Top 10 + Other
Ordinal Encoding   : Stress_Level
One-Hot Encoding   : Gender, Academic, Platform, Purpose, Grouped Country
Scaling            : StandardScaler
Split              : Actual code 70/30
Baseline           : Linear Regression
Main Model         : Random Forest Regressor
Tuning             : RandomizedSearchCV, 5-fold CV
Metrics            : R², MAE, RMSE
Serialization      : joblib / .pkl
Backend            : FastAPI
Validation         : Pydantic
Frontend           : HTML + CSS + JavaScript
API Method         : POST
Endpoint           : /predict
Deployment         : Render
Enter fullscreen mode Exit fullscreen mode

92. Final Takeaway

এই project-এর সবচেয়ে বড় lesson কোনো একটি algorithm না। সবচেয়ে বড় lesson হলো Machine Learning model কীভাবে একটি complete application-এর অংশ হয়

একজন beginner সাধারণত দেখে:

CSV → Model → Accuracy
Enter fullscreen mode Exit fullscreen mode

কিন্তু real project flow:

Problem Understanding
→ Data Quality
→ EDA
→ Cleaning
→ Feature Engineering
→ Correct Preprocessing
→ Leakage-free Training
→ Multiple Model Comparison
→ Evaluation
→ Serialization
→ Backend Validation
→ API
→ Frontend
→ Error Handling
→ Deployment
Enter fullscreen mode Exit fullscreen mode

তুমি যদি এই flow বুঝে নিজের ভাষায় explain করতে পারো, তাহলে project-টা সত্যিকার অর্থে বুঝেছ।

Top comments (0)