{ "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 }