{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# GPA1 Multiple Regression\n",
        "\n",
        "Use GPA1 to estimate college GPA from high-school GPA and ACT. The cells compute results only after the real dataset is installed."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from pathlib import Path\n",
        "\n",
        "DATASET = \"GPA1.DTA\"\n",
        "VARIABLES = [\"colGPA\", \"hsGPA\", \"ACT\"]\n",
        "DATA_FOLDER = \"https://drive.google.com/drive/folders/1_STdcydIcst-opcbwOKRFzUXsgxQgBoS?usp=sharing\"\n",
        "\n",
        "if not Path(DATASET).exists():\n",
        "    raise FileNotFoundError(\n",
        "        \"Dataset file not installed yet\\n\"\n",
        "        f\"Dataset: GPA1\\n\"\n",
        "        f\"Variables needed: {', '.join(VARIABLES)}\\n\"\n",
        "        f\"Course data folder: {DATA_FOLDER}\\n\"\n",
        "        \"Admin upload instruction: upload the dataset in Admin -> Datasets and make it available to this notebook.\"\n",
        "    )\n",
        "\n",
        "print(\"Dataset found:\", DATASET)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "\n",
        "df = pd.read_stata(DATASET)[VARIABLES].dropna()\n",
        "print(df.head())\n",
        "print(\"Rows used:\", len(df))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "y = df[\"colGPA\"].to_numpy()\n",
        "X = np.column_stack([np.ones(len(df)), df[[\"hsGPA\", \"ACT\"]].to_numpy()])\n",
        "names = [\"intercept\", \"hsGPA\", \"ACT\"]\n",
        "beta = np.linalg.lstsq(X, y, rcond=None)[0]\n",
        "fitted = X @ beta\n",
        "residuals = y - fitted\n",
        "r_squared = 1 - np.sum(residuals ** 2) / np.sum((y - y.mean()) ** 2)\n",
        "\n",
        "for name, value in zip(names, beta):\n",
        "    print(f\"{name}: {value:.4f}\")\n",
        "print(\"R-squared:\", round(r_squared, 4))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Interpretation\n",
        "\n",
        "Each slope is read while holding the other included predictor fixed. For example, the high-school GPA coefficient compares students with the same ACT score."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
