Datasets:
File size: 8,332 Bytes
13cc756 | 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 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Student Performance Prediction using Python, MongoDB, and Scikit-Learn\n",
"**A Beginner-Friendly Machine Learning Project for B.Tech CSE Students**\n",
"\n",
"### Project Highlights:\n",
"- **Database:** MongoDB (`student_performance_db`)\n",
"- **Connection Library:** PyMongo\n",
"- **Dataset Size:** 1,000 Student Records\n",
"- **ML Algorithm:** Linear Regression\n",
"- **Evaluation Metrics:** $R^2$ Score and Mean Absolute Error (MAE)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Install & Import Required Libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import all required packages\n",
"import numpy as np\n",
"import pandas as pd\n",
"from pymongo import MongoClient\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\n",
"import matplotlib.pyplot as plt\n",
"\n",
"print(\"All libraries imported successfully!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Generate 1,000 Realistic Student Records & Store in MongoDB"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set random seed for consistency\n",
"np.random.seed(42)\n",
"num_records = 1000\n",
"\n",
"# 1. Features generation\n",
"student_ids = [f\"STU{1001 + i}\" for i in range(num_records)]\n",
"study_hours = np.round(np.random.uniform(1.0, 9.5, num_records), 1)\n",
"attendance = np.round(np.random.uniform(60.0, 99.0, num_records), 1)\n",
"previous_marks = np.round(np.random.uniform(40.0, 95.0, num_records), 1)\n",
"assignments_score = np.random.randint(4, 11, num_records)\n",
"\n",
"# 2. Calculate realistic Final Marks with realistic noise\n",
"noise = np.random.normal(0, 2.5, num_records)\n",
"final_marks = (0.45 * previous_marks + 3.5 * study_hours + 0.25 * attendance + 1.5 * assignments_score + noise)\n",
"final_marks = np.round(np.clip(final_marks, 30.0, 100.0), 1)\n",
"\n",
"# Combine into DataFrame\n",
"df_raw = pd.DataFrame({\n",
" \"student_id\": student_ids,\n",
" \"study_hours\": study_hours,\n",
" \"attendance\": attendance,\n",
" \"previous_marks\": previous_marks,\n",
" \"assignments_score\": assignments_score,\n",
" \"final_marks\": final_marks\n",
"})\n",
"\n",
"# Connect to MongoDB and save records\n",
"client = MongoClient(\"mongodb://localhost:27017/\")\n",
"db = client[\"student_performance_db\"]\n",
"collection = db[\"students\"]\n",
"\n",
"collection.delete_many({})\n",
"collection.insert_many(df_raw.to_dict(orient=\"records\"))\n",
"print(f\"Successfully stored {collection.count_documents({})} documents in MongoDB!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Fetch Data from MongoDB using PyMongo & Show Sample Records"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Fetch all documents from MongoDB\n",
"data_from_db = list(collection.find())\n",
"df = pd.DataFrame(data_from_db)\n",
"\n",
"print(f\"Fetched {len(df)} records from MongoDB.\")\n",
"# Display 5 sample records\n",
"df.head(5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Data Preprocessing & Train-Test Split (80% / 20%)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Drop MongoDB '_id' and identifier 'student_id'\n",
"clean_df = df.drop(columns=['_id', 'student_id'])\n",
"\n",
"# Check for missing values\n",
"print(\"Missing values check:\")\n",
"print(clean_df.isnull().sum())\n",
"\n",
"# Separate Features (X) and Target (y)\n",
"X = clean_df[['study_hours', 'attendance', 'previous_marks', 'assignments_score']]\n",
"y = clean_df['final_marks']\n",
"\n",
"# Split: 80% Training, 20% Testing\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)\n",
"print(f\"Training set: {X_train.shape[0]} rows, Testing set: {X_test.shape[0]} rows\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Train Linear Regression Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Initialize and fit model\n",
"model = LinearRegression()\n",
"model.fit(X_train, y_train)\n",
"\n",
"# Print learned weights\n",
"for feature, weight in zip(X.columns, model.coef_):\n",
" print(f\"Weight for {feature:20s}: {weight:.4f}\")\n",
"print(f\"Intercept (c): {model.intercept_:.4f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Evaluation Metrics & Comparison Table"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Predict on testing dataset\n",
"y_pred = model.predict(X_test)\n",
"\n",
"r2 = r2_score(y_test, y_pred)\n",
"mae = mean_absolute_error(y_test, y_pred)\n",
"rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
"\n",
"print(f\"R-squared (R2) Score : {r2:.4f} (Accuracy: {r2*100:.2f}%)\")\n",
"print(f\"Mean Absolute Error : {mae:.2f} marks\")\n",
"print(f\"Root Mean Sq Error : {rmse:.2f} marks\")\n",
"\n",
"# Display 10 Sample Predictions\n",
"comparison = pd.DataFrame({\n",
" \"Actual Marks\": y_test.values[:10],\n",
" \"Predicted Marks\": np.round(y_pred[:10], 1),\n",
" \"Absolute Error\": np.round(np.abs(y_test.values[:10] - y_pred[:10]), 1)\n",
"})\n",
"comparison"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. Visualizing Actual vs Predicted Marks"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(12, 5))\n",
"\n",
"# Scatter plot\n",
"plt.subplot(1, 2, 1)\n",
"plt.scatter(y_test, y_pred, color='#2563EB', alpha=0.6, edgecolors='k', s=40)\n",
"plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], color='#DC2626', linestyle='--', linewidth=2, label='Perfect Fit')\n",
"plt.title(\"Actual vs Predicted Marks\", fontweight='bold')\n",
"plt.xlabel(\"Actual Marks\")\n",
"plt.ylabel(\"Predicted Marks\")\n",
"plt.grid(True, linestyle=':', alpha=0.6)\n",
"plt.legend()\n",
"\n",
"# Bar chart for 10 samples\n",
"plt.subplot(1, 2, 2)\n",
"indices = np.arange(10)\n",
"width = 0.35\n",
"plt.bar(indices - width/2, y_test.values[:10], width, label='Actual', color='#3B82F6')\n",
"plt.bar(indices + width/2, y_pred[:10], width, label='Predicted', color='#10B981')\n",
"plt.title(\"Comparison for 10 Students\", fontweight='bold')\n",
"plt.xlabel(\"Student Index\")\n",
"plt.ylabel(\"Marks\")\n",
"plt.xticks(indices, [f\"S{i+1}\" for i in indices])\n",
"plt.grid(True, linestyle=':', alpha=0.6)\n",
"plt.legend()\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 8. Test Prediction with a New Custom Student"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"custom_student = pd.DataFrame([{\n",
" 'study_hours': 7.0,\n",
" 'attendance': 90.0,\n",
" 'previous_marks': 82.0,\n",
" 'assignments_score': 9\n",
"}])\n",
"\n",
"predicted_score = model.predict(custom_student)[0]\n",
"print(f\"Predicted Final Marks for custom student: {predicted_score:.1f} / 100\")"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|