{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2dd1fa3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from easynn.feedforward import (\n",
    "    Layer,\n",
    "    ReLU,\n",
    "    LeakyReLU,\n",
    "    Regularization,\n",
    "    Linear,\n",
    "    FFNN,\n",
    "    MSELoss,\n",
    "    Softmax,\n",
    "    CrossEntropyLoss,\n",
    ")\n",
    "from easynn.schedulers import AdamScheduler\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.datasets import make_regression, make_classification\n",
    "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error, accuracy_score\n",
    "import logging\n",
    "\n",
    "logging.basicConfig(level=logging.WARNING)  # Set default logging level to WARNING"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73649f28",
   "metadata": {},
   "source": [
    "# Regression Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "79c55021",
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = make_regression(n_samples=1000, n_features=5, n_informative=3, noise=0.1)\n",
    "X = StandardScaler().fit_transform(X)\n",
    "y = y.reshape(-1, 1)\n",
    "y = StandardScaler().fit_transform(y)\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "8a88c060",
   "metadata": {},
   "outputs": [],
   "source": [
    "layers = [Layer(5, 5, ReLU()), Layer(5, 25, ReLU()), Layer(25, 1, Linear())]\n",
    "network = FFNN(layers, AdamScheduler(learning_rate=0.001, epochs=1000), MSELoss())\n",
    "network.fit(X_train, y_train)\n",
    "predictions = network.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "515e1e02",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'Training Loss Over Time')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 29988 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(network.scheduler.loss_history - min(network.scheduler.loss_history) + 1e-8)\n",
    "plt.yscale(\"log\")\n",
    "plt.xlabel(\"Epoch\")\n",
    "plt.ylabel(\"Loss\")\n",
    "plt.title(\"Training Loss Over Time\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1dd8fefc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'True vs Predicted Values')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 34116 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.scatter(y_test, predictions)\n",
    "plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], \"k--\", lw=2)\n",
    "plt.xlabel(\"True Values\")\n",
    "plt.ylabel(\"Predictions\")\n",
    "plt.title(\"True vs Predicted Values\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d3052118",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0019756351174760136"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mean_squared_error(y_test, predictions)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea3bd93f",
   "metadata": {},
   "source": [
    "# Classifier Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fc9641f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = make_classification(n_samples=1000, n_features=5, n_informative=3, n_classes=2)\n",
    "X = StandardScaler().fit_transform(X)\n",
    "y = y.reshape(-1, 1)\n",
    "y = OneHotEncoder(sparse_output=False).fit_transform(y)\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "00f52ecd",
   "metadata": {},
   "outputs": [],
   "source": [
    "layers = [Layer(5, 10, ReLU()), Layer(10, 5, ReLU()), Layer(5, 2, Softmax())]\n",
    "network = FFNN(\n",
    "    layers, AdamScheduler(learning_rate=0.001, epochs=1000), CrossEntropyLoss()\n",
    ")\n",
    "network.fit(X_train, y_train)\n",
    "predictions = network.predict(X_test)\n",
    "single_class_predictions = OneHotEncoder(sparse_output=False).fit_transform(\n",
    "    np.argmax(predictions, axis=1).reshape(-1, 1)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a3e32a73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.748"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "accuracy_score(y_test, single_class_predictions)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cec1615",
   "metadata": {},
   "source": [
    "# Runge Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "74212e01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pyoptim.optimizers as optimizers\n",
    "import pyoptim.datamanip as datamanip\n",
    "import pyoptim.plotting as plotting\n",
    "\n",
    "from sklearn.model_selection import train_test_split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9651d1c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(-1, 1, 100_000)\n",
    "y = datamanip.noise_data(datamanip.runge_function(x), 1.0)\n",
    "x_train, x_test, y_train, y_test = train_test_split(\n",
    "    x, y, test_size=0.2, random_state=datamanip.get_RNG().integers(0, 1e6)\n",
    ")\n",
    "\n",
    "x_train = x_train.reshape(-1, 1)\n",
    "x_test = x_test.reshape(-1, 1)\n",
    "y_train = y_train.reshape(-1, 1)\n",
    "y_test = y_test.reshape(-1, 1)\n",
    "\n",
    "X_train_scaled, X_test_scaled = datamanip.scale_data(x_train, x_test)\n",
    "y_train_scaled, y_test_scaled = datamanip.scale_data(y_train, y_test)\n",
    "\n",
    "\n",
    "def get_regression_model(\n",
    "    n_hidden_layers: int, n_neurons: int, activation: type = LeakyReLU\n",
    ") -> list[Layer]:\n",
    "    feature_dim = 1\n",
    "    target_dim = 1\n",
    "    layers = []\n",
    "    layers.append(Layer(feature_dim, n_neurons, activation_function=activation()))\n",
    "    for _ in range(n_hidden_layers - 1):\n",
    "        layers.append(Layer(n_neurons, n_neurons, activation_function=activation()))\n",
    "    layers.append(Layer(n_neurons, target_dim, activation_function=Linear()))\n",
    "    return layers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ec000a54",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hidden Layers: 1, Neurons: 50, Test MSE: 0.9177768024329133\n",
      "Hidden Layers: 1, Neurons: 100, Test MSE: 0.9167870523476759\n",
      "Hidden Layers: 2, Neurons: 50, Test MSE: 0.9136592028639727\n",
      "Hidden Layers: 2, Neurons: 100, Test MSE: 0.9135554326148551\n"
     ]
    }
   ],
   "source": [
    "for n_hidden in [1, 2]:\n",
    "    for n_neurons in [50, 100]:\n",
    "        layers = get_regression_model(n_hidden, n_neurons)\n",
    "        network = FFNN(\n",
    "            layers,\n",
    "            AdamScheduler(learning_rate=0.001, epochs=1000),\n",
    "            MSELoss(),\n",
    "        )\n",
    "        network.fit(X_train_scaled, y_train_scaled)\n",
    "        y_pred = network.predict(X_test_scaled)\n",
    "        test_mse = mean_squared_error(y_test_scaled, y_pred)\n",
    "        print(f\"Hidden Layers: {n_hidden}, Neurons: {n_neurons}, Test MSE: {test_mse}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "23e6f86c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# No Noise case\n",
    "x = np.linspace(-1, 1, 1000)\n",
    "y = datamanip.runge_function(x)\n",
    "x_train, x_test, y_train, y_test = train_test_split(\n",
    "    x, y, test_size=0.2, random_state=datamanip.get_RNG().integers(0, 1e6)\n",
    ")\n",
    "\n",
    "x_train = x_train.reshape(-1, 1)\n",
    "x_test = x_test.reshape(-1, 1)\n",
    "y_train = y_train.reshape(-1, 1)\n",
    "y_test = y_test.reshape(-1, 1)\n",
    "\n",
    "X_train_scaled, X_test_scaled = datamanip.scale_data(x_train, x_test)\n",
    "y_train_scaled, y_test_scaled = datamanip.scale_data(y_train, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "63a37bc9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hidden Layers: 1, Neurons: 50, Test MSE: 0.15527058910285813\n",
      "Hidden Layers: 1, Neurons: 100, Test MSE: 0.10180048256207899\n",
      "Hidden Layers: 2, Neurons: 50, Test MSE: 3.143921430819739e-05\n",
      "Hidden Layers: 2, Neurons: 100, Test MSE: 1.0371793804978556e-05\n"
     ]
    }
   ],
   "source": [
    "for n_hidden in [1, 2]:\n",
    "    for n_neurons in [50, 100]:\n",
    "        layers = get_regression_model(n_hidden, n_neurons)\n",
    "        network = FFNN(\n",
    "            layers,\n",
    "            AdamScheduler(learning_rate=0.001, epochs=1000),\n",
    "            MSELoss(),\n",
    "        )\n",
    "        network.fit(X_train_scaled, y_train_scaled)\n",
    "        y_pred_nn = network.predict(X_test_scaled)\n",
    "        test_mse = mean_squared_error(y_test_scaled, y_pred_nn)\n",
    "        print(f\"Hidden Layers: {n_hidden}, Neurons: {n_neurons}, Test MSE: {test_mse}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "9b568bde",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OLS Test MSE: 0.019835005963678293\n"
     ]
    }
   ],
   "source": [
    "x_train = datamanip.polynomial_features(x_train.flatten(), p=10)\n",
    "x_test = datamanip.polynomial_features(x_test.flatten(), p=10)\n",
    "X_train_scaled, X_test_scaled = datamanip.scale_data(x_train, x_test)\n",
    "\n",
    "\n",
    "beta = optimizers.Ridge_parameters(X_train_scaled, y_train_scaled, lam=1e-10)\n",
    "y_pred = X_test_scaled @ beta\n",
    "test_mse = mean_squared_error(y_test_scaled, y_pred)\n",
    "print(f\"OLS Test MSE: {test_mse}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "9db82101",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 107648 characters]",
      "text/plain": [
       "<Figure size 1350x900 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import plotting\n",
    "\n",
    "plt.scatter(x_test[:, 1], y_test_scaled, s=6, label=\"True Data\")\n",
    "plt.scatter(x_test[:, 1], y_pred, s=6, label=\"OLS Prediction\")\n",
    "plt.scatter(x_test[:, 1], y_pred_nn, s=6, label=\"NN Prediction\")\n",
    "plt.legend()\n",
    "plt.xlabel(\"$x$\")\n",
    "plt.ylabel(r\"$y / \\sigma_y$\")\n",
    "plt.savefig(\"runge_no_noise_comparison.pdf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79016960",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "project2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
