{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8adcbe0819b88578",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hit:1 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64  InRelease\n",
      "Hit:2 http://security.ubuntu.com/ubuntu jammy-security InRelease\n",
      "Hit:3 http://archive.ubuntu.com/ubuntu jammy InRelease\n",
      "Hit:4 http://archive.ubuntu.com/ubuntu jammy-updates InRelease\n",
      "Hit:5 http://archive.ubuntu.com/ubuntu jammy-backports InRelease\n",
      "Reading package lists... Done\n",
      "Reading package lists... Done\n",
      "Building dependency tree... Done\n",
      "Reading state information... Done\n",
      "graphviz is already the newest version (2.42.2-6ubuntu0.1).\n",
      "0 upgraded, 0 newly installed, 0 to remove and 121 not upgraded.\n",
      "Requirement already satisfied: tensorflow in /usr/local/lib/python3.11/dist-packages (2.14.0)\n",
      "Requirement already satisfied: absl-py>=1.0.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.0.0)\n",
      "Requirement already satisfied: astunparse>=1.6.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.6.3)\n",
      "Requirement already satisfied: flatbuffers>=23.5.26 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (23.5.26)\n",
      "Requirement already satisfied: gast!=0.5.0,!=0.5.1,!=0.5.2,>=0.2.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.5.4)\n",
      "Requirement already satisfied: google-pasta>=0.1.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.2.0)\n",
      "Requirement already satisfied: h5py>=2.9.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (3.9.0)\n",
      "Requirement already satisfied: libclang>=13.0.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (16.0.6)\n",
      "Requirement already satisfied: ml-dtypes==0.2.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.2.0)\n",
      "Requirement already satisfied: numpy>=1.23.5 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.26.0)\n",
      "Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (3.3.0)\n",
      "Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages (from tensorflow) (23.1)\n",
      "Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (4.24.3)\n",
      "Requirement already satisfied: setuptools in /usr/local/lib/python3.11/dist-packages (from tensorflow) (68.2.2)\n",
      "Requirement already satisfied: six>=1.12.0 in /usr/lib/python3/dist-packages (from tensorflow) (1.16.0)\n",
      "Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.3.0)\n",
      "Requirement already satisfied: typing-extensions>=3.6.6 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (4.8.0)\n",
      "Requirement already satisfied: wrapt<1.15,>=1.11.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.14.1)\n",
      "Requirement already satisfied: tensorflow-io-gcs-filesystem>=0.23.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (0.37.1)\n",
      "Requirement already satisfied: grpcio<2.0,>=1.24.3 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (1.58.0)\n",
      "Requirement already satisfied: tensorboard<2.15,>=2.14 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.14.0)\n",
      "Requirement already satisfied: tensorflow-estimator<2.15,>=2.14.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.14.0)\n",
      "Requirement already satisfied: keras<2.15,>=2.14.0 in /usr/local/lib/python3.11/dist-packages (from tensorflow) (2.14.0)\n",
      "Requirement already satisfied: wheel<1.0,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from astunparse>=1.6.0->tensorflow) (0.41.2)\n",
      "Requirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.15,>=2.14->tensorflow) (2.23.1)\n",
      "Requirement already satisfied: google-auth-oauthlib<1.1,>=0.5 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.15,>=2.14->tensorflow) (1.0.0)\n",
      "Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.15,>=2.14->tensorflow) (3.4.4)\n",
      "Requirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.15,>=2.14->tensorflow) (2.31.0)\n",
      "Requirement already satisfied: tensorboard-data-server<0.8.0,>=0.7.0 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.15,>=2.14->tensorflow) (0.7.1)\n",
      "Requirement already satisfied: werkzeug>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from tensorboard<2.15,>=2.14->tensorflow) (2.3.7)\n",
      "Requirement already satisfied: cachetools<6.0,>=2.0.0 in /usr/local/lib/python3.11/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.15,>=2.14->tensorflow) (5.3.1)\n",
      "Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.11/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.15,>=2.14->tensorflow) (0.3.0)\n",
      "Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.11/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.15,>=2.14->tensorflow) (4.9)\n",
      "Requirement already satisfied: urllib3>=2.0.5 in /usr/local/lib/python3.11/dist-packages (from google-auth<3,>=1.6.3->tensorboard<2.15,>=2.14->tensorflow) (2.0.5)\n",
      "Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.11/dist-packages (from google-auth-oauthlib<1.1,>=0.5->tensorboard<2.15,>=2.14->tensorflow) (1.3.1)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorboard<2.15,>=2.14->tensorflow) (3.2.0)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorboard<2.15,>=2.14->tensorflow) (3.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2.21.0->tensorboard<2.15,>=2.14->tensorflow) (2023.7.22)\n",
      "Requirement already satisfied: MarkupSafe>=2.1.1 in /usr/local/lib/python3.11/dist-packages (from werkzeug>=1.0.1->tensorboard<2.15,>=2.14->tensorflow) (2.1.3)\n",
      "Requirement already satisfied: pyasn1<0.6.0,>=0.4.6 in /usr/local/lib/python3.11/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.15,>=2.14->tensorflow) (0.5.0)\n",
      "Requirement already satisfied: oauthlib>=3.0.0 in /usr/lib/python3/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<1.1,>=0.5->tensorboard<2.15,>=2.14->tensorflow) (3.2.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (1.26.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: pandas in /usr/local/lib/python3.11/dist-packages (2.2.3)\n",
      "Requirement already satisfied: numpy>=1.23.2 in /usr/local/lib/python3.11/dist-packages (from pandas) (1.26.0)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas) (2024.2)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas) (2024.2)\n",
      "Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: keras in /usr/local/lib/python3.11/dist-packages (2.14.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: scikit-learn in /usr/local/lib/python3.11/dist-packages (1.5.2)\n",
      "Requirement already satisfied: numpy>=1.19.5 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (1.26.0)\n",
      "Requirement already satisfied: scipy>=1.6.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (1.14.1)\n",
      "Requirement already satisfied: joblib>=1.2.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (1.4.2)\n",
      "Requirement already satisfied: threadpoolctl>=3.1.0 in /usr/local/lib/python3.11/dist-packages (from scikit-learn) (3.5.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: matplotlib in /usr/local/lib/python3.11/dist-packages (3.8.0)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.1.1)\n",
      "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (0.11.0)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (4.42.1)\n",
      "Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.4.5)\n",
      "Requirement already satisfied: numpy<2,>=1.21 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (1.26.0)\n",
      "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (23.1)\n",
      "Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (10.0.1)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (3.2.0)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.11/dist-packages (from matplotlib) (2.8.2)\n",
      "Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: joblib in /usr/local/lib/python3.11/dist-packages (1.4.2)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: pyarrow in /usr/local/lib/python3.11/dist-packages (18.0.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: fastparquet in /usr/local/lib/python3.11/dist-packages (2024.11.0)\n",
      "Requirement already satisfied: pandas>=1.5.0 in /usr/local/lib/python3.11/dist-packages (from fastparquet) (2.2.3)\n",
      "Requirement already satisfied: numpy in /usr/local/lib/python3.11/dist-packages (from fastparquet) (1.26.0)\n",
      "Requirement already satisfied: cramjam>=2.3 in /usr/local/lib/python3.11/dist-packages (from fastparquet) (2.9.0)\n",
      "Requirement already satisfied: fsspec in /usr/local/lib/python3.11/dist-packages (from fastparquet) (2024.10.0)\n",
      "Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages (from fastparquet) (23.1)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.0->fastparquet) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.0->fastparquet) (2024.2)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.5.0->fastparquet) (2024.2)\n",
      "Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.2->pandas>=1.5.0->fastparquet) (1.16.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: scipy in /usr/local/lib/python3.11/dist-packages (1.14.1)\n",
      "Requirement already satisfied: numpy<2.3,>=1.23.5 in /usr/local/lib/python3.11/dist-packages (from scipy) (1.26.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: seaborn in /usr/local/lib/python3.11/dist-packages (0.13.2)\n",
      "Requirement already satisfied: numpy!=1.24.0,>=1.20 in /usr/local/lib/python3.11/dist-packages (from seaborn) (1.26.0)\n",
      "Requirement already satisfied: pandas>=1.2 in /usr/local/lib/python3.11/dist-packages (from seaborn) (2.2.3)\n",
      "Requirement already satisfied: matplotlib!=3.6.1,>=3.4 in /usr/local/lib/python3.11/dist-packages (from seaborn) (3.8.0)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (1.1.1)\n",
      "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (0.11.0)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (4.42.1)\n",
      "Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (1.4.5)\n",
      "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (23.1)\n",
      "Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (10.0.1)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (3.2.0)\n",
      "Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.11/dist-packages (from matplotlib!=3.6.1,>=3.4->seaborn) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.2->seaborn) (2024.2)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.11/dist-packages (from pandas>=1.2->seaborn) (2024.2)\n",
      "Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.7->matplotlib!=3.6.1,>=3.4->seaborn) (1.16.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: tqdm in /usr/local/lib/python3.11/dist-packages (4.67.1)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: pydot in /usr/local/lib/python3.11/dist-packages (3.0.2)\n",
      "Requirement already satisfied: pyparsing>=3.0.9 in /usr/local/lib/python3.11/dist-packages (from pydot) (3.2.0)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: tensorflow-io in /usr/local/lib/python3.11/dist-packages (0.37.1)\n",
      "Requirement already satisfied: tensorflow-io-gcs-filesystem==0.37.1 in /usr/local/lib/python3.11/dist-packages (from tensorflow-io) (0.37.1)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n",
      "Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.11/dist-packages (0.23.0)\n",
      "Requirement already satisfied: packaging in /usr/local/lib/python3.11/dist-packages (from tensorflow-addons) (23.1)\n",
      "Requirement already satisfied: typeguard<3.0.0,>=2.7 in /usr/local/lib/python3.11/dist-packages (from tensorflow-addons) (2.13.3)\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython3 -m pip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "from opt_einsum.paths import branch_1\n",
    "!apt-get update\n",
    "!apt-get install graphviz -y\n",
    "\n",
    "!pip install tensorflow\n",
    "!pip install numpy\n",
    "!pip install pandas\n",
    "\n",
    "!pip install keras\n",
    "!pip install scikit-learn\n",
    "!pip install matplotlib\n",
    "!pip install joblib\n",
    "!pip install pyarrow\n",
    "!pip install fastparquet\n",
    "!pip install scipy\n",
    "!pip install seaborn\n",
    "!pip install tqdm\n",
    "!pip install pydot\n",
    "!pip install tensorflow-io\n",
    "!pip install tensorflow-addons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7a813e3cbca057b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.keras.layers import Dense, LSTM, MultiHeadAttention, Dropout, BatchNormalization, LayerNormalization, Input, Activation, Lambda, Bidirectional, Add, MaxPooling1D, SpatialDropout1D, GlobalAveragePooling1D, \\\n",
    "    GlobalMaxPooling1D, Concatenate\n",
    "from tensorflow.keras import regularizers\n",
    "from tensorflow.keras.models import Model\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import RobustScaler\n",
    "from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n",
    "from tensorflow.keras.optimizers import AdamW\n",
    "import json\n",
    "from datetime import datetime\n",
    "import matplotlib.pyplot as plt\n",
    "from tensorflow.keras.utils import plot_model\n",
    "import tensorflow_addons as tfa\n",
    "import os\n",
    "import joblib\n",
    "import seaborn as sns\n",
    "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, confusion_matrix\n",
    "from scipy import stats\n",
    "\n",
    "folder_name = datetime.now().strftime(\"%Y-%m-%d_%H-%M\")\n",
    "\n",
    "random_state_value = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b3f525e19f78a1da",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_season(date):\n",
    "    month = date.month\n",
    "    day = date.day\n",
    "    if (month == 12 and day >= 21) or (month <= 3 and day < 20):\n",
    "        return 'Winter'\n",
    "    elif (month == 3 and day >= 20) or (month <= 6 and day < 21):\n",
    "        return 'Spring'\n",
    "    elif (month == 6 and day >= 21) or (month <= 9 and day < 23):\n",
    "        return 'Summer'\n",
    "    elif (month == 9 and day >= 23) or (month <= 12 and day < 21):\n",
    "        return 'Autumn'\n",
    "    else:\n",
    "        return 'Unknown'\n",
    "\n",
    "\n",
    "def get_time_period(hour):\n",
    "    if 5 <= hour < 12:\n",
    "        return 'Morning'\n",
    "    elif 12 <= hour < 17:\n",
    "        return 'Afternoon'\n",
    "    elif 17 <= hour < 21:\n",
    "        return 'Evening'\n",
    "    else:\n",
    "        return 'Night'\n",
    "\n",
    "\n",
    "def add_time_features(df):\n",
    "    \"\"\"\n",
    "    Add time-based features to the DataFrame.\n",
    "    Works with both 'datetime' as column or index.\n",
    "    \"\"\"\n",
    "    # Se datetime è l'indice, lo usiamo direttamente\n",
    "    if isinstance(df.index, pd.DatetimeIndex):\n",
    "        datetime_col = df.index\n",
    "    else:\n",
    "        # Se datetime è una colonna, la convertiamo\n",
    "        if 'datetime' in df.columns:\n",
    "            datetime_col = pd.to_datetime(df['datetime'])\n",
    "        else:\n",
    "            raise ValueError(\"No datetime column or index found in DataFrame\")\n",
    "\n",
    "    # Creazione delle feature temporali\n",
    "    df['timestamp'] = datetime_col.astype(np.int64) // 10 ** 9\n",
    "    df['year'] = datetime_col.year\n",
    "    df['month'] = datetime_col.month\n",
    "    df['day'] = datetime_col.day\n",
    "    df['hour'] = datetime_col.hour\n",
    "    df['minute'] = datetime_col.minute\n",
    "    df['hour_sin'] = np.sin(datetime_col.hour * (2 * np.pi / 24))\n",
    "    df['hour_cos'] = np.cos(datetime_col.hour * (2 * np.pi / 24))\n",
    "    df['day_of_week'] = datetime_col.dayofweek\n",
    "    df['day_of_year'] = datetime_col.dayofyear\n",
    "    df['week_of_year'] = datetime_col.isocalendar().week.astype(int)\n",
    "    df['quarter'] = datetime_col.quarter\n",
    "    df['is_month_end'] = datetime_col.is_month_end.astype(int)\n",
    "    df['is_quarter_end'] = datetime_col.is_quarter_end.astype(int)\n",
    "    df['is_year_end'] = datetime_col.is_year_end.astype(int)\n",
    "    df['month_sin'] = np.sin(datetime_col.month * (2 * np.pi / 12))\n",
    "    df['month_cos'] = np.cos(datetime_col.month * (2 * np.pi / 12))\n",
    "    df['day_of_year_sin'] = np.sin(datetime_col.dayofyear * (2 * np.pi / 365.25))\n",
    "    df['day_of_year_cos'] = np.cos(datetime_col.dayofyear * (2 * np.pi / 365.25))\n",
    "    df['season'] = datetime_col.map(get_season)\n",
    "    df['time_period'] = datetime_col.hour.map(get_time_period)\n",
    "\n",
    "    return df\n",
    "\n",
    "\n",
    "def add_solar_features(df):\n",
    "    # Solar angle calculation\n",
    "    df['solar_angle'] = np.sin(df['day_of_year'] * (2 * np.pi / 365.25)) * np.sin(df['hour'] * (2 * np.pi / 24))\n",
    "\n",
    "    # Interactions between relevant features\n",
    "    df['cloud_temp_interaction'] = df['cloudcover'] * df['temp']\n",
    "    df['visibility_cloud_interaction'] = df['visibility'] * (100 - df['cloudcover'])\n",
    "\n",
    "    # Derived features\n",
    "    df['clear_sky_index'] = (100 - df['cloudcover']) / 100\n",
    "    df['temp_gradient'] = df['temp'] - df['tempmin']\n",
    "\n",
    "    return df\n",
    "\n",
    "\n",
    "def add_solar_specific_features(df):\n",
    "    \"\"\"\n",
    "    Aggiunge feature specifiche per la predizione della radiazione solare\n",
    "    combinando caratteristiche astronomiche e meteorologiche\n",
    "    \"\"\"\n",
    "    # Caratteristiche astronomiche\n",
    "    df['day_length'] = 12 + 3 * np.sin(2 * np.pi * (df['day_of_year'] - 81) / 365.25)\n",
    "    df['solar_noon'] = 12 - df['hour']\n",
    "    df['solar_elevation'] = np.sin(2 * np.pi * df['day_of_year'] / 365.25) * np.cos(2 * np.pi * df['solar_noon'] / 24)\n",
    "\n",
    "    # Angolo solare teorico\n",
    "    df['solar_angle'] = np.sin(df['hour_sin']) * np.sin(df['day_of_year_sin'])\n",
    "\n",
    "    # Interazioni con condizioni atmosferiche\n",
    "    df['cloud_elevation'] = df['cloudcover'] * df['solar_elevation']\n",
    "    df['visibility_elevation'] = df['visibility'] * df['solar_elevation']\n",
    "    df['uv_cloud_interaction'] = df['uvindex'] * (100 - df['cloudcover']) / 100\n",
    "\n",
    "    # Indici di chiarezza e trasmissione\n",
    "    df['clearness_index'] = (100 - df['cloudcover']) * df['visibility'] / 10000\n",
    "    df['atmospheric_attenuation'] = (df['pressure'] / 1013.25) * (1 - (df['humidity'] / 100) * 0.6)\n",
    "\n",
    "    # Radiazione teorica e attenuazione\n",
    "    df['theoretical_radiation'] = df['solar_angle'].clip(0, 1) * 1000\n",
    "    df['expected_radiation'] = df['theoretical_radiation'] * df['clearness_index']\n",
    "\n",
    "    # Rolling features\n",
    "    df['cloud_rolling_12h'] = df['cloudcover'].rolling(window=12).mean()\n",
    "    df['temp_rolling_12h'] = df['temp'].rolling(window=12).mean()\n",
    "    df['uv_rolling_12h'] = df['uvindex'].rolling(window=12).mean()\n",
    "\n",
    "    # Interazioni temperatura-radiazione\n",
    "    df['temp_radiation_potential'] = df['temp'] * df['solar_elevation']\n",
    "\n",
    "    return df\n",
    "\n",
    "\n",
    "def add_radiation_energy_features(df):\n",
    "    \"\"\"Adds specific features based on solarenergy and uvindex\"\"\"\n",
    "\n",
    "    # Assicuriamoci che l'indice sia di tipo datetime\n",
    "    if not isinstance(df.index, pd.DatetimeIndex):\n",
    "        df.index = pd.to_datetime(df['datetime'])\n",
    "\n",
    "    # Solar energy to UV ratio (independent from solarradiation)\n",
    "    df['energy_uv_ratio'] = df['solarenergy'] / (df['uvindex'] + 1e-6)\n",
    "\n",
    "    # Time aggregations\n",
    "    # Moving averages\n",
    "    windows = [3, 6, 12, 24]  # hours\n",
    "    for w in windows:\n",
    "        df[f'energy_rolling_mean_{w}h'] = df['solarenergy'].rolling(window=w).mean()\n",
    "        df[f'uv_rolling_mean_{w}h'] = df['uvindex'].rolling(window=w).mean()\n",
    "\n",
    "    # Daily aggregations utilizzando datetime\n",
    "    df['energy_daily_sum'] = df.groupby(df.index.date)['solarenergy'].transform('sum')\n",
    "    df['uv_daily_max'] = df.groupby(df.index.date)['uvindex'].transform('max')\n",
    "\n",
    "    # Changes\n",
    "    df['energy_change'] = df['solarenergy'].diff()\n",
    "    df['uv_change'] = df['uvindex'].diff()\n",
    "\n",
    "    # Lag features\n",
    "    lags = [1, 2, 3, 6, 12, 24]  # hours\n",
    "    for lag in lags:\n",
    "        df[f'energy_lag_{lag}h'] = df['solarenergy'].shift(lag)\n",
    "        df[f'uv_lag_{lag}h'] = df['uvindex'].shift(lag)\n",
    "\n",
    "    # Peak indicators\n",
    "    df['is_energy_peak'] = (df['solarenergy'] > df['energy_rolling_mean_6h'] * 1.2).astype(int)\n",
    "    df['is_uv_peak'] = (df['uvindex'] > df['uv_rolling_mean_6h'] * 1.2).astype(int)\n",
    "\n",
    "    # Aggiungiamo alcune metriche di volatilità\n",
    "    df['energy_volatility'] = df['energy_change'].rolling(window=24).std()\n",
    "    df['uv_volatility'] = df['uv_change'].rolling(window=24).std()\n",
    "\n",
    "    # Indice di intensità solare composito\n",
    "    df['solar_intensity_index'] = (df['solarenergy'] * df['uvindex']) / (df['cloudcover'] + 1e-6)\n",
    "\n",
    "    # Interazioni\n",
    "    df['uv_cloud_interaction'] = df['uvindex'] * (100 - df['cloudcover']) / 100\n",
    "    df['energy_temp_interaction'] = df['solarenergy'] * df['temp']\n",
    "\n",
    "    return df\n",
    "\n",
    "\n",
    "def add_advanced_features(df):\n",
    "    \"\"\"\n",
    "    Add all advanced features to the DataFrame\n",
    "    Assumes df has a DatetimeIndex\n",
    "    \"\"\"\n",
    "    # Verifichiamo che abbiamo un DatetimeIndex\n",
    "    if not isinstance(df.index, pd.DatetimeIndex):\n",
    "        raise ValueError(\"DataFrame must have a DatetimeIndex\")\n",
    "\n",
    "    # Existing features\n",
    "    df = add_time_features(df)\n",
    "    df = add_solar_features(df)\n",
    "    df = add_solar_specific_features(df)\n",
    "    df = add_radiation_energy_features(df)\n",
    "\n",
    "    # Weather variable interactions\n",
    "    df['temp_humidity'] = df['temp'] * df['humidity']\n",
    "    df['temp_cloudcover'] = df['temp'] * df['cloudcover']\n",
    "    df['visibility_cloudcover'] = df['visibility'] * df['cloudcover']\n",
    "\n",
    "    # Derived features\n",
    "    df['clear_sky_factor'] = (100 - df['cloudcover']) / 100\n",
    "    df['temp_humidity_interaction'] = df['temp'] * df['humidity'] / 100\n",
    "    df['atmospheric_transparency'] = (100 - df['cloudcover']) * (df['visibility'] / 10)\n",
    "\n",
    "    # Rolling means\n",
    "    df['temp_rolling_mean_6h'] = df['temp'].rolling(window=6).mean()\n",
    "    df['cloudcover_rolling_mean_6h'] = df['cloudcover'].rolling(window=6).mean()\n",
    "\n",
    "    # Lag features\n",
    "    df['temp_1h_lag'] = df['temp'].shift(1)\n",
    "    df['cloudcover_1h_lag'] = df['cloudcover'].shift(1)\n",
    "    df['humidity_1h_lag'] = df['humidity'].shift(1)\n",
    "\n",
    "    # Extreme conditions indicator\n",
    "    df['extreme_conditions'] = ((df['temp'] > df['temp'].quantile(0.75)) &\n",
    "                                (df['humidity'] < df['humidity'].quantile(0.25))).astype(int)\n",
    "\n",
    "    # One-hot encoding for categorical features\n",
    "    df = pd.get_dummies(df, columns=['season', 'time_period'])\n",
    "\n",
    "    return df\n",
    "\n",
    "\n",
    "def prepare_advanced_data(df):\n",
    "    \"\"\"\n",
    "    Prepare data for advanced modeling with proper datetime handling\n",
    "    \"\"\"\n",
    "    # Assicuriamoci che abbiamo una copia del DataFrame\n",
    "    df = df.copy()\n",
    "\n",
    "    # Verifichiamo se datetime è già l'indice\n",
    "    if not isinstance(df.index, pd.DatetimeIndex):\n",
    "        if 'datetime' in df.columns:\n",
    "            df['datetime'] = pd.to_datetime(df['datetime'])\n",
    "            df.set_index('datetime', inplace=True)\n",
    "        else:\n",
    "            raise ValueError(\"No datetime column or index found in DataFrame\")\n",
    "\n",
    "    # Ordiniamo il DataFrame per datetime\n",
    "    df = df.sort_index()\n",
    "\n",
    "    # Apply feature engineering functions\n",
    "    df = add_advanced_features(df)\n",
    "\n",
    "    #all_columns = list(df.columns)\n",
    "    #print(all_columns)\n",
    "\n",
    "    features = {\n",
    "        # Primary Features (strong direct correlation)\n",
    "        'primary_features': [\n",
    "            'uvindex',  # Direct radiation indicator\n",
    "            'cloudcover',  # Cloud coverage\n",
    "            'visibility',  # Atmospheric transparency\n",
    "            'temp',  # Temperature\n",
    "            'pressure',  # Atmospheric pressure\n",
    "            'humidity',  # Humidity\n",
    "        ],\n",
    "\n",
    "        # Astronomical and Temporal Features\n",
    "        'astronomical_features': [\n",
    "            'solar_elevation',  # Solar elevation\n",
    "            'solar_angle',  # Solar angle\n",
    "            'day_length',  # Day length\n",
    "            'hour_sin',  # Daily cycle\n",
    "            'hour_cos',\n",
    "            'day_of_year_sin',  # Annual cycle\n",
    "            'day_of_year_cos',\n",
    "            'month_sin',  # Monthly cycle\n",
    "            'month_cos',\n",
    "        ],\n",
    "\n",
    "        # Key Indices and Interactions\n",
    "        'key_interactions': [\n",
    "            'clear_sky_index',  # Clear sky index\n",
    "            'atmospheric_attenuation',  # Atmospheric attenuation\n",
    "            'theoretical_radiation',  # Theoretical radiation\n",
    "            'expected_radiation',  # Expected radiation\n",
    "            'cloud_elevation',  # Cloud-elevation interaction\n",
    "            'visibility_elevation',  # Visibility-elevation interaction\n",
    "            'uv_cloud_interaction',  # UV-cloud interaction\n",
    "            'temp_radiation_potential',  # Temperature-radiation potential\n",
    "        ],\n",
    "\n",
    "        # Rolling Features (temporal trends)\n",
    "        'rolling_features': [\n",
    "            'cloud_rolling_12h',  # Cloud coverage moving average\n",
    "            'temp_rolling_12h',  # Temperature moving average\n",
    "            'uv_rolling_12h',  # UV moving average\n",
    "            'cloudcover_rolling_mean_6h',\n",
    "            'temp_rolling_mean_6h',\n",
    "        ],\n",
    "\n",
    "        # Lag Features (most recent)\n",
    "        'lag_features': [\n",
    "            'temp_1h_lag',  # 1-hour temperature lag\n",
    "            'cloudcover_1h_lag',  # 1-hour cloud coverage lag\n",
    "            'humidity_1h_lag',  # 1-hour humidity lag\n",
    "            'uv_lag_1h',  # 1-hour UV lag\n",
    "        ],\n",
    "\n",
    "        # Categorical Features\n",
    "        'categorical_features': [\n",
    "            'season_Spring',  # Seasons\n",
    "            'season_Summer',\n",
    "            'season_Autumn',\n",
    "            'season_Winter',\n",
    "            'time_period_Morning',  # Time periods\n",
    "            'time_period_Afternoon',\n",
    "            'time_period_Evening',\n",
    "            'time_period_Night',\n",
    "        ]\n",
    "    }\n",
    "\n",
    "    final_features = [feature for group in features.values() for feature in group]\n",
    "\n",
    "    # Handle missing values\n",
    "    target_variables = ['solarradiation', 'solarenergy', 'uvindex']\n",
    "    for column in final_features + target_variables:\n",
    "        if column in df.columns:\n",
    "            df[column] = df[column].interpolate(method='time')\n",
    "    df.fillna(0, inplace=True)\n",
    "\n",
    "    # Temporal split\n",
    "    data_after_2010 = df[df['year'] >= 2010].copy()\n",
    "    data_before_2010 = df[df['year'] < 2010].copy()\n",
    "\n",
    "    X = data_after_2010[final_features]\n",
    "    y = data_after_2010['solarradiation']\n",
    "    X_to_predict = data_before_2010[final_features]\n",
    "\n",
    "    # Train-test split\n",
    "    X_train, X_test, y_train, y_test = train_test_split(\n",
    "        X, y, test_size=0.2, random_state=random_state_value, shuffle=False\n",
    "    )\n",
    "\n",
    "    # Scaling\n",
    "    scaler_X = RobustScaler()\n",
    "    X_train_scaled = scaler_X.fit_transform(X_train)\n",
    "    X_test_scaled = scaler_X.transform(X_test)\n",
    "    X_to_predict_scaled = scaler_X.transform(X_to_predict)\n",
    "\n",
    "    scaler_y = RobustScaler()\n",
    "    y_train_scaled = scaler_y.fit_transform(y_train.values.reshape(-1, 1))\n",
    "    y_test_scaled = scaler_y.transform(y_test.values.reshape(-1, 1))\n",
    "\n",
    "    # Print info about selected features\n",
    "    print(\"\\nSelected features:\")\n",
    "    print(f\"Number of features: {len(final_features)}\")\n",
    "    print(\"Features list:\", final_features)\n",
    "\n",
    "    return X_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled, scaler_X, scaler_y, final_features, X_to_predict_scaled\n",
    "\n",
    "\n",
    "def create_sequence_data(X, sequence_length=24):\n",
    "    \"\"\"\n",
    "    Converts data into sequences for LSTM input\n",
    "    sequence_length represents how many previous hours to consider\n",
    "    \"\"\"\n",
    "    sequences = []\n",
    "    for i in range(len(X) - sequence_length + 1):\n",
    "        sequences.append(X[i:i + sequence_length])\n",
    "    return np.array(sequences)\n",
    "\n",
    "\n",
    "def prepare_hybrid_data(df):\n",
    "    X_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled, scaler_X, scaler_y, features, X_to_predict_scaled = prepare_advanced_data(df)\n",
    "\n",
    "    # Convert data into sequences\n",
    "    sequence_length = 24  # 24 hours of historical data\n",
    "\n",
    "    X_train_seq = create_sequence_data(X_train_scaled, sequence_length)\n",
    "    X_test_seq = create_sequence_data(X_test_scaled, sequence_length)\n",
    "\n",
    "    # Adjust y by removing the first (sequence_length-1) elements\n",
    "    y_train = y_train_scaled[sequence_length - 1:]\n",
    "    y_test = y_test_scaled[sequence_length - 1:]\n",
    "\n",
    "    X_to_predict_seq = create_sequence_data(X_to_predict_scaled, sequence_length)\n",
    "\n",
    "    return X_train_seq, X_test_seq, y_train, y_test, scaler_X, scaler_y, features, X_to_predict_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9dff3259-b376-4cfc-89d8-ab2ea18aaa5e",
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "outputs": [],
   "source": [
    "def create_residual_lstm_layer(x, units, dropout_rate, l2_reg=0.01, return_sequences=True, survival_probability=0.8):\n",
    "    \"\"\"\n",
    "    Creates a bidirectional LSTM layer with residual connections and regularization.\n",
    "\n",
    "    Parameters:\n",
    "        x: Input tensor\n",
    "        units: Number of LSTM units\n",
    "        dropout_rate: Dropout rate for regularization\n",
    "        l2_reg: L2 regularization factor\n",
    "        return_sequences: Whether to return sequences or just the last output\n",
    "        survival_probability: Probability of layer survival for stochastic depth\n",
    "    \"\"\"\n",
    "    residual = x\n",
    "    x = Bidirectional(LSTM(units, return_sequences=return_sequences, kernel_regularizer=regularizers.l2(l2_reg)))(x)\n",
    "    x = LayerNormalization()(x)\n",
    "    x = Dropout(dropout_rate)(x)\n",
    "\n",
    "    if return_sequences:\n",
    "        if int(residual.shape[-1]) != 2 * units:\n",
    "            residual = Dense(2 * units, activation='linear')(residual)\n",
    "        x = tfa.layers.StochasticDepth(survival_probability)([x, residual])\n",
    "    return x\n",
    "\n",
    "\n",
    "def attention_block(x, units, num_heads=8, survival_probability=0.8):\n",
    "    \"\"\"\n",
    "    Creates a multi-head attention block with residual connections.\n",
    "\n",
    "    Parameters:\n",
    "        x: Input tensor\n",
    "        units: Dimension of the key space\n",
    "        num_heads: Number of attention heads\n",
    "        survival_probability: Probability of layer survival for stochastic depth\n",
    "    \"\"\"\n",
    "    attention = MultiHeadAttention(num_heads=num_heads, key_dim=units)(x, x)\n",
    "    x = tfa.layers.StochasticDepth(survival_probability)([x, attention])\n",
    "    x = LayerNormalization()(x)\n",
    "    return x\n",
    "\n",
    "\n",
    "def create_solarradiation_model(input_shape, folder_name, l2_lambda=0.005, min_output=0, max_output=1):\n",
    "    \"\"\"\n",
    "    Creates a deep learning model for solar radiation prediction using LSTM and attention mechanisms.\n",
    "\n",
    "    Parameters:\n",
    "        input_shape: Shape of input data\n",
    "        folder_name: Directory to save model architecture visualization\n",
    "        l2_lambda: L2 regularization factor\n",
    "    \"\"\"\n",
    "    inputs = Input(shape=input_shape)\n",
    "\n",
    "    # Progressive hyperparameters for model architecture\n",
    "    survival_probs = [0.9, 0.8, 0.7, 0.6]  # Decreasing survival probabilities for deeper layers\n",
    "    attention_survival_probs = [0.85, 0.75, 0.65, 0.55]  # Survival probabilities for attention blocks\n",
    "    lstm_units = [256, 128, 64, 32]  # Decreasing number of units for LSTM layers\n",
    "    dropout_rates = [0.4, 0.3, 0.2, 0.2]  # Decreasing dropout rates\n",
    "    attention_heads = [32, 24, 16, 8]  # Decreasing number of attention heads\n",
    "\n",
    "    lstm_blocks = 4\n",
    "    # Main network architecture\n",
    "    x = inputs\n",
    "    for i in range(lstm_blocks):\n",
    "        # LSTM layer with residual connections\n",
    "        x = create_residual_lstm_layer(\n",
    "            x,\n",
    "            units=lstm_units[i],\n",
    "            dropout_rate=dropout_rates[i],\n",
    "            l2_reg=l2_lambda,\n",
    "            return_sequences=True,\n",
    "            survival_probability=survival_probs[i]\n",
    "        )\n",
    "        # Attention block\n",
    "        x = attention_block(\n",
    "            x,\n",
    "            units=lstm_units[i],\n",
    "            num_heads=attention_heads[i],\n",
    "            survival_probability=attention_survival_probs[i]\n",
    "        )\n",
    "        if i < lstm_blocks - 1:  # No pooling after last LSTM layer\n",
    "            x = MaxPooling1D()(x)\n",
    "\n",
    "    # Final LSTM layer for sequence aggregation\n",
    "    x = create_residual_lstm_layer(\n",
    "        x,\n",
    "        units=32,\n",
    "        dropout_rate=0.1,\n",
    "        l2_reg=l2_lambda,\n",
    "        return_sequences=False,\n",
    "        survival_probability=0.6\n",
    "    )\n",
    "\n",
    "    # Dense layers for final prediction\n",
    "    dense_units = [128, 64, 32]\n",
    "    dense_dropout = [0.2, 0.1, 0.05]\n",
    "\n",
    "    for units, dropout in zip(dense_units, dense_dropout):\n",
    "        x = Dense(units, kernel_regularizer=regularizers.l2(l2_lambda))(x)\n",
    "        x = BatchNormalization()(x)\n",
    "        x = Activation('swish')(x)\n",
    "        x = Dropout(dropout)(x)\n",
    "\n",
    "    # Output layer with value clipping\n",
    "    outputs = Dense(1)(x)\n",
    "    outputs = Lambda(lambda x: tf.clip_by_value(x, min_output, max_output))(outputs)\n",
    "\n",
    "    # Model compilation\n",
    "    model = Model(inputs=inputs, outputs=outputs, name=\"SolarRadiationModel\")\n",
    "\n",
    "    # Improved loss function\n",
    "    def hybrid_focal_loss(y_true, y_pred):\n",
    "        # MSE with focal weighting\n",
    "        mse = tf.square(y_true - y_pred)\n",
    "        error_ratio = tf.abs(y_true - y_pred) / (tf.abs(y_true) + 1.0)\n",
    "        focal_weight = tf.pow(error_ratio, 2)\n",
    "        weighted_mse = focal_weight * mse\n",
    "\n",
    "        # MAE component\n",
    "        mae = tf.abs(y_true - y_pred)\n",
    "\n",
    "        return tf.reduce_mean(0.7 * weighted_mse + 0.3 * mae)\n",
    "\n",
    "    # Custom metrics\n",
    "    def rmse(y_true, y_pred):\n",
    "        return tf.sqrt(tf.reduce_mean(tf.square(y_true - y_pred)))\n",
    "\n",
    "    def custom_mape(y_true, y_pred):\n",
    "        epsilon = 1e-7\n",
    "        diff = tf.abs((y_true - y_pred) / (y_true + epsilon))\n",
    "        diff = tf.clip_by_value(diff, 0, 1)\n",
    "        return tf.reduce_mean(diff) * 100\n",
    "\n",
    "    # Optimizer\n",
    "    optimizer = AdamW(\n",
    "        learning_rate=0.0003,\n",
    "        beta_1=0.9,\n",
    "        beta_2=0.999,\n",
    "        epsilon=1e-7,\n",
    "        weight_decay=0.001,\n",
    "        amsgrad=True\n",
    "    )\n",
    "\n",
    "    model.compile(\n",
    "        optimizer=optimizer,\n",
    "        loss=hybrid_focal_loss,\n",
    "        metrics=['mse', 'mae', rmse, custom_mape]\n",
    "    )\n",
    "\n",
    "    model.summary()\n",
    "\n",
    "    plot_model(model,\n",
    "               to_file=f'{folder_name}_model_architecture.png',\n",
    "               show_shapes=True,\n",
    "               show_layer_names=True,\n",
    "               dpi=150,\n",
    "               show_layer_activations=True)\n",
    "\n",
    "    return model\n",
    "\n",
    "\n",
    "def evaluate_solarradiation_predictions(y_true, y_pred, hour=None, folder_name=None):\n",
    "    \"\"\"\n",
    "    Comprehensive evaluation of solar radiation predictions with detailed analysis and visualizations.\n",
    "\n",
    "    Parameters:\n",
    "    -----------\n",
    "    y_true : array-like\n",
    "        Actual solar radiation values (W/m²)\n",
    "    y_pred : array-like\n",
    "        Predicted solar radiation values (W/m²)\n",
    "    hour : array-like, optional\n",
    "        Array of hours corresponding to predictions, for temporal analysis\n",
    "    folder_name : str, optional\n",
    "        Directory to save analysis plots\n",
    "\n",
    "    Returns:\n",
    "    --------\n",
    "    dict\n",
    "        Dictionary containing all calculated metrics\n",
    "    \"\"\"\n",
    "\n",
    "    # Data preparation\n",
    "    y_true = np.array(y_true).ravel()\n",
    "    y_pred = np.array(y_pred).ravel()\n",
    "    errors = y_pred - y_true\n",
    "\n",
    "    # Basic metrics calculation\n",
    "    mae_raw = mean_absolute_error(y_true, y_pred)\n",
    "    rmse_raw = np.sqrt(mean_squared_error(y_true, y_pred))\n",
    "    r2_raw = r2_score(y_true, y_pred)\n",
    "    \n",
    "    # Corrected MAPE calculation\n",
    "    mask = y_true > 10  # Consider only values above 10 W/m²\n",
    "    if np.any(mask):\n",
    "        mape = np.mean(np.abs((y_true[mask] - y_pred[mask]) / y_true[mask])) * 100\n",
    "    else:\n",
    "        mape = np.nan\n",
    "\n",
    "    # Corrected error margin accuracy\n",
    "    within_5_percent = np.mean(np.abs(errors) <= 5) * 100  # Within 5 W/m²\n",
    "    within_10_percent = np.mean(np.abs(errors) <= 10) * 100  # Within 10 W/m²\n",
    "    within_20_percent = np.mean(np.abs(errors) <= 20) * 100  # Within 20 W/m²\n",
    "\n",
    "    # Radiation level classification\n",
    "    def get_radiation_level(value):\n",
    "        if value <= 200:\n",
    "            return 'Very Low'\n",
    "        elif value <= 400:\n",
    "            return 'Low'\n",
    "        elif value <= 600:\n",
    "            return 'Moderate'\n",
    "        elif value <= 800:\n",
    "            return 'High'\n",
    "        elif value <= 1000:\n",
    "            return 'Very High'\n",
    "        else:\n",
    "            return 'Extreme'\n",
    "\n",
    "    # Calculate radiation levels\n",
    "    y_true_levels = [get_radiation_level(v) for v in y_true]\n",
    "    y_pred_levels = [get_radiation_level(v) for v in y_pred]\n",
    "    level_accuracy = np.mean([t == p for t, p in zip(y_true_levels, y_pred_levels)])\n",
    "\n",
    "    # Print main metrics\n",
    "    print(\"\\nSolar Radiation Prediction Metrics:\")\n",
    "    print(\"\\nAbsolute Metrics:\")\n",
    "    print(f\"MAE: {mae_raw:.2f} W/m²\")\n",
    "    print(f\"RMSE: {rmse_raw:.2f} W/m²\")\n",
    "    print(f\"R² Score: {r2_raw:.3f}\")\n",
    "    print(f\"MAPE: {mape:.2f}%\" if not np.isnan(mape) else \"MAPE: N/A (insufficient data)\")\n",
    "\n",
    "    print(\"\\nAccuracy Metrics:\")\n",
    "    print(f\"Within ±5 W/m²: {within_5_percent:.1f}%\")\n",
    "    print(f\"Within ±10 W/m²: {within_10_percent:.1f}%\")\n",
    "    print(f\"Within ±20 W/m²: {within_20_percent:.1f}%\")\n",
    "\n",
    "    print(\"\\nLevel Accuracy:\")\n",
    "    print(f\"Level Accuracy: {level_accuracy * 100:.1f}%\")\n",
    "\n",
    "    # Confusion matrix for radiation levels\n",
    "    cm = confusion_matrix(y_true_levels, y_pred_levels)\n",
    "    print(\"\\nConfusion Matrix for Radiation Levels:\")\n",
    "    cm_df = pd.DataFrame(\n",
    "        cm,\n",
    "        columns=['Very Low', 'Low', 'Moderate', 'High', 'Very High', 'Extreme'],\n",
    "        index=['Very Low', 'Low', 'Moderate', 'High', 'Very High', 'Extreme']\n",
    "    )\n",
    "    print(cm_df)\n",
    "\n",
    "    # Time period analysis\n",
    "    if hour is not None:\n",
    "        day_periods = {\n",
    "            'Morning (5-11)': (5, 11),\n",
    "            'Noon (11-13)': (11, 13),\n",
    "            'Afternoon (13-17)': (13, 17),\n",
    "            'Evening (17-21)': (17, 21),\n",
    "            'Night (21-5)': (21, 5)\n",
    "        }\n",
    "\n",
    "        print(\"\\nAnalysis by Time Period:\")\n",
    "        for period, (start, end) in day_periods.items():\n",
    "            if start < end:\n",
    "                mask = (hour >= start) & (hour < end)\n",
    "            else:\n",
    "                mask = (hour >= start) | (hour < end)\n",
    "\n",
    "            if np.any(mask):\n",
    "                period_mae = mean_absolute_error(y_true[mask], y_pred[mask])\n",
    "                \n",
    "                # Corrected period MAPE calculation\n",
    "                period_mask = mask & (y_true > 10)\n",
    "                if np.any(period_mask):\n",
    "                    period_mape = np.mean(np.abs((y_true[period_mask] - y_pred[period_mask]) / y_true[period_mask])) * 100\n",
    "                    print(f\"\\n{period}:\")\n",
    "                    print(f\"MAE: {period_mae:.2f} W/m²\")\n",
    "                    print(f\"MAPE: {period_mape:.2f}%\")\n",
    "                else:\n",
    "                    print(f\"\\n{period}:\")\n",
    "                    print(f\"MAE: {period_mae:.2f} W/m²\")\n",
    "                    print(\"MAPE: N/A (insufficient data)\")\n",
    "\n",
    "    # Visualizations\n",
    "    if folder_name is not None:\n",
    "        try:\n",
    "            # Figure 1: Main analysis plots\n",
    "            plt.figure(figsize=(20, 15))\n",
    "\n",
    "            # Plot 1: Scatter plot of actual vs predicted values\n",
    "            plt.subplot(3, 2, 1)\n",
    "            plt.scatter(y_true, y_pred, alpha=0.5)\n",
    "            plt.plot([y_true.min(), y_true.max()], [y_true.min(), y_true.max()], 'r--', lw=2)\n",
    "            plt.xlabel('Actual Radiation (W/m²)')\n",
    "            plt.ylabel('Predicted Radiation (W/m²)')\n",
    "            plt.title('Actual vs Predicted Values')\n",
    "            plt.grid(True)\n",
    "\n",
    "            # Plot 2: Absolute error distribution\n",
    "            plt.subplot(3, 2, 2)\n",
    "            plt.hist(errors, bins=50, alpha=0.7)\n",
    "            plt.xlabel('Prediction Error (W/m²)')\n",
    "            plt.ylabel('Frequency')\n",
    "            plt.title('Error Distribution')\n",
    "            plt.grid(True)\n",
    "\n",
    "            # Plot 3: Percentage error distribution (only for values > 10 W/m²)\n",
    "            plt.subplot(3, 2, 3)\n",
    "            mask = y_true > 10\n",
    "            if np.any(mask):\n",
    "                percentage_errors = ((y_pred[mask] - y_true[mask]) / y_true[mask]) * 100\n",
    "                plt.hist(np.clip(percentage_errors, -100, 100), bins=50, alpha=0.7)\n",
    "                plt.xlabel('Percentage Error (%)')\n",
    "                plt.ylabel('Frequency')\n",
    "                plt.title('Percentage Error Distribution (for values > 10 W/m²)')\n",
    "                plt.grid(True)\n",
    "\n",
    "            # Plot 4: Errors vs actual values\n",
    "            plt.subplot(3, 2, 4)\n",
    "            plt.scatter(y_true, errors, alpha=0.5)\n",
    "            plt.axhline(y=0, color='r', linestyle='--')\n",
    "            plt.xlabel('Actual Radiation (W/m²)')\n",
    "            plt.ylabel('Error (W/m²)')\n",
    "            plt.title('Errors vs Actual Values')\n",
    "            plt.grid(True)\n",
    "\n",
    "            # Plot 5: Error boxplot by radiation level\n",
    "            plt.subplot(3, 2, 5)\n",
    "            sns.boxplot(x=[get_radiation_level(v) for v in y_true], y=errors)\n",
    "            plt.xticks(rotation=45)\n",
    "            plt.xlabel('Radiation Level')\n",
    "            plt.ylabel('Error (W/m²)')\n",
    "            plt.title('Error Distribution by Level')\n",
    "\n",
    "            # Plot 6: Confusion matrix heatmap\n",
    "            plt.subplot(3, 2, 6)\n",
    "            sns.heatmap(cm_df, annot=True, fmt='d', cmap='Blues')\n",
    "            plt.title('Confusion Matrix')\n",
    "            plt.xticks(rotation=45)\n",
    "            plt.yticks(rotation=45)\n",
    "\n",
    "            plt.tight_layout()\n",
    "            filename = f'{folder_name}_radiation_analysis.png'\n",
    "            plt.savefig(filename, dpi=300, bbox_inches='tight')\n",
    "            print(f\"\\nPlot saved as: {filename}\")\n",
    "            plt.close()\n",
    "\n",
    "        except Exception as e:\n",
    "            print(f\"\\nError saving plots: {str(e)}\")\n",
    "\n",
    "    # Additional error statistics\n",
    "    print(\"\\nError Statistics:\")\n",
    "    print(f\"Mean error: {np.mean(errors):.3f}\")\n",
    "    print(f\"Error standard deviation: {np.std(errors):.3f}\")\n",
    "    print(f\"Median error: {np.median(errors):.3f}\")\n",
    "    print(f\"95th percentile absolute error: {np.percentile(np.abs(errors), 95):.3f}\")\n",
    "\n",
    "    # Return structured metrics\n",
    "    metrics = {\n",
    "        'absolute': {\n",
    "            'mae': mae_raw,\n",
    "            'rmse': rmse_raw,\n",
    "            'r2': r2_raw,\n",
    "            'mape': float(mape) if not np.isnan(mape) else None\n",
    "        },\n",
    "        'accuracy': {\n",
    "            'within_5_wm2': float(within_5_percent),\n",
    "            'within_10_wm2': float(within_10_percent),\n",
    "            'within_20_wm2': float(within_20_percent)\n",
    "        },\n",
    "        'categorical': {\n",
    "            'level_accuracy': float(level_accuracy)\n",
    "        },\n",
    "        'error_stats': {\n",
    "            'mean': float(np.mean(errors)),\n",
    "            'std': float(np.std(errors)),\n",
    "            'median': float(np.median(errors)),\n",
    "            'p95_abs': float(np.percentile(np.abs(errors), 95))\n",
    "        }\n",
    "    }\n",
    "\n",
    "    return metrics\n",
    "\n",
    "\n",
    "def plot_training_history(history, folder_name=None):\n",
    "    \"\"\"\n",
    "    Visualize and save training loss and metrics plots\n",
    "\n",
    "    Parameters:\n",
    "    -----------\n",
    "    history : tensorflow.keras.callbacks.History\n",
    "        History object returned by model training\n",
    "    folder_name : str\n",
    "        Directory to save the plots and metrics\n",
    "    \"\"\"\n",
    "\n",
    "    try:\n",
    "        # Create figure\n",
    "        plt.figure(figsize=(12, 4))\n",
    "\n",
    "        # Loss plot\n",
    "        plt.subplot(1, 2, 1)\n",
    "        plt.plot(history.history['loss'], label='Training Loss')\n",
    "        plt.plot(history.history['val_loss'], label='Validation Loss')\n",
    "        plt.title('Model Loss')\n",
    "        plt.xlabel('Epoch')\n",
    "        plt.ylabel('Loss')\n",
    "        plt.legend()\n",
    "        plt.grid(True)\n",
    "\n",
    "        # MAE plot\n",
    "        plt.subplot(1, 2, 2)\n",
    "        plt.plot(history.history['mae'], label='Training MAE')\n",
    "        plt.plot(history.history['val_mae'], label='Validation MAE')\n",
    "        plt.title('Model MAE')\n",
    "        plt.xlabel('Epoch')\n",
    "        plt.ylabel('MAE')\n",
    "        plt.legend()\n",
    "        plt.grid(True)\n",
    "\n",
    "        plt.tight_layout()\n",
    "\n",
    "        if folder_name is not None:\n",
    "            # Generate filename with timestamp\n",
    "            filename = f'{folder_name}_training_history.png'  # Rimossa parentesi extra\n",
    "\n",
    "            # Save figure\n",
    "            plt.savefig(filename, dpi=300, bbox_inches='tight')\n",
    "            print(f\"\\nTraining history plot saved as: {filename}\")\n",
    "\n",
    "        # Save numerical data in CSV format\n",
    "        history_df = pd.DataFrame({\n",
    "            'epoch': range(1, len(history.history['loss']) + 1),\n",
    "            'training_loss': history.history['loss'],\n",
    "            'validation_loss': history.history['val_loss'],\n",
    "            'training_mae': history.history['mae'],\n",
    "            'validation_mae': history.history['val_mae']})\n",
    "\n",
    "        if folder_name is not None:\n",
    "            csv_filename = f'{folder_name}_training_history.csv'  # Rimossa parentesi extra\n",
    "            history_df.to_csv(csv_filename, index=False)\n",
    "            print(f\"Training history data saved as: {csv_filename}\")\n",
    "\n",
    "        # Calculate and save final statistics\n",
    "        final_stats = {\n",
    "            'final_training_loss': history.history['loss'][-1],\n",
    "            'final_validation_loss': history.history['val_loss'][-1],\n",
    "            'final_training_mae': history.history['mae'][-1],\n",
    "            'final_validation_mae': history.history['val_mae'][-1],\n",
    "            'best_validation_loss': min(history.history['val_loss']),\n",
    "            'best_validation_mae': min(history.history['val_mae']),\n",
    "            'epochs': len(history.history['loss']),\n",
    "        }\n",
    "\n",
    "        if folder_name is not None:\n",
    "            # Save statistics in JSON format\n",
    "            stats_filename = f'{folder_name}_training_stats.json'  # Rimossa parentesi extra\n",
    "            with open(stats_filename, 'w') as f:\n",
    "                json.dump(final_stats, f, indent=4)\n",
    "            print(f\"Final statistics saved as: {stats_filename}\")\n",
    "\n",
    "        # Print main statistics\n",
    "        print(\"\\nFinal Training Statistics:\")\n",
    "        print(f\"Final Loss (train/val): {final_stats['final_training_loss']:.4f}/{final_stats['final_validation_loss']:.4f}\")\n",
    "        print(f\"Final MAE (train/val): {final_stats['final_training_mae']:.4f}/{final_stats['final_validation_mae']:.4f}\")\n",
    "        print(f\"Best validation loss: {final_stats['best_validation_loss']:.4f}\")\n",
    "        print(f\"Best validation MAE: {final_stats['best_validation_mae']:.4f}\")\n",
    "\n",
    "        plt.show()\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"\\nError during plot creation or saving: {str(e)}\")\n",
    "\n",
    "\n",
    "def train_hybrid_model(model, X_train, y_train, X_test, y_test, epochs=100, batch_size=32, folder_name='solarradiation'):\n",
    "    \"\"\"\n",
    "    Advanced training function for the hybrid solar radiation model\n",
    "    \"\"\"\n",
    "\n",
    "    def calculate_metrics(y_true, y_pred):\n",
    "        \"\"\"Helper function to calculate metrics safely\"\"\"\n",
    "        y_true = np.array(y_true).flatten()\n",
    "        y_pred = np.array(y_pred).flatten()\n",
    "\n",
    "        # Count out of range predictions\n",
    "        out_of_range = np.sum((y_pred < 0) | (y_pred > 1500))\n",
    "\n",
    "        # Calculate MAPE with clipping to avoid extreme values\n",
    "        diff = np.abs((y_true - y_pred) / (y_true + 1e-7))\n",
    "        diff = np.clip(diff, 0, 1)  # Clip to maximum 100% error\n",
    "        mape = np.mean(diff) * 100\n",
    "\n",
    "        # Calculate accuracy within 10%\n",
    "        within_10_percent = np.mean(diff <= 0.10) * 100\n",
    "\n",
    "        # Calculate MAE and RMSE\n",
    "        mae = np.mean(np.abs(y_true - y_pred))\n",
    "        rmse = np.sqrt(np.mean(np.square(y_true - y_pred)))\n",
    "\n",
    "        return out_of_range, mape, within_10_percent, mae, rmse\n",
    "\n",
    "    callbacks = [\n",
    "        EarlyStopping(\n",
    "            monitor='val_loss',\n",
    "            patience=15,\n",
    "            restore_best_weights=True,\n",
    "            mode='min',\n",
    "            verbose=1,\n",
    "            min_delta=1e-4\n",
    "        ),\n",
    "        ReduceLROnPlateau(\n",
    "            monitor='val_loss',\n",
    "            factor=0.5,\n",
    "            patience=7,\n",
    "            verbose=1,\n",
    "            mode='min',\n",
    "            min_delta=1e-4,\n",
    "            cooldown=2,\n",
    "            min_lr=1e-7\n",
    "        ),\n",
    "        tf.keras.callbacks.ModelCheckpoint(\n",
    "            filepath=f'{folder_name}_best_model.h5',\n",
    "            monitor='val_loss',\n",
    "            save_best_only=True,\n",
    "            mode='min',\n",
    "            save_weights_only=False\n",
    "        ),\n",
    "        tf.keras.callbacks.TensorBoard(\n",
    "            log_dir=f'./{folder_name}_logs',\n",
    "            histogram_freq=1,\n",
    "            write_graph=True,\n",
    "            update_freq='epoch'\n",
    "        ),\n",
    "        tf.keras.callbacks.LambdaCallback(\n",
    "            on_epoch_end=lambda epoch, logs: (\n",
    "                    print(f\"\\nEpoch {epoch + 1} Detailed Metrics:\") and\n",
    "                    (lambda: (\n",
    "                        y_pred := model.predict(X_test, verbose=0),\n",
    "                        metrics := calculate_metrics(y_test, y_pred),\n",
    "                        print(f\"Out of range: {metrics[0]} predictions\"),\n",
    "                        print(f\"MAPE: {metrics[1]:.2f}%\"),\n",
    "                        print(f\"Within ±10%: {metrics[2]:.2f}%\"),\n",
    "                        print(f\"MAE: {metrics[3]:.2f}\"),\n",
    "                        print(f\"RMSE: {metrics[4]:.2f}\")\n",
    "                    ))()\n",
    "            ) if epoch % 5 == 0 else None\n",
    "        )\n",
    "    ]\n",
    "\n",
    "    try:\n",
    "        history = model.fit(\n",
    "            X_train, y_train,\n",
    "            validation_data=(X_test, y_test),\n",
    "            epochs=epochs,\n",
    "            batch_size=batch_size,\n",
    "            callbacks=callbacks,\n",
    "            verbose=1,\n",
    "            shuffle=False\n",
    "        )\n",
    "\n",
    "        print(\"\\nTraining completed successfully!\")\n",
    "\n",
    "        # Final evaluation\n",
    "        final_pred = model.predict(X_test, verbose=0)\n",
    "        metrics = calculate_metrics(y_test, final_pred)\n",
    "\n",
    "        print(\"\\nFinal Model Performance:\")\n",
    "        print(f\"Out of range predictions: {metrics[0]} ({metrics[0] / len(y_test) * 100:.2f}%)\")\n",
    "        print(f\"MAPE: {metrics[1]:.2f}%\")\n",
    "        print(f\"Predictions within ±10%: {metrics[2]:.2f}%\")\n",
    "        print(f\"MAE: {metrics[3]:.2f}\")\n",
    "        print(f\"RMSE: {metrics[4]:.2f}\")\n",
    "\n",
    "        plot_training_history(history, folder_name=folder_name)\n",
    "\n",
    "        return history\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"\\nError during training: {str(e)}\")\n",
    "        raise\n",
    "\n",
    "    finally:\n",
    "        tf.keras.backend.clear_session()\n",
    "\n",
    "\n",
    "def integrate_predictions(df, predictions, sequence_length=24):\n",
    "    \"\"\"\n",
    "    Integrates solar radiation predictions into the original dataset for pre-2010 data.\n",
    "\n",
    "    Parameters:\n",
    "    -----------\n",
    "    df : pandas.DataFrame\n",
    "        Original dataset\n",
    "    predictions : numpy.ndarray\n",
    "        Array of solar radiation predictions\n",
    "    sequence_length : int\n",
    "        Sequence length used for predictions\n",
    "\n",
    "    Returns:\n",
    "    --------\n",
    "    pandas.DataFrame\n",
    "        Updated dataset with solar radiation predictions\n",
    "    \"\"\"\n",
    "    # Convert datetime to datetime format if not already\n",
    "    df['datetime'] = pd.to_datetime(df['datetime'])\n",
    "\n",
    "    # Identify pre-2010 rows\n",
    "    mask_pre_2010 = df['datetime'].dt.year < 2010\n",
    "\n",
    "    # Create temporary DataFrame with predictions\n",
    "    dates_pre_2010 = df[mask_pre_2010]['datetime'].iloc[sequence_length - 1:]\n",
    "    predictions_df = pd.DataFrame({\n",
    "        'datetime': dates_pre_2010,\n",
    "        'solarradiation_predicted': predictions.flatten()})\n",
    "\n",
    "    # Merge with original dataset\n",
    "    df = df.merge(predictions_df, on='datetime', how='left')\n",
    "\n",
    "    # Update solar radiation column where missing\n",
    "    df['solarradiation'] = df['solarradiation'].fillna(df['solarradiation_predicted'])\n",
    "\n",
    "    # Remove temporary column\n",
    "    df = df.drop('solarradiation_predicted', axis=1)\n",
    "\n",
    "    print(f\"Added {len(predictions)} predictions to dataset\")\n",
    "    print(f\"Rows with solar radiation after integration: {df['solarradiation'].notna().sum()}\")\n",
    "\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1dd1bb91-cdf9-4304-be56-8d55bd5d1148",
   "metadata": {},
   "outputs": [],
   "source": [
    "def analyze_distribution(data, solar_column='solarenergy', name = 'Solar Energy'):\n",
    "    \"\"\"\n",
    "    Analizza dettagliatamente la distribuzione della variabile solarenergy.\n",
    "\n",
    "    Parameters:\n",
    "    -----------\n",
    "    data : pandas.DataFrame\n",
    "        DataFrame contenente la colonna solarenergy\n",
    "    solar_column : str, default='solarenergy'\n",
    "        Nome della colonna da analizzare\n",
    "\n",
    "    Returns:\n",
    "    --------\n",
    "    dict\n",
    "        Dizionario contenente le statistiche principali\n",
    "    \"\"\"\n",
    "\n",
    "    # Creiamo una figura con più subplot\n",
    "    fig = plt.figure(figsize=(20, 12))\n",
    "\n",
    "    # 1. Statistiche di base\n",
    "    stats_dict = {\n",
    "        'count': len(data[solar_column]),\n",
    "        'missing': data[solar_column].isnull().sum(),\n",
    "        'zeros': (data[solar_column] == 0).sum(),\n",
    "        'mean': data[solar_column].mean(),\n",
    "        'median': data[solar_column].median(),\n",
    "        'std': data[solar_column].std(),\n",
    "        'min': data[solar_column].min(),\n",
    "        'max': data[solar_column].max(),\n",
    "        'skewness': stats.skew(data[solar_column].dropna()),\n",
    "        'kurtosis': stats.kurtosis(data[solar_column].dropna())\n",
    "    }\n",
    "\n",
    "    # Calcolo dei percentili\n",
    "    percentiles = [1, 5, 10, 25, 50, 75, 90, 95, 99]\n",
    "    for p in percentiles:\n",
    "        stats_dict[f'percentile_{p}'] = np.percentile(data[solar_column].dropna(), p)\n",
    "\n",
    "    # 2. Visualizzazioni\n",
    "\n",
    "    # 2.1 Distribuzione\n",
    "    plt.subplot(2, 2, 1)\n",
    "    sns.histplot(data=data, x=solar_column, kde=True)\n",
    "    plt.title(f'Distribuzione di {name}')\n",
    "    plt.xlabel(f'{name}')\n",
    "    plt.ylabel('Frequenza')\n",
    "\n",
    "    # 2.2 Box Plot\n",
    "    plt.subplot(2, 2, 2)\n",
    "    sns.boxplot(y=data[solar_column])\n",
    "    plt.title(f'Box Plot di {name}')\n",
    "\n",
    "    # 2.3 QQ Plot\n",
    "    plt.subplot(2, 2, 3)\n",
    "    stats.probplot(data[solar_column].dropna(), dist=\"norm\", plot=plt)\n",
    "    plt.title(f'Q-Q Plot di {name}')\n",
    "\n",
    "    # 2.4 Distribuzione Log-trasformata\n",
    "    plt.subplot(2, 2, 4)\n",
    "    sns.histplot(data=np.log1p(data[solar_column]), kde=True)\n",
    "    plt.title(f'Distribuzione Log-trasformata di {name}')\n",
    "    plt.xlabel(f'Log({name} + 1)')\n",
    "    plt.ylabel('Frequenza')\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "    # 3. Analisi temporale se disponibile\n",
    "    if 'timestamp' in data.columns or 'datetime' in data.columns:\n",
    "        time_col = 'timestamp' if 'timestamp' in data.columns else 'datetime'\n",
    "        if isinstance(data[time_col].iloc[0], (int, float)):\n",
    "            data['temp_datetime'] = pd.to_datetime(data[time_col], unit='s')\n",
    "        else:\n",
    "            data['temp_datetime'] = pd.to_datetime(data[time_col])\n",
    "\n",
    "        # Plot temporale\n",
    "        plt.figure(figsize=(15, 6))\n",
    "        plt.plot(data['temp_datetime'], data[solar_column])\n",
    "        plt.title(f'Serie Temporale di {name}')\n",
    "        plt.xlabel('Data')\n",
    "        plt.ylabel(f'{name}')\n",
    "        plt.xticks(rotation=45)\n",
    "        plt.tight_layout()\n",
    "        plt.show()\n",
    "\n",
    "        # Analisi stagionale\n",
    "        data['month'] = data['temp_datetime'].dt.month\n",
    "        seasonal_stats = data.groupby('month')[solar_column].agg(['mean', 'std', 'median'])\n",
    "\n",
    "        plt.figure(figsize=(12, 6))\n",
    "        seasonal_stats['mean'].plot(kind='bar')\n",
    "        plt.title(f'Media Mensile di {name}')\n",
    "        plt.xlabel('Mese')\n",
    "        plt.ylabel(f'{name} Media')\n",
    "        plt.tight_layout()\n",
    "        plt.show()\n",
    "\n",
    "    # 4. Stampa delle statistiche principali\n",
    "    print(f\"\\nStatistiche principali di {name}:\")\n",
    "    print(\"-\" * 50)\n",
    "    for key, value in stats_dict.items():\n",
    "        print(f\"{key:15}: {value:,.4f}\")\n",
    "\n",
    "    # 5. Suggerimenti per la normalizzazione\n",
    "    print(\"\\nSuggerimenti per la normalizzazione:\")\n",
    "    print(\"-\" * 50)\n",
    "\n",
    "    skewness = abs(stats_dict['skewness'])\n",
    "    if skewness > 1:\n",
    "        print(\"- La distribuzione è fortemente asimmetrica (skewness > 1)\")\n",
    "        print(\"- Considerare una trasformazione logaritmica: np.log1p(x)\")\n",
    "\n",
    "    range_ratio = stats_dict['max'] / stats_dict['std']\n",
    "    if range_ratio > 10:\n",
    "        print(\"- La variabile ha una scala molto ampia\")\n",
    "        print(\"- Considerare RobustScaler o StandardScaler per la normalizzazione\")\n",
    "\n",
    "    zero_ratio = stats_dict['zeros'] / stats_dict['count']\n",
    "    if zero_ratio > 0.1:\n",
    "        print(f\"- Alta presenza di zeri ({zero_ratio:.2%})\")\n",
    "        print(\"- Considerare un modello in due parti: classificazione degli zeri + regressione sui valori non-zero\")\n",
    "\n",
    "    return stats_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "initial_id",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initializing solar radiation model training...\n",
      "\n",
      "1. Preparing data...\n",
      "\n",
      "Selected features:\n",
      "Number of features: 40\n",
      "Features list: ['uvindex', 'cloudcover', 'visibility', 'temp', 'pressure', 'humidity', 'solar_elevation', 'solar_angle', 'day_length', 'hour_sin', 'hour_cos', 'day_of_year_sin', 'day_of_year_cos', 'month_sin', 'month_cos', 'clear_sky_index', 'atmospheric_attenuation', 'theoretical_radiation', 'expected_radiation', 'cloud_elevation', 'visibility_elevation', 'uv_cloud_interaction', 'temp_radiation_potential', 'cloud_rolling_12h', 'temp_rolling_12h', 'uv_rolling_12h', 'cloudcover_rolling_mean_6h', 'temp_rolling_mean_6h', 'temp_1h_lag', 'cloudcover_1h_lag', 'humidity_1h_lag', 'uv_lag_1h', 'season_Spring', 'season_Summer', 'season_Autumn', 'season_Winter', 'time_period_Morning', 'time_period_Afternoon', 'time_period_Evening', 'time_period_Night']\n",
      "Training data shape: (103798, 24, 40)\n",
      "Test data shape: (25933, 24, 40)\n",
      "Saving scaler X to: 2024-11-25_13-52_scale_X.joblib\n",
      "Saving scaler X to: 2024-11-25_13-52_scale_y.joblib\n",
      "Saving features to: 2024-11-25_13-52_features.json\n"
     ]
    }
   ],
   "source": [
    "df = pd.read_parquet('../../sources/weather_data_uvindex.parquet')\n",
    "\n",
    "\n",
    "print(\"Initializing solar radiation model training...\")\n",
    "\n",
    "\n",
    "# Data preparation\n",
    "print(\"\\n1. Preparing data...\")\n",
    "X_train_seq, X_test_seq, y_train, y_test, scaler_X, scaler_y, features, X_to_predict_seq = prepare_hybrid_data(df)\n",
    "\n",
    "print(f\"Training data shape: {X_train_seq.shape}\")\n",
    "print(f\"Test data shape: {X_test_seq.shape}\")\n",
    "\n",
    "# Save or load scaler and features\n",
    "scaler_X_path = f'{folder_name}_scale_X.joblib'\n",
    "scaler_y_path = f'{folder_name}_scale_y.joblib'\n",
    "features_path = f'{folder_name}_features.json'\n",
    "model_path = f'{folder_name}_best_model.h5'\n",
    "history_path = f'{folder_name}_training_history.json'\n",
    "\n",
    "if os.path.exists(scaler_X_path):\n",
    "    print(f\"Loading existing scaler X from: {scaler_X_path}\")\n",
    "    scaler = joblib.load(scaler_X_path)\n",
    "else:\n",
    "    print(f\"Saving scaler X to: {scaler_X_path}\")\n",
    "    joblib.dump(scaler_X, scaler_X_path)\n",
    "\n",
    "if os.path.exists(scaler_y_path):\n",
    "    print(f\"Loading existing scaler X from: {scaler_y_path}\")\n",
    "    scaler = joblib.load(scaler_y_path)\n",
    "else:\n",
    "    print(f\"Saving scaler X to: {scaler_y_path}\")\n",
    "    joblib.dump(scaler_y, scaler_y_path)\n",
    "\n",
    "if os.path.exists(features_path):\n",
    "    print(f\"Loading existing features from: {features_path}\")\n",
    "    with open(features_path, 'r') as f:\n",
    "        features = json.load(f)\n",
    "else:\n",
    "    print(f\"Saving features to: {features_path}\")\n",
    "    with open(features_path, 'w') as f:\n",
    "        json.dump(features, f)\n",
    "\n",
    "# Data quality verification\n",
    "if np.isnan(X_train_seq).any() or np.isnan(y_train).any():\n",
    "    raise ValueError(\"Found NaN values in training data\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "44749f6a-8941-41e8-8105-c36417245ed5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "2. Creating model...\n",
      "\n",
      "Max dataset solar radiation : 1113.0 - Scaled Version : 3.2535460992907805\n",
      "Max dataset solar radiation increased by 15% : 1279.9499999999998 - Scaled Version : 3.7415780141843973\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-25 13:52:27.432588: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1886] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 43404 MB memory:  -> device: 0, name: NVIDIA L40, pci bus id: 0000:01:00.0, compute capability: 8.9\n",
      "2024-11-25 13:52:28.267692: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"SolarRadiationModel\"\n",
      "__________________________________________________________________________________________________\n",
      " Layer (type)                Output Shape                 Param #   Connected to                  \n",
      "==================================================================================================\n",
      " input_1 (InputLayer)        [(None, 24, 40)]             0         []                            \n",
      "                                                                                                  \n",
      " bidirectional (Bidirection  (None, 24, 512)              608256    ['input_1[0][0]']             \n",
      " al)                                                                                              \n",
      "                                                                                                  \n",
      " layer_normalization (Layer  (None, 24, 512)              1024      ['bidirectional[0][0]']       \n",
      " Normalization)                                                                                   \n",
      "                                                                                                  \n",
      " dropout (Dropout)           (None, 24, 512)              0         ['layer_normalization[0][0]'] \n",
      "                                                                                                  \n",
      " dense (Dense)               (None, 24, 512)              20992     ['input_1[0][0]']             \n",
      "                                                                                                  \n",
      " stochastic_depth (Stochast  (None, 24, 512)              0         ['dropout[0][0]',             \n",
      " icDepth)                                                            'dense[0][0]']               \n",
      "                                                                                                  \n",
      " multi_head_attention (Mult  (None, 24, 512)              1680230   ['stochastic_depth[0][0]',    \n",
      " iHeadAttention)                                          4          'stochastic_depth[0][0]']    \n",
      "                                                                                                  \n",
      " stochastic_depth_1 (Stocha  (None, 24, 512)              0         ['stochastic_depth[0][0]',    \n",
      " sticDepth)                                                          'multi_head_attention[0][0]']\n",
      "                                                                                                  \n",
      " layer_normalization_1 (Lay  (None, 24, 512)              1024      ['stochastic_depth_1[0][0]']  \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " max_pooling1d (MaxPooling1  (None, 12, 512)              0         ['layer_normalization_1[0][0]'\n",
      " D)                                                                 ]                             \n",
      "                                                                                                  \n",
      " bidirectional_1 (Bidirecti  (None, 12, 256)              656384    ['max_pooling1d[0][0]']       \n",
      " onal)                                                                                            \n",
      "                                                                                                  \n",
      " layer_normalization_2 (Lay  (None, 12, 256)              512       ['bidirectional_1[0][0]']     \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " dropout_1 (Dropout)         (None, 12, 256)              0         ['layer_normalization_2[0][0]'\n",
      "                                                                    ]                             \n",
      "                                                                                                  \n",
      " dense_1 (Dense)             (None, 12, 256)              131328    ['max_pooling1d[0][0]']       \n",
      "                                                                                                  \n",
      " stochastic_depth_2 (Stocha  (None, 12, 256)              0         ['dropout_1[0][0]',           \n",
      " sticDepth)                                                          'dense_1[0][0]']             \n",
      "                                                                                                  \n",
      " multi_head_attention_1 (Mu  (None, 12, 256)              3155200   ['stochastic_depth_2[0][0]',  \n",
      " ltiHeadAttention)                                                   'stochastic_depth_2[0][0]']  \n",
      "                                                                                                  \n",
      " stochastic_depth_3 (Stocha  (None, 12, 256)              0         ['stochastic_depth_2[0][0]',  \n",
      " sticDepth)                                                          'multi_head_attention_1[0][0]\n",
      "                                                                    ']                            \n",
      "                                                                                                  \n",
      " layer_normalization_3 (Lay  (None, 12, 256)              512       ['stochastic_depth_3[0][0]']  \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " max_pooling1d_1 (MaxPoolin  (None, 6, 256)               0         ['layer_normalization_3[0][0]'\n",
      " g1D)                                                               ]                             \n",
      "                                                                                                  \n",
      " bidirectional_2 (Bidirecti  (None, 6, 128)               164352    ['max_pooling1d_1[0][0]']     \n",
      " onal)                                                                                            \n",
      "                                                                                                  \n",
      " layer_normalization_4 (Lay  (None, 6, 128)               256       ['bidirectional_2[0][0]']     \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " dropout_2 (Dropout)         (None, 6, 128)               0         ['layer_normalization_4[0][0]'\n",
      "                                                                    ]                             \n",
      "                                                                                                  \n",
      " dense_2 (Dense)             (None, 6, 128)               32896     ['max_pooling1d_1[0][0]']     \n",
      "                                                                                                  \n",
      " stochastic_depth_4 (Stocha  (None, 6, 128)               0         ['dropout_2[0][0]',           \n",
      " sticDepth)                                                          'dense_2[0][0]']             \n",
      "                                                                                                  \n",
      " multi_head_attention_2 (Mu  (None, 6, 128)               527488    ['stochastic_depth_4[0][0]',  \n",
      " ltiHeadAttention)                                                   'stochastic_depth_4[0][0]']  \n",
      "                                                                                                  \n",
      " stochastic_depth_5 (Stocha  (None, 6, 128)               0         ['stochastic_depth_4[0][0]',  \n",
      " sticDepth)                                                          'multi_head_attention_2[0][0]\n",
      "                                                                    ']                            \n",
      "                                                                                                  \n",
      " layer_normalization_5 (Lay  (None, 6, 128)               256       ['stochastic_depth_5[0][0]']  \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " max_pooling1d_2 (MaxPoolin  (None, 3, 128)               0         ['layer_normalization_5[0][0]'\n",
      " g1D)                                                               ]                             \n",
      "                                                                                                  \n",
      " bidirectional_3 (Bidirecti  (None, 3, 64)                41216     ['max_pooling1d_2[0][0]']     \n",
      " onal)                                                                                            \n",
      "                                                                                                  \n",
      " layer_normalization_6 (Lay  (None, 3, 64)                128       ['bidirectional_3[0][0]']     \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " dropout_3 (Dropout)         (None, 3, 64)                0         ['layer_normalization_6[0][0]'\n",
      "                                                                    ]                             \n",
      "                                                                                                  \n",
      " dense_3 (Dense)             (None, 3, 64)                8256      ['max_pooling1d_2[0][0]']     \n",
      "                                                                                                  \n",
      " stochastic_depth_6 (Stocha  (None, 3, 64)                0         ['dropout_3[0][0]',           \n",
      " sticDepth)                                                          'dense_3[0][0]']             \n",
      "                                                                                                  \n",
      " multi_head_attention_3 (Mu  (None, 3, 64)                66368     ['stochastic_depth_6[0][0]',  \n",
      " ltiHeadAttention)                                                   'stochastic_depth_6[0][0]']  \n",
      "                                                                                                  \n",
      " stochastic_depth_7 (Stocha  (None, 3, 64)                0         ['stochastic_depth_6[0][0]',  \n",
      " sticDepth)                                                          'multi_head_attention_3[0][0]\n",
      "                                                                    ']                            \n",
      "                                                                                                  \n",
      " layer_normalization_7 (Lay  (None, 3, 64)                128       ['stochastic_depth_7[0][0]']  \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " bidirectional_4 (Bidirecti  (None, 64)                   24832     ['layer_normalization_7[0][0]'\n",
      " onal)                                                              ]                             \n",
      "                                                                                                  \n",
      " layer_normalization_8 (Lay  (None, 64)                   128       ['bidirectional_4[0][0]']     \n",
      " erNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " dropout_4 (Dropout)         (None, 64)                   0         ['layer_normalization_8[0][0]'\n",
      "                                                                    ]                             \n",
      "                                                                                                  \n",
      " dense_4 (Dense)             (None, 128)                  8320      ['dropout_4[0][0]']           \n",
      "                                                                                                  \n",
      " batch_normalization (Batch  (None, 128)                  512       ['dense_4[0][0]']             \n",
      " Normalization)                                                                                   \n",
      "                                                                                                  \n",
      " activation (Activation)     (None, 128)                  0         ['batch_normalization[0][0]'] \n",
      "                                                                                                  \n",
      " dropout_5 (Dropout)         (None, 128)                  0         ['activation[0][0]']          \n",
      "                                                                                                  \n",
      " dense_5 (Dense)             (None, 64)                   8256      ['dropout_5[0][0]']           \n",
      "                                                                                                  \n",
      " batch_normalization_1 (Bat  (None, 64)                   256       ['dense_5[0][0]']             \n",
      " chNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " activation_1 (Activation)   (None, 64)                   0         ['batch_normalization_1[0][0]'\n",
      "                                                                    ]                             \n",
      "                                                                                                  \n",
      " dropout_6 (Dropout)         (None, 64)                   0         ['activation_1[0][0]']        \n",
      "                                                                                                  \n",
      " dense_6 (Dense)             (None, 32)                   2080      ['dropout_6[0][0]']           \n",
      "                                                                                                  \n",
      " batch_normalization_2 (Bat  (None, 32)                   128       ['dense_6[0][0]']             \n",
      " chNormalization)                                                                                 \n",
      "                                                                                                  \n",
      " activation_2 (Activation)   (None, 32)                   0         ['batch_normalization_2[0][0]'\n",
      "                                                                    ]                             \n",
      "                                                                                                  \n",
      " dropout_7 (Dropout)         (None, 32)                   0         ['activation_2[0][0]']        \n",
      "                                                                                                  \n",
      " dense_7 (Dense)             (None, 1)                    33        ['dropout_7[0][0]']           \n",
      "                                                                                                  \n",
      " lambda (Lambda)             (None, 1)                    0         ['dense_7[0][0]']             \n",
      "                                                                                                  \n",
      "==================================================================================================\n",
      "Total params: 22263425 (84.93 MB)\n",
      "Trainable params: 22262977 (84.93 MB)\n",
      "Non-trainable params: 448 (1.75 KB)\n",
      "__________________________________________________________________________________________________\n",
      "\n",
      "4. Starting training...\n",
      "Epoch 1/100\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-11-25 13:52:50.667967: I tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:442] Loaded cuDNN version 8905\n",
      "2024-11-25 13:52:52.254189: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x759e08d2de90 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:\n",
      "2024-11-25 13:52:52.254217: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): NVIDIA L40, Compute Capability 8.9\n",
      "2024-11-25 13:52:52.258602: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:269] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable.\n",
      "2024-11-25 13:52:52.401237: I ./tensorflow/compiler/jit/device_compiler.h:186] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "540/541 [============================>.] - ETA: 0s - loss: 8.3573 - mse: 0.6705 - mae: 0.5175 - rmse: 0.7610 - custom_mape: 62.5211"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.11/dist-packages/keras/src/engine/training.py:3079: UserWarning: You are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')`.\n",
      "  saving_api.save_model(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Epoch 1 Detailed Metrics:\n",
      "541/541 [==============================] - 70s 79ms/step - loss: 8.3541 - mse: 0.6698 - mae: 0.5171 - rmse: 0.7602 - custom_mape: 62.5082 - val_loss: 5.5029 - val_mse: 0.1555 - val_mae: 0.2236 - val_rmse: 0.3853 - val_custom_mape: 33.0501 - lr: 1.3120e-04\n",
      "Epoch 2/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 4.8835 - mse: 0.1649 - mae: 0.2351 - rmse: 0.3909 - custom_mape: 34.9535 - val_loss: 4.0981 - val_mse: 0.1782 - val_mae: 0.2380 - val_rmse: 0.3937 - val_custom_mape: 32.7671 - lr: 2.6891e-04\n",
      "Epoch 3/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 2.8253 - mse: 0.1180 - mae: 0.1955 - rmse: 0.3321 - custom_mape: 30.7958 - val_loss: 2.0010 - val_mse: 0.0838 - val_mae: 0.1619 - val_rmse: 0.2713 - val_custom_mape: 28.0167 - lr: 2.1053e-04\n",
      "Epoch 4/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 1.6423 - mse: 0.0603 - mae: 0.1361 - rmse: 0.2385 - custom_mape: 24.5993 - val_loss: 1.4116 - val_mse: 0.0688 - val_mae: 0.1494 - val_rmse: 0.2560 - val_custom_mape: 26.3951 - lr: 1.0081e-04\n",
      "Epoch 5/100\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 1.3057 - mse: 0.0424 - mae: 0.1127 - rmse: 0.2007 - custom_mape: 21.8917 - val_loss: 1.2564 - val_mse: 0.0442 - val_mae: 0.1149 - val_rmse: 0.2065 - val_custom_mape: 22.3474 - lr: 1.4334e-05\n",
      "Epoch 6/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 1.1928 - mse: 0.0425 - mae: 0.1130 - rmse: 0.2005 - custom_mape: 21.7451\n",
      "Epoch 6 Detailed Metrics:\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 1.1925 - mse: 0.0425 - mae: 0.1129 - rmse: 0.2003 - custom_mape: 21.7690 - val_loss: 1.0131 - val_mse: 0.0528 - val_mae: 0.1265 - val_rmse: 0.2226 - val_custom_mape: 22.8960 - lr: 2.4076e-04\n",
      "Epoch 7/100\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.8364 - mse: 0.0590 - mae: 0.1341 - rmse: 0.2334 - custom_mape: 24.2004 - val_loss: 0.6962 - val_mse: 0.0741 - val_mae: 0.1525 - val_rmse: 0.2596 - val_custom_mape: 25.3537 - lr: 2.2058e-04\n",
      "Epoch 8/100\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.5898 - mse: 0.0509 - mae: 0.1241 - rmse: 0.2155 - custom_mape: 23.1834 - val_loss: 0.5431 - val_mse: 0.0950 - val_mae: 0.2095 - val_rmse: 0.3062 - val_custom_mape: 37.3372 - lr: 1.8277e-04\n",
      "Epoch 9/100\n",
      "541/541 [==============================] - 40s 74ms/step - loss: 0.4529 - mse: 0.0402 - mae: 0.1098 - rmse: 0.1931 - custom_mape: 21.1223 - val_loss: 0.4038 - val_mse: 0.0302 - val_mae: 0.0935 - val_rmse: 0.1677 - val_custom_mape: 20.0386 - lr: 1.3408e-04\n",
      "Epoch 10/100\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.3761 - mse: 0.0310 - mae: 0.0958 - rmse: 0.1704 - custom_mape: 19.7314 - val_loss: 0.3586 - val_mse: 0.0451 - val_mae: 0.1141 - val_rmse: 0.1979 - val_custom_mape: 20.7993 - lr: 8.3141e-05\n",
      "Epoch 11/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.3347 - mse: 0.0242 - mae: 0.0840 - rmse: 0.1510 - custom_mape: 18.0393\n",
      "Epoch 11 Detailed Metrics:\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.3347 - mse: 0.0242 - mae: 0.0840 - rmse: 0.1509 - custom_mape: 18.0607 - val_loss: 0.3301 - val_mse: 0.0397 - val_mae: 0.1035 - val_rmse: 0.1812 - val_custom_mape: 18.6451 - lr: 3.9028e-05\n",
      "Epoch 12/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.3175 - mse: 0.0224 - mae: 0.0806 - rmse: 0.1453 - custom_mape: 17.6096 - val_loss: 0.3190 - val_mse: 0.0345 - val_mae: 0.0967 - val_rmse: 0.1716 - val_custom_mape: 18.2344 - lr: 9.5830e-06\n",
      "Epoch 13/100\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.3131 - mse: 0.0225 - mae: 0.0811 - rmse: 0.1450 - custom_mape: 17.6923 - val_loss: 0.3130 - val_mse: 0.0311 - val_mae: 0.0966 - val_rmse: 0.1710 - val_custom_mape: 20.7828 - lr: 2.1869e-04\n",
      "Epoch 14/100\n",
      "541/541 [==============================] - 38s 71ms/step - loss: 0.2933 - mse: 0.0562 - mae: 0.1310 - rmse: 0.2245 - custom_mape: 24.0791 - val_loss: 0.2675 - val_mse: 0.0672 - val_mae: 0.1489 - val_rmse: 0.2424 - val_custom_mape: 29.0105 - lr: 2.1594e-04\n",
      "Epoch 15/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.2300 - mse: 0.0400 - mae: 0.1099 - rmse: 0.1920 - custom_mape: 21.2963 - val_loss: 0.2111 - val_mse: 0.0450 - val_mae: 0.1232 - val_rmse: 0.2018 - val_custom_mape: 25.0584 - lr: 2.0840e-04\n",
      "Epoch 16/100\n",
      "541/541 [==============================] - ETA: 0s - loss: 0.1924 - mse: 0.0436 - mae: 0.1148 - rmse: 0.1990 - custom_mape: 21.9478\n",
      "Epoch 16 Detailed Metrics:\n",
      "541/541 [==============================] - 40s 73ms/step - loss: 0.1924 - mse: 0.0436 - mae: 0.1148 - rmse: 0.1990 - custom_mape: 21.9478 - val_loss: 0.1791 - val_mse: 0.0464 - val_mae: 0.1232 - val_rmse: 0.2052 - val_custom_mape: 24.7895 - lr: 1.9641e-04\n",
      "Epoch 17/100\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.1588 - mse: 0.0344 - mae: 0.1019 - rmse: 0.1778 - custom_mape: 20.1684 - val_loss: 0.1435 - val_mse: 0.0285 - val_mae: 0.0913 - val_rmse: 0.1615 - val_custom_mape: 19.9306 - lr: 1.8050e-04\n",
      "Epoch 18/100\n",
      "541/541 [==============================] - 38s 69ms/step - loss: 0.1359 - mse: 0.0305 - mae: 0.0962 - rmse: 0.1677 - custom_mape: 19.8060 - val_loss: 0.1478 - val_mse: 0.0771 - val_mae: 0.1585 - val_rmse: 0.2474 - val_custom_mape: 27.4152 - lr: 1.6139e-04\n",
      "Epoch 19/100\n",
      "541/541 [==============================] - 39s 71ms/step - loss: 0.1209 - mse: 0.0312 - mae: 0.0959 - rmse: 0.1679 - custom_mape: 19.2837 - val_loss: 0.1135 - val_mse: 0.0329 - val_mae: 0.0929 - val_rmse: 0.1644 - val_custom_mape: 19.0066 - lr: 1.3994e-04\n",
      "Epoch 20/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.1055 - mse: 0.0236 - mae: 0.0839 - rmse: 0.1472 - custom_mape: 18.0202 - val_loss: 0.1032 - val_mse: 0.0308 - val_mae: 0.0911 - val_rmse: 0.1598 - val_custom_mape: 19.2490 - lr: 1.1712e-04\n",
      "Epoch 21/100\n",
      "541/541 [==============================] - ETA: 0s - loss: 0.0994 - mse: 0.0271 - mae: 0.0897 - rmse: 0.1563 - custom_mape: 18.7032\n",
      "Epoch 21 Detailed Metrics:\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0994 - mse: 0.0271 - mae: 0.0897 - rmse: 0.1563 - custom_mape: 18.7032 - val_loss: 0.1014 - val_mse: 0.0343 - val_mae: 0.1057 - val_rmse: 0.1742 - val_custom_mape: 24.6971 - lr: 9.3944e-05\n",
      "Epoch 22/100\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0895 - mse: 0.0197 - mae: 0.0768 - rmse: 0.1354 - custom_mape: 17.1486 - val_loss: 0.0911 - val_mse: 0.0286 - val_mae: 0.0896 - val_rmse: 0.1566 - val_custom_mape: 19.0230 - lr: 7.1464e-05\n",
      "Epoch 23/100\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.0833 - mse: 0.0167 - mae: 0.0708 - rmse: 0.1252 - custom_mape: 16.4218 - val_loss: 0.0898 - val_mse: 0.0347 - val_mae: 0.0968 - val_rmse: 0.1657 - val_custom_mape: 17.8852 - lr: 5.0687e-05\n",
      "Epoch 24/100\n",
      "541/541 [==============================] - 38s 69ms/step - loss: 0.0798 - mse: 0.0159 - mae: 0.0689 - rmse: 0.1217 - custom_mape: 16.0625 - val_loss: 0.0820 - val_mse: 0.0250 - val_mae: 0.0791 - val_rmse: 0.1418 - val_custom_mape: 16.7331 - lr: 3.2548e-05\n",
      "Epoch 25/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.0767 - mse: 0.0140 - mae: 0.0647 - rmse: 0.1146 - custom_mape: 15.6304 - val_loss: 0.0798 - val_mse: 0.0229 - val_mae: 0.0763 - val_rmse: 0.1377 - val_custom_mape: 16.6235 - lr: 1.7863e-05\n",
      "Epoch 26/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0757 - mse: 0.0140 - mae: 0.0646 - rmse: 0.1144 - custom_mape: 15.5670\n",
      "Epoch 26 Detailed Metrics:\n",
      "541/541 [==============================] - 39s 71ms/step - loss: 0.0757 - mse: 0.0140 - mae: 0.0646 - rmse: 0.1143 - custom_mape: 15.5871 - val_loss: 0.0793 - val_mse: 0.0233 - val_mae: 0.0766 - val_rmse: 0.1381 - val_custom_mape: 16.4359 - lr: 7.2916e-06\n",
      "Epoch 27/100\n",
      "541/541 [==============================] - 35s 64ms/step - loss: 0.0754 - mse: 0.0142 - mae: 0.0650 - rmse: 0.1150 - custom_mape: 15.6099 - val_loss: 0.0796 - val_mse: 0.0245 - val_mae: 0.0785 - val_rmse: 0.1406 - val_custom_mape: 16.5037 - lr: 1.3093e-06\n",
      "Epoch 28/100\n",
      "541/541 [==============================] - 35s 65ms/step - loss: 0.0753 - mse: 0.0146 - mae: 0.0660 - rmse: 0.1168 - custom_mape: 15.6841 - val_loss: 0.0847 - val_mse: 0.0333 - val_mae: 0.1012 - val_rmse: 0.1737 - val_custom_mape: 20.9143 - lr: 1.9679e-04\n",
      "Epoch 29/100\n",
      "541/541 [==============================] - 35s 66ms/step - loss: 0.0901 - mse: 0.0467 - mae: 0.1176 - rmse: 0.2031 - custom_mape: 22.1549 - val_loss: 0.1183 - val_mse: 0.1009 - val_mae: 0.1867 - val_rmse: 0.2930 - val_custom_mape: 30.4890 - lr: 1.9593e-04\n",
      "Epoch 30/100\n",
      "541/541 [==============================] - 36s 66ms/step - loss: 0.0798 - mse: 0.0364 - mae: 0.1057 - rmse: 0.1827 - custom_mape: 21.1398 - val_loss: 0.0919 - val_mse: 0.0843 - val_mae: 0.1507 - val_rmse: 0.2669 - val_custom_mape: 23.3218 - lr: 1.9398e-04\n",
      "Epoch 31/100\n",
      "541/541 [==============================] - ETA: 0s - loss: 0.0720 - mse: 0.0336 - mae: 0.1008 - rmse: 0.1748 - custom_mape: 19.9648\n",
      "Epoch 31 Detailed Metrics:\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0720 - mse: 0.0336 - mae: 0.1008 - rmse: 0.1748 - custom_mape: 19.9648 - val_loss: 0.0618 - val_mse: 0.0238 - val_mae: 0.0780 - val_rmse: 0.1408 - val_custom_mape: 16.9390 - lr: 1.9095e-04\n",
      "Epoch 32/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0655 - mse: 0.0299 - mae: 0.0960 - rmse: 0.1657 - custom_mape: 19.8846 - val_loss: 0.0781 - val_mse: 0.0562 - val_mae: 0.1387 - val_rmse: 0.2230 - val_custom_mape: 25.8359 - lr: 1.8687e-04\n",
      "Epoch 33/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0630 - mse: 0.0322 - mae: 0.0984 - rmse: 0.1708 - custom_mape: 19.9807 - val_loss: 0.0745 - val_mse: 0.0661 - val_mae: 0.1394 - val_rmse: 0.2340 - val_custom_mape: 22.5655 - lr: 1.8180e-04\n",
      "Epoch 34/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0694 - mse: 0.0437 - mae: 0.1127 - rmse: 0.1919 - custom_mape: 21.6774 - val_loss: 0.0740 - val_mse: 0.0535 - val_mae: 0.1283 - val_rmse: 0.2119 - val_custom_mape: 21.3689 - lr: 1.7579e-04\n",
      "Epoch 35/100\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.0605 - mse: 0.0311 - mae: 0.0963 - rmse: 0.1663 - custom_mape: 19.5287 - val_loss: 0.0686 - val_mse: 0.0554 - val_mae: 0.1297 - val_rmse: 0.2094 - val_custom_mape: 21.9974 - lr: 1.6890e-04\n",
      "Epoch 36/100\n",
      "541/541 [==============================] - ETA: 0s - loss: 0.0568 - mse: 0.0311 - mae: 0.0973 - rmse: 0.1681 - custom_mape: 19.8627\n",
      "Epoch 36 Detailed Metrics:\n",
      "541/541 [==============================] - 39s 71ms/step - loss: 0.0568 - mse: 0.0311 - mae: 0.0973 - rmse: 0.1681 - custom_mape: 19.8627 - val_loss: 0.0517 - val_mse: 0.0246 - val_mae: 0.0877 - val_rmse: 0.1521 - val_custom_mape: 19.8935 - lr: 1.6122e-04\n",
      "Epoch 37/100\n",
      "541/541 [==============================] - 40s 73ms/step - loss: 0.0503 - mse: 0.0251 - mae: 0.0868 - rmse: 0.1509 - custom_mape: 18.7631 - val_loss: 0.0632 - val_mse: 0.0557 - val_mae: 0.1318 - val_rmse: 0.2154 - val_custom_mape: 22.4402 - lr: 1.5284e-04\n",
      "Epoch 38/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0522 - mse: 0.0322 - mae: 0.0988 - rmse: 0.1711 - custom_mape: 19.8555 - val_loss: 0.0561 - val_mse: 0.0366 - val_mae: 0.1139 - val_rmse: 0.1888 - val_custom_mape: 23.3929 - lr: 1.4383e-04\n",
      "Epoch 39/100\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0458 - mse: 0.0236 - mae: 0.0847 - rmse: 0.1476 - custom_mape: 18.3107 - val_loss: 0.0417 - val_mse: 0.0218 - val_mae: 0.0746 - val_rmse: 0.1359 - val_custom_mape: 17.6771 - lr: 1.3432e-04\n",
      "Epoch 40/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0430 - mse: 0.0217 - mae: 0.0815 - rmse: 0.1418 - custom_mape: 18.0985 - val_loss: 0.0502 - val_mse: 0.0404 - val_mae: 0.1058 - val_rmse: 0.1835 - val_custom_mape: 20.7356 - lr: 1.2440e-04\n",
      "Epoch 41/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0426 - mse: 0.0228 - mae: 0.0833 - rmse: 0.1452 - custom_mape: 18.0141\n",
      "Epoch 41 Detailed Metrics:\n",
      "541/541 [==============================] - 36s 66ms/step - loss: 0.0426 - mse: 0.0228 - mae: 0.0832 - rmse: 0.1451 - custom_mape: 18.0266 - val_loss: 0.0439 - val_mse: 0.0246 - val_mae: 0.0896 - val_rmse: 0.1506 - val_custom_mape: 20.5262 - lr: 1.1419e-04\n",
      "Epoch 42/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0398 - mse: 0.0200 - mae: 0.0783 - rmse: 0.1361 - custom_mape: 17.6098 - val_loss: 0.0454 - val_mse: 0.0335 - val_mae: 0.0979 - val_rmse: 0.1629 - val_custom_mape: 18.9381 - lr: 1.0381e-04\n",
      "Epoch 43/100\n",
      "541/541 [==============================] - 39s 71ms/step - loss: 0.0390 - mse: 0.0205 - mae: 0.0789 - rmse: 0.1381 - custom_mape: 17.4761 - val_loss: 0.0389 - val_mse: 0.0225 - val_mae: 0.0795 - val_rmse: 0.1419 - val_custom_mape: 18.9360 - lr: 9.3356e-05\n",
      "Epoch 44/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.0357 - mse: 0.0165 - mae: 0.0713 - rmse: 0.1243 - custom_mape: 16.7496 - val_loss: 0.0473 - val_mse: 0.0405 - val_mae: 0.1093 - val_rmse: 0.1787 - val_custom_mape: 19.7927 - lr: 8.2964e-05\n",
      "Epoch 45/100\n",
      "541/541 [==============================] - 39s 71ms/step - loss: 0.0371 - mse: 0.0196 - mae: 0.0776 - rmse: 0.1349 - custom_mape: 17.3625 - val_loss: 0.0400 - val_mse: 0.0258 - val_mae: 0.0872 - val_rmse: 0.1522 - val_custom_mape: 19.9462 - lr: 7.2747e-05\n",
      "Epoch 46/100\n",
      "541/541 [==============================] - ETA: 0s - loss: 0.0330 - mse: 0.0143 - mae: 0.0665 - rmse: 0.1162 - custom_mape: 16.2204\n",
      "Epoch 46 Detailed Metrics:\n",
      "541/541 [==============================] - 41s 77ms/step - loss: 0.0330 - mse: 0.0143 - mae: 0.0665 - rmse: 0.1162 - custom_mape: 16.2204 - val_loss: 0.0364 - val_mse: 0.0220 - val_mae: 0.0783 - val_rmse: 0.1340 - val_custom_mape: 17.0947 - lr: 6.2818e-05\n",
      "Epoch 47/100\n",
      "541/541 [==============================] - 41s 76ms/step - loss: 0.0333 - mse: 0.0154 - mae: 0.0690 - rmse: 0.1205 - custom_mape: 16.3305 - val_loss: 0.0363 - val_mse: 0.0243 - val_mae: 0.0790 - val_rmse: 0.1431 - val_custom_mape: 17.9395 - lr: 5.3291e-05\n",
      "Epoch 48/100\n",
      "541/541 [==============================] - 41s 77ms/step - loss: 0.0307 - mse: 0.0126 - mae: 0.0622 - rmse: 0.1091 - custom_mape: 15.5196 - val_loss: 0.0337 - val_mse: 0.0201 - val_mae: 0.0724 - val_rmse: 0.1290 - val_custom_mape: 16.5807 - lr: 4.4272e-05\n",
      "Epoch 49/100\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.0302 - mse: 0.0125 - mae: 0.0617 - rmse: 0.1083 - custom_mape: 15.3759 - val_loss: 0.0353 - val_mse: 0.0231 - val_mae: 0.0786 - val_rmse: 0.1369 - val_custom_mape: 17.0512 - lr: 3.5864e-05\n",
      "Epoch 50/100\n",
      "541/541 [==============================] - 41s 75ms/step - loss: 0.0289 - mse: 0.0113 - mae: 0.0588 - rmse: 0.1033 - custom_mape: 15.0117 - val_loss: 0.0328 - val_mse: 0.0194 - val_mae: 0.0715 - val_rmse: 0.1260 - val_custom_mape: 16.4202 - lr: 2.8161e-05\n",
      "Epoch 51/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0283 - mse: 0.0110 - mae: 0.0576 - rmse: 0.1014 - custom_mape: 14.7889\n",
      "Epoch 51 Detailed Metrics:\n",
      "541/541 [==============================] - 43s 80ms/step - loss: 0.0283 - mse: 0.0110 - mae: 0.0576 - rmse: 0.1014 - custom_mape: 14.8090 - val_loss: 0.0329 - val_mse: 0.0200 - val_mae: 0.0725 - val_rmse: 0.1267 - val_custom_mape: 16.1412 - lr: 2.1251e-05\n",
      "Epoch 52/100\n",
      "541/541 [==============================] - 41s 76ms/step - loss: 0.0279 - mse: 0.0106 - mae: 0.0570 - rmse: 0.1001 - custom_mape: 14.7309 - val_loss: 0.0326 - val_mse: 0.0199 - val_mae: 0.0721 - val_rmse: 0.1267 - val_custom_mape: 16.1540 - lr: 1.5210e-05\n",
      "Epoch 53/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0277 - mse: 0.0105 - mae: 0.0567 - rmse: 0.0993 - custom_mape: 14.6780 - val_loss: 0.0329 - val_mse: 0.0206 - val_mae: 0.0734 - val_rmse: 0.1285 - val_custom_mape: 16.2771 - lr: 1.0107e-05\n",
      "Epoch 54/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0275 - mse: 0.0103 - mae: 0.0562 - rmse: 0.0986 - custom_mape: 14.6906 - val_loss: 0.0322 - val_mse: 0.0195 - val_mae: 0.0713 - val_rmse: 0.1258 - val_custom_mape: 16.1401 - lr: 5.9992e-06\n",
      "Epoch 55/100\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0275 - mse: 0.0105 - mae: 0.0565 - rmse: 0.0993 - custom_mape: 14.7210 - val_loss: 0.0325 - val_mse: 0.0202 - val_mae: 0.0724 - val_rmse: 0.1279 - val_custom_mape: 16.1922 - lr: 2.9336e-06\n",
      "Epoch 56/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0276 - mse: 0.0105 - mae: 0.0568 - rmse: 0.0996 - custom_mape: 14.7010\n",
      "Epoch 56 Detailed Metrics:\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.0276 - mse: 0.0105 - mae: 0.0568 - rmse: 0.0996 - custom_mape: 14.7231 - val_loss: 0.0320 - val_mse: 0.0194 - val_mae: 0.0710 - val_rmse: 0.1254 - val_custom_mape: 16.0903 - lr: 9.4439e-07\n",
      "Epoch 57/100\n",
      "541/541 [==============================] - 36s 66ms/step - loss: 0.0274 - mse: 0.0103 - mae: 0.0562 - rmse: 0.0985 - custom_mape: 14.6804 - val_loss: 0.0318 - val_mse: 0.0191 - val_mae: 0.0703 - val_rmse: 0.1246 - val_custom_mape: 16.0085 - lr: 5.4016e-08\n",
      "Epoch 58/100\n",
      "541/541 [==============================] - 34s 63ms/step - loss: 0.0322 - mse: 0.0176 - mae: 0.0715 - rmse: 0.1250 - custom_mape: 16.7714 - val_loss: 0.0412 - val_mse: 0.0307 - val_mae: 0.0991 - val_rmse: 0.1727 - val_custom_mape: 21.0792 - lr: 1.7709e-04\n",
      "Epoch 59/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.0563 - mse: 0.0543 - mae: 0.1225 - rmse: 0.2110 - custom_mape: 22.3851 - val_loss: 0.0627 - val_mse: 0.0621 - val_mae: 0.1421 - val_rmse: 0.2244 - val_custom_mape: 26.3625 - lr: 1.7679e-04\n",
      "Epoch 60/100\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.0465 - mse: 0.0347 - mae: 0.1009 - rmse: 0.1759 - custom_mape: 19.8500 - val_loss: 0.0514 - val_mse: 0.0437 - val_mae: 0.1161 - val_rmse: 0.1923 - val_custom_mape: 23.5605 - lr: 1.7624e-04\n",
      "Epoch 61/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0416 - mse: 0.0273 - mae: 0.0918 - rmse: 0.1597 - custom_mape: 19.2484\n",
      "Epoch 61 Detailed Metrics:\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0415 - mse: 0.0273 - mae: 0.0917 - rmse: 0.1597 - custom_mape: 19.2691 - val_loss: 0.0561 - val_mse: 0.0538 - val_mae: 0.1366 - val_rmse: 0.2197 - val_custom_mape: 25.7023 - lr: 1.7545e-04\n",
      "Epoch 62/100\n",
      "541/541 [==============================] - ETA: 0s - loss: 0.0425 - mse: 0.0304 - mae: 0.0970 - rmse: 0.1667 - custom_mape: 20.2351\n",
      "Epoch 62: ReduceLROnPlateau reducing learning rate to 3.4881295869126915e-05.\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.0425 - mse: 0.0304 - mae: 0.0970 - rmse: 0.1667 - custom_mape: 20.2351 - val_loss: 0.0451 - val_mse: 0.0344 - val_mae: 0.1058 - val_rmse: 0.1754 - val_custom_mape: 22.0628 - lr: 1.7441e-04\n",
      "Epoch 63/100\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0409 - mse: 0.0288 - mae: 0.0934 - rmse: 0.1608 - custom_mape: 19.4842 - val_loss: 0.0553 - val_mse: 0.0597 - val_mae: 0.1402 - val_rmse: 0.2277 - val_custom_mape: 24.8888 - lr: 1.7312e-04\n",
      "Epoch 64/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.0392 - mse: 0.0268 - mae: 0.0898 - rmse: 0.1561 - custom_mape: 18.8321 - val_loss: 0.0483 - val_mse: 0.0360 - val_mae: 0.1207 - val_rmse: 0.1853 - val_custom_mape: 30.6992 - lr: 1.7160e-04\n",
      "Epoch 65/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0367 - mse: 0.0234 - mae: 0.0850 - rmse: 0.1474 - custom_mape: 18.5001 - val_loss: 0.0611 - val_mse: 0.0787 - val_mae: 0.1592 - val_rmse: 0.2557 - val_custom_mape: 27.1302 - lr: 1.6985e-04\n",
      "Epoch 66/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0354 - mse: 0.0231 - mae: 0.0835 - rmse: 0.1455 - custom_mape: 18.0659\n",
      "Epoch 66 Detailed Metrics:\n",
      "541/541 [==============================] - 38s 70ms/step - loss: 0.0355 - mse: 0.0231 - mae: 0.0835 - rmse: 0.1456 - custom_mape: 18.1011 - val_loss: 0.0308 - val_mse: 0.0148 - val_mae: 0.0698 - val_rmse: 0.1188 - val_custom_mape: 19.3388 - lr: 1.6787e-04\n",
      "Epoch 67/100\n",
      "541/541 [==============================] - 34s 63ms/step - loss: 0.0379 - mse: 0.0272 - mae: 0.0913 - rmse: 0.1574 - custom_mape: 19.2562 - val_loss: 0.0670 - val_mse: 0.0740 - val_mae: 0.1756 - val_rmse: 0.2696 - val_custom_mape: 35.2934 - lr: 1.6566e-04\n",
      "Epoch 68/100\n",
      "541/541 [==============================] - 36s 66ms/step - loss: 0.0367 - mse: 0.0258 - mae: 0.0874 - rmse: 0.1516 - custom_mape: 18.6506 - val_loss: 0.0364 - val_mse: 0.0239 - val_mae: 0.0878 - val_rmse: 0.1462 - val_custom_mape: 22.8155 - lr: 1.6323e-04\n",
      "Epoch 69/100\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0351 - mse: 0.0232 - mae: 0.0840 - rmse: 0.1458 - custom_mape: 18.4729 - val_loss: 0.0440 - val_mse: 0.0429 - val_mae: 0.1105 - val_rmse: 0.1929 - val_custom_mape: 22.5552 - lr: 1.6060e-04\n",
      "Epoch 70/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.0373 - mse: 0.0266 - mae: 0.0880 - rmse: 0.1523 - custom_mape: 18.6093 - val_loss: 0.0342 - val_mse: 0.0220 - val_mae: 0.0808 - val_rmse: 0.1415 - val_custom_mape: 18.8001 - lr: 1.5776e-04\n",
      "Epoch 71/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0285 - mse: 0.0140 - mae: 0.0653 - rmse: 0.1143 - custom_mape: 15.8762\n",
      "Epoch 71 Detailed Metrics:\n",
      "541/541 [==============================] - 38s 69ms/step - loss: 0.0285 - mse: 0.0140 - mae: 0.0653 - rmse: 0.1142 - custom_mape: 15.8894 - val_loss: 0.0261 - val_mse: 0.0135 - val_mae: 0.0598 - val_rmse: 0.1085 - val_custom_mape: 16.6281 - lr: 1.5473e-04\n",
      "Epoch 72/100\n",
      "541/541 [==============================] - 39s 71ms/step - loss: 0.0314 - mse: 0.0208 - mae: 0.0773 - rmse: 0.1348 - custom_mape: 17.4662 - val_loss: 0.1001 - val_mse: 0.1225 - val_mae: 0.2531 - val_rmse: 0.3373 - val_custom_mape: 45.8354 - lr: 1.5151e-04\n",
      "Epoch 73/100\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.0338 - mse: 0.0232 - mae: 0.0844 - rmse: 0.1457 - custom_mape: 18.5363 - val_loss: 0.0489 - val_mse: 0.0599 - val_mae: 0.1301 - val_rmse: 0.2211 - val_custom_mape: 21.9077 - lr: 1.4811e-04\n",
      "Epoch 74/100\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.0353 - mse: 0.0258 - mae: 0.0890 - rmse: 0.1551 - custom_mape: 18.6775 - val_loss: 0.0340 - val_mse: 0.0259 - val_mae: 0.0851 - val_rmse: 0.1516 - val_custom_mape: 19.9781 - lr: 1.4454e-04\n",
      "Epoch 75/100\n",
      "541/541 [==============================] - 39s 73ms/step - loss: 0.0317 - mse: 0.0205 - mae: 0.0790 - rmse: 0.1372 - custom_mape: 17.6368 - val_loss: 0.0631 - val_mse: 0.0685 - val_mae: 0.1722 - val_rmse: 0.2580 - val_custom_mape: 38.4844 - lr: 1.4082e-04\n",
      "Epoch 76/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0397 - mse: 0.0317 - mae: 0.0969 - rmse: 0.1681 - custom_mape: 19.9562\n",
      "Epoch 76: ReduceLROnPlateau reducing learning rate to 2.738986222539097e-05.\n",
      "\n",
      "Epoch 76 Detailed Metrics:\n",
      "541/541 [==============================] - 38s 71ms/step - loss: 0.0397 - mse: 0.0317 - mae: 0.0969 - rmse: 0.1679 - custom_mape: 19.9689 - val_loss: 0.0408 - val_mse: 0.0323 - val_mae: 0.1042 - val_rmse: 0.1719 - val_custom_mape: 20.9799 - lr: 1.3695e-04\n",
      "Epoch 77/100\n",
      "541/541 [==============================] - 38s 69ms/step - loss: 0.0328 - mse: 0.0208 - mae: 0.0798 - rmse: 0.1392 - custom_mape: 17.8401 - val_loss: 0.0362 - val_mse: 0.0293 - val_mae: 0.0922 - val_rmse: 0.1596 - val_custom_mape: 19.6859 - lr: 1.3294e-04\n",
      "Epoch 78/100\n",
      "541/541 [==============================] - 37s 69ms/step - loss: 0.0295 - mse: 0.0172 - mae: 0.0724 - rmse: 0.1262 - custom_mape: 16.6377 - val_loss: 0.0507 - val_mse: 0.0652 - val_mae: 0.1377 - val_rmse: 0.2239 - val_custom_mape: 21.8391 - lr: 1.2881e-04\n",
      "Epoch 79/100\n",
      "541/541 [==============================] - 39s 73ms/step - loss: 0.0313 - mse: 0.0205 - mae: 0.0789 - rmse: 0.1380 - custom_mape: 17.4685 - val_loss: 0.0287 - val_mse: 0.0193 - val_mae: 0.0717 - val_rmse: 0.1272 - val_custom_mape: 17.1353 - lr: 1.2456e-04\n",
      "Epoch 80/100\n",
      "541/541 [==============================] - 40s 75ms/step - loss: 0.0291 - mse: 0.0180 - mae: 0.0739 - rmse: 0.1289 - custom_mape: 16.8870 - val_loss: 0.0446 - val_mse: 0.0404 - val_mae: 0.1205 - val_rmse: 0.1947 - val_custom_mape: 24.6887 - lr: 1.2022e-04\n",
      "Epoch 81/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0313 - mse: 0.0210 - mae: 0.0805 - rmse: 0.1399 - custom_mape: 17.9034\n",
      "Epoch 81 Detailed Metrics:\n",
      "541/541 [==============================] - 39s 72ms/step - loss: 0.0313 - mse: 0.0210 - mae: 0.0805 - rmse: 0.1398 - custom_mape: 17.9156 - val_loss: 0.0343 - val_mse: 0.0271 - val_mae: 0.0901 - val_rmse: 0.1555 - val_custom_mape: 22.6929 - lr: 1.1578e-04\n",
      "Epoch 82/100\n",
      "541/541 [==============================] - 37s 68ms/step - loss: 0.0279 - mse: 0.0161 - mae: 0.0706 - rmse: 0.1234 - custom_mape: 16.5048 - val_loss: 0.0382 - val_mse: 0.0389 - val_mae: 0.1040 - val_rmse: 0.1719 - val_custom_mape: 18.8728 - lr: 1.1127e-04\n",
      "Epoch 83/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0283 - mse: 0.0175 - mae: 0.0729 - rmse: 0.1278 - custom_mape: 16.6226\n",
      "Epoch 83: ReduceLROnPlateau reducing learning rate to 2.133804955519736e-05.\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0283 - mse: 0.0175 - mae: 0.0729 - rmse: 0.1278 - custom_mape: 16.6437 - val_loss: 0.0371 - val_mse: 0.0295 - val_mae: 0.1006 - val_rmse: 0.1693 - val_custom_mape: 21.9720 - lr: 1.0669e-04\n",
      "Epoch 84/100\n",
      "541/541 [==============================] - 36s 66ms/step - loss: 0.0280 - mse: 0.0170 - mae: 0.0721 - rmse: 0.1260 - custom_mape: 17.0158 - val_loss: 0.0318 - val_mse: 0.0262 - val_mae: 0.0849 - val_rmse: 0.1485 - val_custom_mape: 17.9378 - lr: 1.0206e-04\n",
      "Epoch 85/100\n",
      "541/541 [==============================] - 38s 71ms/step - loss: 0.0278 - mse: 0.0171 - mae: 0.0723 - rmse: 0.1257 - custom_mape: 17.1040 - val_loss: 0.0441 - val_mse: 0.0515 - val_mae: 0.1231 - val_rmse: 0.1994 - val_custom_mape: 20.8031 - lr: 9.7396e-05\n",
      "Epoch 86/100\n",
      "540/541 [============================>.] - ETA: 0s - loss: 0.0282 - mse: 0.0176 - mae: 0.0734 - rmse: 0.1280 - custom_mape: 16.8326Restoring model weights from the end of the best epoch: 71.\n",
      "\n",
      "Epoch 86 Detailed Metrics:\n",
      "541/541 [==============================] - 36s 67ms/step - loss: 0.0282 - mse: 0.0176 - mae: 0.0734 - rmse: 0.1279 - custom_mape: 16.8449 - val_loss: 0.0324 - val_mse: 0.0245 - val_mae: 0.0870 - val_rmse: 0.1518 - val_custom_mape: 19.8808 - lr: 9.2705e-05\n",
      "Epoch 86: early stopping\n",
      "\n",
      "Training completed successfully!\n",
      "\n",
      "Final Model Performance:\n",
      "Out of range predictions: 14036 (54.12%)\n",
      "MAPE: 16.61%\n",
      "Predictions within ±10%: 68.85%\n",
      "MAE: 0.06\n",
      "RMSE: 0.12\n",
      "\n",
      "Training history plot saved as: 2024-11-25_13-52_training_history.png\n",
      "Training history data saved as: 2024-11-25_13-52_training_history.csv\n",
      "Final statistics saved as: 2024-11-25_13-52_training_stats.json\n",
      "\n",
      "Final Training Statistics:\n",
      "Final Loss (train/val): 0.0282/0.0324\n",
      "Final MAE (train/val): 0.0734/0.0870\n",
      "Best validation loss: 0.0261\n",
      "Best validation MAE: 0.0598\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 70904 characters]",
      "text/plain": [
       "<Figure size 1200x400 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Model creation\n",
    "print(\"\\n2. Creating model...\")\n",
    "input_shape = (X_train_seq.shape[1], X_train_seq.shape[2])\n",
    "\n",
    "max_val = df['solarradiation'].max()\n",
    "\n",
    "min_val_scaled = scaler_y.transform([[0]])[0][0]\n",
    "max_val_scaled = scaler_y.transform([[max_val]])[0][0]\n",
    "\n",
    "print(f\"\\nMax dataset solar radiation : {max_val} - Scaled Version : {max_val_scaled}\")\n",
    "\n",
    "increase_percentage = 15\n",
    "\n",
    "max_val = max_val * (1 + increase_percentage / 100)\n",
    "max_val_scaled = max_val_scaled * (1 + increase_percentage / 100)\n",
    "\n",
    "print(f\"Max dataset solar radiation increased by {increase_percentage}% : {max_val} - Scaled Version : {max_val_scaled}\")\n",
    "\n",
    "model = create_solarradiation_model(input_shape=input_shape, folder_name=folder_name, min_output=min_val_scaled, max_output=max_val_scaled)\n",
    "\n",
    "print(\"\\n4. Starting training...\")\n",
    "history = train_hybrid_model(\n",
    "    model=model,\n",
    "    X_train=X_train_seq,\n",
    "    y_train=y_train,\n",
    "    X_test=X_test_seq,\n",
    "    y_test=y_test,\n",
    "    epochs=100,\n",
    "    batch_size=192,\n",
    "    folder_name=folder_name\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ad6226ea-ab01-47aa-9571-52ea9e654c01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "5. Generating predictions...\n",
      "811/811 [==============================] - 9s 10ms/step\n",
      "\n",
      "6. Evaluating model...\n",
      "\n",
      "Solar Radiation Prediction Metrics:\n",
      "\n",
      "Absolute Metrics:\n",
      "MAE: 25.05 W/m²\n",
      "RMSE: 39.70 W/m²\n",
      "R² Score: 0.977\n",
      "MAPE: 20.66%\n",
      "\n",
      "Accuracy Metrics:\n",
      "Within ±5 W/m²: 7.5%\n",
      "Within ±10 W/m²: 13.3%\n",
      "Within ±20 W/m²: 68.6%\n",
      "\n",
      "Level Accuracy:\n",
      "Level Accuracy: 89.0%\n",
      "\n",
      "Confusion Matrix for Radiation Levels:\n",
      "           Very Low   Low  Moderate  High  Very High  Extreme\n",
      "Very Low          0    10         0     0          0        0\n",
      "Low               0  1710         0   111          0        0\n",
      "Moderate          0     0      2171   434          0      256\n",
      "High              0   374       171  1751          0        0\n",
      "Very High         0  1136         0     1          0        0\n",
      "Extreme           0     0       352     0          0    17456\n",
      "\n",
      "Plot saved as: 2024-11-25_13-52_radiation_analysis.png\n",
      "\n",
      "Error Statistics:\n",
      "Mean error: 1.543\n",
      "Error standard deviation: 39.674\n",
      "Median error: 12.000\n",
      "95th percentile absolute error: 86.014\n"
     ]
    }
   ],
   "source": [
    "print(\"\\n5. Generating predictions...\")\n",
    "predictions = model.predict(X_test_seq)\n",
    "predictions = np.clip(predictions, 0, 11)\n",
    "\n",
    "predictions_original = scaler_y.inverse_transform(predictions)\n",
    "y_test_original = scaler_y.inverse_transform(y_test)\n",
    "\n",
    "print(\"\\n6. Evaluating model...\")\n",
    "metrics = evaluate_solarradiation_predictions(y_test_original, predictions_original, folder_name=folder_name)\n",
    "\n",
    "# Create results dictionary\n",
    "training_results = {\n",
    "    'model_params': {\n",
    "        'input_shape': input_shape,\n",
    "        'n_features': len(features),\n",
    "        'sequence_length': X_train_seq.shape[1]\n",
    "    },\n",
    "    'training_params': {\n",
    "        'batch_size': 192,\n",
    "        'total_epochs': len(history.history['loss']),\n",
    "        'best_epoch': np.argmin(history.history['val_loss']) + 1\n",
    "    },\n",
    "    'performance_metrics': {\n",
    "        'final_loss': float(history.history['val_loss'][-1]),\n",
    "        'final_mae': float(history.history['val_mae'][-1]),\n",
    "        'best_val_loss': float(min(history.history['val_loss'])),\n",
    "        'out_of_range_predictions': int(np.sum((predictions < 0) | (predictions > 11)))\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2c42461d-b189-4dc0-81da-4eb4879b9135",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "7. Predicting missing data...\n",
      "7122/7122 [==============================] - 70s 10ms/step\n",
      "\n",
      "8. Integrating predictions into original dataset...\n",
      "Added 227879 predictions to dataset\n",
      "Rows with solar radiation after integration: 357615\n",
      "\n",
      "Training completed successfully!\n"
     ]
    }
   ],
   "source": [
    "print(\"\\n7. Predicting missing data...\")\n",
    "to_predict_predictions = model.predict(X_to_predict_seq)\n",
    "to_predict_predictions = np.clip(to_predict_predictions, 0, 11)\n",
    "\n",
    "to_predict_predictions = scaler_y.inverse_transform(to_predict_predictions)\n",
    "\n",
    "print(\"\\n8. Integrating predictions into original dataset...\")\n",
    "df_updated = integrate_predictions(df.copy(), to_predict_predictions)\n",
    "\n",
    "df_updated.to_parquet('../../sources/weather_data_solarradiation.parquet')\n",
    "\n",
    "# Add prediction statistics to training_results\n",
    "training_results['prediction_stats'] = {\n",
    "    'n_predictions_added': len(to_predict_predictions),\n",
    "    'mean_predicted_solarradiation': float(to_predict_predictions.mean()),\n",
    "    'min_predicted_solarradiation': float(to_predict_predictions.min()),\n",
    "    'max_predicted_solarradiation': float(to_predict_predictions.max()),\n",
    "}\n",
    "\n",
    "print(\"\\nTraining completed successfully!\")\n",
    "\n",
    "tf.keras.backend.clear_session()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "914f7330-d1b9-474d-8605-c0de2aefe087",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 141860 characters]",
      "text/plain": [
       "<Figure size 2000x1200 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 64612 characters]",
      "text/plain": [
       "<Figure size 1500x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 25644 characters]",
      "text/plain": [
       "<Figure size 1200x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Statistiche principali di Solar Radiation:\n",
      "--------------------------------------------------\n",
      "count          : 357,679.0000\n",
      "missing        : 64.0000\n",
      "zeros          : 59,357.0000\n",
      "mean           : 181.9066\n",
      "median         : 12.0000\n",
      "std            : 249.6366\n",
      "min            : 0.0000\n",
      "max            : 1,113.0000\n",
      "skewness       : 1.2630\n",
      "kurtosis       : 0.2932\n",
      "percentile_1   : 0.0000\n",
      "percentile_5   : 0.0000\n",
      "percentile_10  : 0.0000\n",
      "percentile_25  : 12.0000\n",
      "percentile_50  : 12.0000\n",
      "percentile_75  : 316.1503\n",
      "percentile_90  : 630.4008\n",
      "percentile_95  : 727.4549\n",
      "percentile_99  : 862.0000\n",
      "\n",
      "Suggerimenti per la normalizzazione:\n",
      "--------------------------------------------------\n",
      "- La distribuzione è fortemente asimmetrica (skewness > 1)\n",
      "- Considerare una trasformazione logaritmica: np.log1p(x)\n",
      "- Alta presenza di zeri (16.60%)\n",
      "- Considerare un modello in due parti: classificazione degli zeri + regressione sui valori non-zero\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'count': 357679,\n",
       " 'missing': 64,\n",
       " 'zeros': 59357,\n",
       " 'mean': 181.90659489328456,\n",
       " 'median': 12.0,\n",
       " 'std': 249.63664428001422,\n",
       " 'min': 0.0,\n",
       " 'max': 1113.0,\n",
       " 'skewness': 1.262984127717114,\n",
       " 'kurtosis': 0.2932425990070442,\n",
       " 'percentile_1': 0.0,\n",
       " 'percentile_5': 0.0,\n",
       " 'percentile_10': 0.0,\n",
       " 'percentile_25': 12.0,\n",
       " 'percentile_50': 12.0,\n",
       " 'percentile_75': 316.15032958984375,\n",
       " 'percentile_90': 630.4008203125001,\n",
       " 'percentile_95': 727.4549438476562,\n",
       " 'percentile_99': 862.0}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "analyze_distribution(df_updated, 'solarradiation', 'Solar Radiation')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "08fd4208-0afb-4bf1-bdef-b10b4065fe55",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Plot saved as: 2024-11-25_14-57_error_analysis.png\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 161732 characters]",
      "text/plain": [
       "<Figure size 1500x500 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Error Statistics:\n",
      "MAE: 0.0740\n",
      "MSE: 0.0138\n",
      "RMSE: 0.1173\n",
      "Mean error: 0.0046\n",
      "Error std: 0.1172\n",
      "Predictions within ±0.5: 99.2%\n",
      "Predictions within ±1.0: 100.0%\n",
      "Predictions within ±1.5: 100.0%\n",
      "Predictions within ±2.0: 100.0%\n"
     ]
    }
   ],
   "source": [
    "def plot_error_analysis(y_true, y_pred, folder_name=None):\n",
    "    \"\"\"\n",
    "    Function to visualize prediction error analysis\n",
    "\n",
    "    Parameters:\n",
    "    -----------\n",
    "    y_true : array-like\n",
    "        Actual values\n",
    "    y_pred : array-like\n",
    "        Predicted values\n",
    "    folder_name : str, optional\n",
    "        Directory to save plots. If None, plots are only displayed\n",
    "\n",
    "    Generates:\n",
    "    ----------\n",
    "    - Error distribution histogram\n",
    "    - Actual vs Predicted scatter plot\n",
    "    - Errors vs Actual Values scatter plot\n",
    "    - Comprehensive error statistics\n",
    "    \"\"\"\n",
    "\n",
    "    # Convert to 1D numpy arrays if needed\n",
    "    if isinstance(y_true, pd.Series):\n",
    "        y_true = y_true.values\n",
    "    if isinstance(y_pred, pd.Series):\n",
    "        y_pred = y_pred.values\n",
    "\n",
    "    y_true = y_true.ravel()\n",
    "    y_pred = y_pred.ravel()\n",
    "\n",
    "    # Calculate errors\n",
    "    errors = y_pred - y_true\n",
    "\n",
    "    # Create main figure\n",
    "    fig = plt.figure(figsize=(15, 5))\n",
    "\n",
    "    # Plot 1: Error Distribution\n",
    "    plt.subplot(1, 3, 1)\n",
    "    plt.hist(errors, bins=50, alpha=0.7)\n",
    "    plt.title('Prediction Error Distribution')\n",
    "    plt.xlabel('Error')\n",
    "    plt.ylabel('Frequency')\n",
    "\n",
    "    # Plot 2: Actual vs Predicted\n",
    "    plt.subplot(1, 3, 2)\n",
    "    plt.scatter(y_true, y_pred, alpha=0.5)\n",
    "    plt.plot([y_true.min(), y_true.max()], [y_true.min(), y_true.max()], 'r--', lw=2)\n",
    "    plt.title('Actual vs Predicted Values')\n",
    "    plt.xlabel('Actual Values')\n",
    "    plt.ylabel('Predicted Values')\n",
    "\n",
    "    # Plot 3: Errors vs Actual Values\n",
    "    plt.subplot(1, 3, 3)\n",
    "    plt.scatter(y_true, errors, alpha=0.5)\n",
    "    plt.axhline(y=0, color='r', linestyle='--')\n",
    "    plt.title('Errors vs Actual Values')\n",
    "    plt.xlabel('Actual Values')\n",
    "    plt.ylabel('Error')\n",
    "\n",
    "    plt.tight_layout()\n",
    "\n",
    "    # Save plot if directory is specified\n",
    "    if folder_name is not None:\n",
    "        try:\n",
    "            # Create directory if it doesn't exist\n",
    "            filename = f'{folder_name}_error_analysis.png'\n",
    "\n",
    "            # Save figure\n",
    "            plt.savefig(filename, dpi=300, bbox_inches='tight')\n",
    "            print(f\"\\nPlot saved as: {filename}\")\n",
    "        except Exception as e:\n",
    "            print(f\"\\nError saving plot: {str(e)}\")\n",
    "\n",
    "    plt.show()\n",
    "\n",
    "    # Print error statistics\n",
    "    print(\"\\nError Statistics:\")\n",
    "    print(f\"MAE: {np.mean(np.abs(errors)):.4f}\")\n",
    "    print(f\"MSE: {np.mean(errors ** 2):.4f}\")\n",
    "    print(f\"RMSE: {np.sqrt(np.mean(errors ** 2)):.4f}\")\n",
    "    print(f\"Mean error: {np.mean(errors):.4f}\")\n",
    "    print(f\"Error std: {np.std(errors):.4f}\")\n",
    "\n",
    "    # Calculate percentage of errors within thresholds\n",
    "    thresholds = [0.5, 1.0, 1.5, 2.0]\n",
    "    for threshold in thresholds:\n",
    "        within_threshold = np.mean(np.abs(errors) <= threshold) * 100\n",
    "        print(f\"Predictions within ±{threshold}: {within_threshold:.1f}%\")\n",
    "\n",
    "\n",
    "# Example usage\n",
    "plot_error_analysis(y_test, predictions, folder_name=folder_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "846f15d4-d1b2-4a90-a702-b9a85f4e2945",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f982c92c-ba99-4df6-b3c8-df92426679db",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11.0rc1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
