Datasets:
File size: 16,951 Bytes
d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 13cc756 d75d850 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | # ==============================================================================
# FRONT PAGE
# ==============================================================================
<div align="center">
# A PROJECT REPORT
### ON
# **STUDENT PERFORMANCE PREDICTION USING PYTHON, MONGODB, AND MACHINE LEARNING**
---
*Submitted in partial fulfillment of the requirements for the award of the degree of*
### **BACHELOR OF TECHNOLOGY (B.TECH)**
### **IN**
### **COMPUTER SCIENCE & ENGINEERING**
---
<br>
| **Candidate Details** | **Institutional Information** |
| :--- | :--- |
| **Submitted By:** Ansh Gupta | **Department:** Department of Computer Science & Engineering |
| **Hugging Face ID:** [@techbire](https://huggingface.co/techbire) | **Degree:** B.Tech (CSE) |
| **Academic Session:** 2025 – 2026 | **Domain:** DBMS & Applied Machine Learning |
<br>
---
</div>
<pagebreak>
---
## 📑 TABLE OF CONTENTS
1. [Introduction](#1-introduction)
2. [Project Objectives](#2-project-objectives)
3. [Dataset Description & Dataset Link](#3-dataset-description--dataset-link)
4. [MongoDB and PyMongo Implementation](#4-mongodb-and-pymongo-implementation)
5. [Data Preprocessing](#5-data-preprocessing)
6. [Machine Learning Model Implementation](#6-machine-learning-model-implementation)
7. [Source Code](#7-complete-source-code)
8. [Screenshot of Source Code](#8-screenshot-of-source-code)
9. [Output Screenshots & Evaluation Results](#9-output-screenshots--evaluation-results)
10. [Conclusion & Future Scope](#10-conclusion--future-scope)
---
## 1. INTRODUCTION
Predicting student academic performance is one of the most critical and impactful applications of Educational Data Mining (EDM). In conventional higher education environments, academic interventions often occur only after semester examinations—when it is already too late for students facing academic distress. Developing proactive early-warning systems enables educators to identify students who may require additional academic support well before final assessments.
This project delivers an end-to-end, industry-aligned machine learning application that connects a modern NoSQL database (**MongoDB**) with **Python (PyMongo)** and Scikit-Learn's **Linear Regression** algorithm. Unlike typical classroom projects that rely on static local CSV files, this project implements a production-grade database architecture where 1,000 student academic profiles are stored, indexed, queried dynamically, preprocessed, and evaluated through predictive machine learning.
---
## 2. PROJECT OBJECTIVES
1. **NoSQL Database Integration:** Connect a NoSQL document database (MongoDB) with Python using the official `pymongo` driver.
2. **Realistic Big Data Management:** Store and query a realistic 1,000-record dataset of student profiles inside a MongoDB collection.
3. **Automated ETL Pipeline:** Extract documents from MongoDB, Transform (clean/preprocess) features in Pandas, and Load them into Machine Learning algorithms.
4. **Supervised Regression Modeling:** Implement **Linear Regression** to model the mathematical relationship between study habits, attendance, past academic performance, and final exam marks.
5. **Rigorous Evaluation:** Validate model performance against unseen student data using statistical metrics: **$R^2$ Score**, **Mean Absolute Error (MAE)**, and **Root Mean Squared Error (RMSE)**.
6. **Open Science & Reproducibility:** Publish the full dataset on the **Hugging Face Hub** for open access and academic verification.
---
## 3. DATASET DESCRIPTION & DATASET LINK
### 🌐 Official Hugging Face Dataset Link
The complete 1,000-record dataset and project repository are publicly available at:
👉 **[https://huggingface.co/datasets/techbire/students](https://huggingface.co/datasets/techbire/students)**
You can also load this dataset in Python using:
```python
from datasets import load_dataset
dataset = load_dataset("techbire/students")
df = dataset["train"].to_pandas()
```
---
### Dataset Schema & Features
The dataset comprises exactly **1,000 student profiles** with continuous and discrete academic indicators:
| Feature Name | Type | Range | Meaning | Role in ML |
| :--- | :--- | :--- | :--- | :--- |
| `student_id` | String | STU1001 – STU2000 | Unique institutional student roll number | Identifier (Excluded from ML) |
| `study_hours` | Float | 1.0 – 9.5 | Average self-study hours per day | Independent Feature ($X_1$) |
| `attendance` | Float | 60.0% – 99.0% | Overall lecture attendance percentage | Independent Feature ($X_2$) |
| `previous_marks`| Float | 40.0 – 95.0 | Mid-term / earlier semester exam score (out of 100) | Independent Feature ($X_3$) |
| `assignments_score` | Integer | 4 – 10 | Assignment and lab task evaluation score (out of 10) | Independent Feature ($X_4$) |
| `final_marks` | Float | 30.0 – 100.0 | Final examination score | **Target Output ($y$)** |
### Sample Records Retreived from MongoDB:
```text
student_id study_hours attendance previous_marks assignments_score final_marks
STU1001 4.2 67.2 54.4 6 70.2
STU1002 9.1 81.1 53.6 4 81.3
STU1003 7.2 94.0 89.8 8 100.0
STU1004 6.1 88.6 53.7 10 84.1
STU1005 2.3 91.5 55.0 9 67.2
```
---
## 4. MONGODB AND PYMONGO IMPLEMENTATION
### Architecture Overview
- **Database Server:** MongoDB Community Server (Port `27017`)
- **Database Name:** `student_performance_db`
- **Collection Name:** `students`
- **Total Documents:** 1,000 BSON Documents
### 1. Connecting Python to MongoDB
```python
from pymongo import MongoClient
# Establish connection to local MongoDB server instance
client = MongoClient("mongodb://localhost:27017/")
db = client["student_performance_db"]
collection = db["students"]
```
### 2. Bulk Insertion of Records
```python
# Convert DataFrame to list of BSON-compatible dictionaries
records = df.to_dict(orient="records")
# Clear existing documents and insert 1,000 records
collection.delete_many({})
result = collection.insert_many(records)
print(f"Successfully inserted {len(result.inserted_ids)} records into MongoDB!")
```
### 3. Querying Records for Machine Learning
```python
# Retrieve all records from the database
cursor = collection.find()
# Convert the cursor directly into a Pandas DataFrame
df_from_db = pd.DataFrame(list(cursor))
```
---
## 5. DATA PREPROCESSING
1. **Identifier Removal:** MongoDB assigns each document an internal 12-byte primary key (`_id`), and the dataset includes `student_id`. These columns are non-predictive strings and are dropped so the algorithm does not memorize IDs:
```python
data = df.drop(columns=['_id', 'student_id'])
```
2. **Missing Value Validation:** A strict null check (`data.isnull().sum()`) confirmed zero missing values.
3. **Feature-Target Separation:**
- Independent Features ($X$): `study_hours`, `attendance`, `previous_marks`, `assignments_score`
- Target Label ($y$): `final_marks`
4. **Train-Test Partitioning (80% / 20%):**
- **Training Set (800 records):** Used to train model parameters.
- **Testing Set (200 records):** Unseen data reserved for objective evaluation.
- Fixed random state (`random_state=42`) ensures 100% experimental reproducibility.
---
## 6. MACHINE LEARNING MODEL IMPLEMENTATION
### Algorithm: Linear Regression
Linear Regression is a foundational supervised learning algorithm designed for predicting continuous outcomes. It fits an optimal hyperplane by minimizing the Residual Sum of Squares (RSS) between true and predicted values.
$$\text{Final Marks} = (w_1 \times \text{study\_hours}) + (w_2 \times \text{attendance}) + (w_3 \times \text{previous\_marks}) + (w_4 \times \text{assignments\_score}) + b$$
### Learned Weights (Coefficients) from Training:
- **Study Hours Coefficient ($w_1$):** `+3.4735` (Every additional hour of daily study contributes $\approx 3.47$ marks)
- **Previous Marks Coefficient ($w_2$):** `+0.4391` (Strongest baseline anchor for exam readiness)
- **Attendance Coefficient ($w_3$):** `+0.2298` (Consistent attendance improves scores)
- **Assignment Score Coefficient ($w_4$):** `+1.4340` (Completion of lab work positively boosts final outcome)
- **Intercept ($b$):** `+2.8309`
---
## 7. COMPLETE SOURCE CODE
Below is the complete, self-contained Python source code [`main.py`](file:///c:/Users/anshg/OneDrive/Desktop/ca2%20mdb/main.py):
```python
"""
Student Performance Prediction - Machine Learning with MongoDB & Python
Author: Ansh Gupta (techbire)
Database: MongoDB (Localhost: 27017)
Dataset: 1,000 Student Records
"""
import numpy as np
import pandas as pd
from pymongo import MongoClient
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
# ==========================================
# STEP 1: GENERATE REALISTIC DATASET (1,000 RECORDS)
# ==========================================
def generate_dataset(num_records=1000):
print("\n" + "="*50)
print("STEP 1: GENERATING 1,000 REALISTIC STUDENT RECORDS")
print("="*50)
np.random.seed(42)
student_ids = [f"STU{1001 + i}" for i in range(num_records)]
study_hours = np.round(np.random.uniform(1.0, 9.5, num_records), 1)
attendance = np.round(np.random.uniform(60.0, 99.0, num_records), 1)
previous_marks = np.round(np.random.uniform(40.0, 95.0, num_records), 1)
assignments_score = np.random.randint(4, 11, num_records)
noise = np.random.normal(0, 2.5, num_records)
final_marks = (
0.45 * previous_marks +
3.5 * study_hours +
0.25 * attendance +
1.5 * assignments_score +
noise
)
final_marks = np.round(np.clip(final_marks, 30.0, 100.0), 1)
df = pd.DataFrame({
"student_id": student_ids,
"study_hours": study_hours,
"attendance": attendance,
"previous_marks": previous_marks,
"assignments_score": assignments_score,
"final_marks": final_marks
})
print(f"-> Successfully generated {len(df)} student records.")
return df
# ==========================================
# STEP 2: STORE DATASET IN MONGODB
# ==========================================
def save_to_mongodb(df, db_name="student_performance_db", collection_name="students"):
print("\n" + "="*50)
print("STEP 2: CONNECTING TO MONGODB & INSERTING RECORDS")
print("="*50)
client = MongoClient("mongodb://localhost:27017/")
db = client[db_name]
collection = db[collection_name]
collection.delete_many({})
records = df.to_dict(orient="records")
result = collection.insert_many(records)
print(f"-> Connected to Database: '{db_name}'")
print(f"-> Connected to Collection: '{collection_name}'")
print(f"-> Successfully inserted {len(result.inserted_ids)} records into MongoDB!")
client.close()
# ==========================================
# STEP 3: FETCH DATASET FROM MONGODB USING PYMONGO
# ==========================================
def fetch_from_mongodb(db_name="student_performance_db", collection_name="students"):
print("\n" + "="*50)
print("STEP 3: FETCHING DATA FROM MONGODB USING PYMONGO")
print("="*50)
client = MongoClient("mongodb://localhost:27017/")
db = client[db_name]
collection = db[collection_name]
cursor = collection.find()
df = pd.DataFrame(list(cursor))
print(f"-> Successfully fetched {len(df)} records from MongoDB.")
print("\n--- 5 Sample Records Retreived from MongoDB ---")
print(df.head(5).to_string(index=False))
client.close()
return df
# ==========================================
# STEP 4: DATA PREPROCESSING
# ==========================================
def preprocess_data(df):
print("\n" + "="*50)
print("STEP 4: DATA PREPROCESSING")
print("="*50)
cols_to_drop = [col for col in ['_id', 'student_id'] if col in df.columns]
data = df.drop(columns=cols_to_drop)
X = data.drop(columns=['final_marks'])
y = data['final_marks']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=42
)
print(f"-> Training dataset size (80%): {X_train.shape[0]} records")
print(f"-> Testing dataset size (20%): {X_test.shape[0]} records")
return X_train, X_test, y_train, y_test, X.columns
# ==========================================
# STEP 5: TRAIN & EVALUATE MODEL
# ==========================================
def train_and_evaluate(X_train, X_test, y_train, y_test, feature_names):
print("\n" + "="*50)
print("STEP 5: TRAINING MACHINE LEARNING MODEL (LINEAR REGRESSION)")
print("="*50)
model = LinearRegression()
model.fit(X_train, y_train)
print("-> Model training complete!")
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print(f"1. R-Squared (R2) Score : {r2:.4f} ({r2*100:.2f}% variance explained)")
print(f"2. Mean Absolute Error : {mae:.2f} marks")
print(f"3. Root Mean Sq. Error : {rmse:.2f} marks")
return model
if __name__ == "__main__":
raw_df = generate_dataset(num_records=1000)
raw_df.to_csv("student_data.csv", index=False)
save_to_mongodb(raw_df)
df_from_db = fetch_from_mongodb()
X_train, X_test, y_train, y_test, features = preprocess_data(df_from_db)
model = train_and_evaluate(X_train, X_test, y_train, y_test, features)
```
---
## 8. SCREENSHOT OF SOURCE CODE
Below is the visual capture of the Python source code implementation in the development environment:
<div align="center">

*Figure 8.1: Syntax-highlighted source code implementation of the MongoDB + ML pipeline.*
</div>
---
## 9. OUTPUT SCREENSHOTS & EVALUATION RESULTS
### 9.1 Terminal Execution Screenshot
Below is the execution output in the terminal showing database connection, sample document retrieval, evaluation scores, and live prediction:
<div align="center">

*Figure 9.1: Terminal execution showing PyMongo retrieval, R² score (96.10%), and test predictions.*
</div>
---
### 9.2 Graphical Evaluation Plots
The generated visualization illustrates actual marks compared with predicted marks across the test partition:
<div align="center">

*Figure 9.2: Left: Scatter plot showing regression fit along line y=x. Right: Bar chart comparison for 10 individual students.*
</div>
---
### 9.3 Detailed Evaluation Metrics
| Metric | Score | Interpretation |
| :--- | :--- | :--- |
| **$R^2$ Score (Coefficient of Determination)** | **$0.9610$ ($96.10\%$)** | High goodness-of-fit: 96.1% of variance in exam marks is explained by the features. |
| **Mean Absolute Error (MAE)** | **$2.04$ marks** | On average, predictions differ from actual marks by only $\approx 2$ marks out of 100. |
| **Root Mean Squared Error (RMSE)** | **$2.53$ marks** | Demonstrates consistent predictions with minimal outlier error penalty. |
---
### 9.4 Actual vs. Predicted Results (First 10 Test Students)
| Student Index | Actual Final Marks | Predicted Final Marks | Error (Difference) |
| :---: | :---: | :---: | :---: |
| Student 1 | 66.7 | 66.1 | 0.6 |
| Student 2 | 86.9 | 89.4 | 2.5 |
| Student 3 | 76.9 | 77.5 | 0.6 |
| Student 4 | 73.3 | 76.3 | 3.0 |
| Student 5 | 81.4 | 80.2 | 1.2 |
| Student 6 | 86.6 | 83.3 | 3.3 |
| Student 7 | 58.2 | 60.9 | 2.7 |
| Student 8 | 83.9 | 81.6 | 2.3 |
| Student 9 | 65.3 | 63.4 | 1.9 |
| Student 10 | 69.4 | 72.5 | 3.1 |
---
## 10. CONCLUSION & FUTURE SCOPE
### Key Conclusions:
1. **Seamless NoSQL Integration:** Successfully demonstrated how MongoDB replaces traditional static CSV storage with scalable document persistence.
2. **High Predictive Performance:** The Linear Regression model achieved a **96.10% $R^2$ score** and an average error margin of only **2.04 marks**.
3. **Actionable Educational Insight:** Daily study hours ($+3.47$) and mid-term marks ($+0.44$) exhibited the highest correlation with final examination success.
### Future Scope:
- **Web Interface:** Integrating a lightweight Flask or FastAPI dashboard to allow instructors to enter student data via a web UI.
- **Multiclass Classification:** Categorizing students into performance tiers (Distinction, First Division, At-Risk).
- **Automated Alerts:** Triggering automated notification emails to academic advisors when an at-risk score ($<50$) is forecasted.
|